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/AST/ASTConcept.h" 18 #include "clang/AST/ASTFwd.h" 19 #include "clang/AST/Attr.h" 20 #include "clang/AST/Availability.h" 21 #include "clang/AST/ComparisonCategories.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/ExprConcepts.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/ExternalASTSource.h" 30 #include "clang/AST/LocInfoType.h" 31 #include "clang/AST/MangleNumberingContext.h" 32 #include "clang/AST/NSAPI.h" 33 #include "clang/AST/PrettyPrinter.h" 34 #include "clang/AST/StmtCXX.h" 35 #include "clang/AST/TypeLoc.h" 36 #include "clang/AST/TypeOrdering.h" 37 #include "clang/Basic/BitmaskEnum.h" 38 #include "clang/Basic/ExpressionTraits.h" 39 #include "clang/Basic/Module.h" 40 #include "clang/Basic/OpenCLOptions.h" 41 #include "clang/Basic/OpenMPKinds.h" 42 #include "clang/Basic/PragmaKinds.h" 43 #include "clang/Basic/Specifiers.h" 44 #include "clang/Basic/TemplateKinds.h" 45 #include "clang/Basic/TypeTraits.h" 46 #include "clang/Sema/AnalysisBasedWarnings.h" 47 #include "clang/Sema/CleanupInfo.h" 48 #include "clang/Sema/DeclSpec.h" 49 #include "clang/Sema/ExternalSemaSource.h" 50 #include "clang/Sema/IdentifierResolver.h" 51 #include "clang/Sema/ObjCMethodList.h" 52 #include "clang/Sema/Ownership.h" 53 #include "clang/Sema/Scope.h" 54 #include "clang/Sema/SemaConcept.h" 55 #include "clang/Sema/TypoCorrection.h" 56 #include "clang/Sema/Weak.h" 57 #include "llvm/ADT/ArrayRef.h" 58 #include "llvm/ADT/Optional.h" 59 #include "llvm/ADT/SetVector.h" 60 #include "llvm/ADT/SmallBitVector.h" 61 #include "llvm/ADT/SmallPtrSet.h" 62 #include "llvm/ADT/SmallSet.h" 63 #include "llvm/ADT/SmallVector.h" 64 #include "llvm/ADT/TinyPtrVector.h" 65 #include "llvm/Frontend/OpenMP/OMPConstants.h" 66 #include <deque> 67 #include <memory> 68 #include <string> 69 #include <tuple> 70 #include <vector> 71 72 namespace llvm { 73 class APSInt; 74 template <typename ValueT> struct DenseMapInfo; 75 template <typename ValueT, typename ValueInfoT> class DenseSet; 76 class SmallBitVector; 77 struct InlineAsmIdentifierInfo; 78 } 79 80 namespace clang { 81 class ADLResult; 82 class ASTConsumer; 83 class ASTContext; 84 class ASTMutationListener; 85 class ASTReader; 86 class ASTWriter; 87 class ArrayType; 88 class ParsedAttr; 89 class BindingDecl; 90 class BlockDecl; 91 class CapturedDecl; 92 class CXXBasePath; 93 class CXXBasePaths; 94 class CXXBindTemporaryExpr; 95 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; 96 class CXXConstructorDecl; 97 class CXXConversionDecl; 98 class CXXDeleteExpr; 99 class CXXDestructorDecl; 100 class CXXFieldCollector; 101 class CXXMemberCallExpr; 102 class CXXMethodDecl; 103 class CXXScopeSpec; 104 class CXXTemporary; 105 class CXXTryStmt; 106 class CallExpr; 107 class ClassTemplateDecl; 108 class ClassTemplatePartialSpecializationDecl; 109 class ClassTemplateSpecializationDecl; 110 class VarTemplatePartialSpecializationDecl; 111 class CodeCompleteConsumer; 112 class CodeCompletionAllocator; 113 class CodeCompletionTUInfo; 114 class CodeCompletionResult; 115 class CoroutineBodyStmt; 116 class Decl; 117 class DeclAccessPair; 118 class DeclContext; 119 class DeclRefExpr; 120 class DeclaratorDecl; 121 class DeducedTemplateArgument; 122 class DependentDiagnostic; 123 class DesignatedInitExpr; 124 class Designation; 125 class EnableIfAttr; 126 class EnumConstantDecl; 127 class Expr; 128 class ExtVectorType; 129 class FormatAttr; 130 class FriendDecl; 131 class FunctionDecl; 132 class FunctionProtoType; 133 class FunctionTemplateDecl; 134 class ImplicitConversionSequence; 135 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList; 136 class InitListExpr; 137 class InitializationKind; 138 class InitializationSequence; 139 class InitializedEntity; 140 class IntegerLiteral; 141 class LabelStmt; 142 class LambdaExpr; 143 class LangOptions; 144 class LocalInstantiationScope; 145 class LookupResult; 146 class MacroInfo; 147 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath; 148 class ModuleLoader; 149 class MultiLevelTemplateArgumentList; 150 class NamedDecl; 151 class ObjCCategoryDecl; 152 class ObjCCategoryImplDecl; 153 class ObjCCompatibleAliasDecl; 154 class ObjCContainerDecl; 155 class ObjCImplDecl; 156 class ObjCImplementationDecl; 157 class ObjCInterfaceDecl; 158 class ObjCIvarDecl; 159 template <class T> class ObjCList; 160 class ObjCMessageExpr; 161 class ObjCMethodDecl; 162 class ObjCPropertyDecl; 163 class ObjCProtocolDecl; 164 class OMPThreadPrivateDecl; 165 class OMPRequiresDecl; 166 class OMPDeclareReductionDecl; 167 class OMPDeclareSimdDecl; 168 class OMPClause; 169 struct OMPVarListLocTy; 170 struct OverloadCandidate; 171 enum class OverloadCandidateParamOrder : char; 172 enum OverloadCandidateRewriteKind : unsigned; 173 class OverloadCandidateSet; 174 class OverloadExpr; 175 class ParenListExpr; 176 class ParmVarDecl; 177 class Preprocessor; 178 class PseudoDestructorTypeStorage; 179 class PseudoObjectExpr; 180 class QualType; 181 class StandardConversionSequence; 182 class Stmt; 183 class StringLiteral; 184 class SwitchStmt; 185 class TemplateArgument; 186 class TemplateArgumentList; 187 class TemplateArgumentLoc; 188 class TemplateDecl; 189 class TemplateInstantiationCallback; 190 class TemplateParameterList; 191 class TemplatePartialOrderingContext; 192 class TemplateTemplateParmDecl; 193 class Token; 194 class TypeAliasDecl; 195 class TypedefDecl; 196 class TypedefNameDecl; 197 class TypeLoc; 198 class TypoCorrectionConsumer; 199 class UnqualifiedId; 200 class UnresolvedLookupExpr; 201 class UnresolvedMemberExpr; 202 class UnresolvedSetImpl; 203 class UnresolvedSetIterator; 204 class UsingDecl; 205 class UsingShadowDecl; 206 class ValueDecl; 207 class VarDecl; 208 class VarTemplateSpecializationDecl; 209 class VisibilityAttr; 210 class VisibleDeclConsumer; 211 class IndirectFieldDecl; 212 struct DeductionFailureInfo; 213 class TemplateSpecCandidateSet; 214 215 namespace sema { 216 class AccessedEntity; 217 class BlockScopeInfo; 218 class Capture; 219 class CapturedRegionScopeInfo; 220 class CapturingScopeInfo; 221 class CompoundScopeInfo; 222 class DelayedDiagnostic; 223 class DelayedDiagnosticPool; 224 class FunctionScopeInfo; 225 class LambdaScopeInfo; 226 class PossiblyUnreachableDiag; 227 class SemaPPCallbacks; 228 class TemplateDeductionInfo; 229 } 230 231 namespace threadSafety { 232 class BeforeSet; 233 void threadSafetyCleanup(BeforeSet* Cache); 234 } 235 236 // FIXME: No way to easily map from TemplateTypeParmTypes to 237 // TemplateTypeParmDecls, so we have this horrible PointerUnion. 238 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, 239 SourceLocation> UnexpandedParameterPack; 240 241 /// Describes whether we've seen any nullability information for the given 242 /// file. 243 struct FileNullability { 244 /// The first pointer declarator (of any pointer kind) in the file that does 245 /// not have a corresponding nullability annotation. 246 SourceLocation PointerLoc; 247 248 /// The end location for the first pointer declarator in the file. Used for 249 /// placing fix-its. 250 SourceLocation PointerEndLoc; 251 252 /// Which kind of pointer declarator we saw. 253 uint8_t PointerKind; 254 255 /// Whether we saw any type nullability annotations in the given file. 256 bool SawTypeNullability = false; 257 }; 258 259 /// A mapping from file IDs to a record of whether we've seen nullability 260 /// information in that file. 261 class FileNullabilityMap { 262 /// A mapping from file IDs to the nullability information for each file ID. 263 llvm::DenseMap<FileID, FileNullability> Map; 264 265 /// A single-element cache based on the file ID. 266 struct { 267 FileID File; 268 FileNullability Nullability; 269 } Cache; 270 271 public: 272 FileNullability &operator[](FileID file) { 273 // Check the single-element cache. 274 if (file == Cache.File) 275 return Cache.Nullability; 276 277 // It's not in the single-element cache; flush the cache if we have one. 278 if (!Cache.File.isInvalid()) { 279 Map[Cache.File] = Cache.Nullability; 280 } 281 282 // Pull this entry into the cache. 283 Cache.File = file; 284 Cache.Nullability = Map[file]; 285 return Cache.Nullability; 286 } 287 }; 288 289 /// Tracks expected type during expression parsing, for use in code completion. 290 /// The type is tied to a particular token, all functions that update or consume 291 /// the type take a start location of the token they are looking at as a 292 /// parameter. This avoids updating the type on hot paths in the parser. 293 class PreferredTypeBuilder { 294 public: PreferredTypeBuilder(bool Enabled)295 PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {} 296 297 void enterCondition(Sema &S, SourceLocation Tok); 298 void enterReturn(Sema &S, SourceLocation Tok); 299 void enterVariableInit(SourceLocation Tok, Decl *D); 300 /// Handles e.g. BaseType{ .D = Tok... 301 void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType, 302 const Designation &D); 303 /// Computing a type for the function argument may require running 304 /// overloading, so we postpone its computation until it is actually needed. 305 /// 306 /// Clients should be very careful when using this funciton, as it stores a 307 /// function_ref, clients should make sure all calls to get() with the same 308 /// location happen while function_ref is alive. 309 /// 310 /// The callback should also emit signature help as a side-effect, but only 311 /// if the completion point has been reached. 312 void enterFunctionArgument(SourceLocation Tok, 313 llvm::function_ref<QualType()> ComputeType); 314 315 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc); 316 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, 317 SourceLocation OpLoc); 318 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op); 319 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base); 320 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS); 321 /// Handles all type casts, including C-style cast, C++ casts, etc. 322 void enterTypeCast(SourceLocation Tok, QualType CastType); 323 324 /// Get the expected type associated with this location, if any. 325 /// 326 /// If the location is a function argument, determining the expected type 327 /// involves considering all function overloads and the arguments so far. 328 /// In this case, signature help for these function overloads will be reported 329 /// as a side-effect (only if the completion point has been reached). get(SourceLocation Tok)330 QualType get(SourceLocation Tok) const { 331 if (!Enabled || Tok != ExpectedLoc) 332 return QualType(); 333 if (!Type.isNull()) 334 return Type; 335 if (ComputeType) 336 return ComputeType(); 337 return QualType(); 338 } 339 340 private: 341 bool Enabled; 342 /// Start position of a token for which we store expected type. 343 SourceLocation ExpectedLoc; 344 /// Expected type for a token starting at ExpectedLoc. 345 QualType Type; 346 /// A function to compute expected type at ExpectedLoc. It is only considered 347 /// if Type is null. 348 llvm::function_ref<QualType()> ComputeType; 349 }; 350 351 /// Sema - This implements semantic analysis and AST building for C. 352 class Sema final { 353 Sema(const Sema &) = delete; 354 void operator=(const Sema &) = delete; 355 356 ///Source of additional semantic information. 357 ExternalSemaSource *ExternalSource; 358 359 ///Whether Sema has generated a multiplexer and has to delete it. 360 bool isMultiplexExternalSource; 361 362 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); 363 364 bool isVisibleSlow(const NamedDecl *D); 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 = 29; 397 static const unsigned MaximumAlignment = 1u << 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 413 /// Flag indicating whether or not to collect detailed statistics. 414 bool CollectStats; 415 416 /// Code-completion consumer. 417 CodeCompleteConsumer *CodeCompleter; 418 419 /// CurContext - This is the current declaration context of parsing. 420 DeclContext *CurContext; 421 422 /// Generally null except when we temporarily switch decl contexts, 423 /// like in \see ActOnObjCTemporaryExitContainerContext. 424 DeclContext *OriginalLexicalContext; 425 426 /// VAListTagName - The declaration name corresponding to __va_list_tag. 427 /// This is used as part of a hack to omit that class from ADL results. 428 DeclarationName VAListTagName; 429 430 bool MSStructPragmaOn; // True when \#pragma ms_struct on 431 432 /// Controls member pointer representation format under the MS ABI. 433 LangOptions::PragmaMSPointersToMembersKind 434 MSPointerToMemberRepresentationMethod; 435 436 /// Stack of active SEH __finally scopes. Can be empty. 437 SmallVector<Scope*, 2> CurrentSEHFinally; 438 439 /// Source location for newly created implicit MSInheritanceAttrs 440 SourceLocation ImplicitMSInheritanceAttrLoc; 441 442 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by 443 /// `TransformTypos` in order to keep track of any TypoExprs that are created 444 /// recursively during typo correction and wipe them away if the correction 445 /// fails. 446 llvm::SmallVector<TypoExpr *, 2> TypoExprs; 447 448 /// pragma clang section kind 449 enum PragmaClangSectionKind { 450 PCSK_Invalid = 0, 451 PCSK_BSS = 1, 452 PCSK_Data = 2, 453 PCSK_Rodata = 3, 454 PCSK_Text = 4, 455 PCSK_Relro = 5 456 }; 457 458 enum PragmaClangSectionAction { 459 PCSA_Set = 0, 460 PCSA_Clear = 1 461 }; 462 463 struct PragmaClangSection { 464 std::string SectionName; 465 bool Valid = false; 466 SourceLocation PragmaLocation; 467 }; 468 469 PragmaClangSection PragmaClangBSSSection; 470 PragmaClangSection PragmaClangDataSection; 471 PragmaClangSection PragmaClangRodataSection; 472 PragmaClangSection PragmaClangRelroSection; 473 PragmaClangSection PragmaClangTextSection; 474 475 enum PragmaMsStackAction { 476 PSK_Reset = 0x0, // #pragma () 477 PSK_Set = 0x1, // #pragma (value) 478 PSK_Push = 0x2, // #pragma (push[, id]) 479 PSK_Pop = 0x4, // #pragma (pop[, id]) 480 PSK_Show = 0x8, // #pragma (show) -- only for "pack"! 481 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value) 482 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value) 483 }; 484 485 // #pragma pack and align. 486 class AlignPackInfo { 487 public: 488 // `Native` represents default align mode, which may vary based on the 489 // platform. 490 enum Mode : unsigned char { Native, Natural, Packed, Mac68k }; 491 492 // #pragma pack info constructor AlignPackInfo(AlignPackInfo::Mode M,unsigned Num,bool IsXL)493 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL) 494 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) { 495 assert(Num == PackNumber && "The pack number has been truncated."); 496 } 497 498 // #pragma align info constructor AlignPackInfo(AlignPackInfo::Mode M,bool IsXL)499 AlignPackInfo(AlignPackInfo::Mode M, bool IsXL) 500 : PackAttr(false), AlignMode(M), 501 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {} 502 AlignPackInfo(bool IsXL)503 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {} 504 AlignPackInfo()505 AlignPackInfo() : AlignPackInfo(Native, false) {} 506 507 // When a AlignPackInfo itself cannot be used, this returns an 32-bit 508 // integer encoding for it. This should only be passed to 509 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly. getRawEncoding(const AlignPackInfo & Info)510 static uint32_t getRawEncoding(const AlignPackInfo &Info) { 511 std::uint32_t Encoding{}; 512 if (Info.IsXLStack()) 513 Encoding |= IsXLMask; 514 515 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1; 516 517 if (Info.IsPackAttr()) 518 Encoding |= PackAttrMask; 519 520 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4; 521 522 return Encoding; 523 } 524 getFromRawEncoding(unsigned Encoding)525 static AlignPackInfo getFromRawEncoding(unsigned Encoding) { 526 bool IsXL = static_cast<bool>(Encoding & IsXLMask); 527 AlignPackInfo::Mode M = 528 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1); 529 int PackNumber = (Encoding & PackNumMask) >> 4; 530 531 if (Encoding & PackAttrMask) 532 return AlignPackInfo(M, PackNumber, IsXL); 533 534 return AlignPackInfo(M, IsXL); 535 } 536 IsPackAttr()537 bool IsPackAttr() const { return PackAttr; } 538 IsAlignAttr()539 bool IsAlignAttr() const { return !PackAttr; } 540 getAlignMode()541 Mode getAlignMode() const { return AlignMode; } 542 getPackNumber()543 unsigned getPackNumber() const { return PackNumber; } 544 IsPackSet()545 bool IsPackSet() const { 546 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack 547 // attriute on a decl. 548 return PackNumber != UninitPackVal && PackNumber != 0; 549 } 550 IsXLStack()551 bool IsXLStack() const { return XLStack; } 552 553 bool operator==(const AlignPackInfo &Info) const { 554 return std::tie(AlignMode, PackNumber, PackAttr, XLStack) == 555 std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr, 556 Info.XLStack); 557 } 558 559 bool operator!=(const AlignPackInfo &Info) const { 560 return !(*this == Info); 561 } 562 563 private: 564 /// \brief True if this is a pragma pack attribute, 565 /// not a pragma align attribute. 566 bool PackAttr; 567 568 /// \brief The alignment mode that is in effect. 569 Mode AlignMode; 570 571 /// \brief The pack number of the stack. 572 unsigned char PackNumber; 573 574 /// \brief True if it is a XL #pragma align/pack stack. 575 bool XLStack; 576 577 /// \brief Uninitialized pack value. 578 static constexpr unsigned char UninitPackVal = -1; 579 580 // Masks to encode and decode an AlignPackInfo. 581 static constexpr uint32_t IsXLMask{0x0000'0001}; 582 static constexpr uint32_t AlignModeMask{0x0000'0006}; 583 static constexpr uint32_t PackAttrMask{0x00000'0008}; 584 static constexpr uint32_t PackNumMask{0x0000'01F0}; 585 }; 586 587 template<typename ValueType> 588 struct PragmaStack { 589 struct Slot { 590 llvm::StringRef StackSlotLabel; 591 ValueType Value; 592 SourceLocation PragmaLocation; 593 SourceLocation PragmaPushLocation; SlotPragmaStack::Slot594 Slot(llvm::StringRef StackSlotLabel, ValueType Value, 595 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation) 596 : StackSlotLabel(StackSlotLabel), Value(Value), 597 PragmaLocation(PragmaLocation), 598 PragmaPushLocation(PragmaPushLocation) {} 599 }; 600 ActPragmaStack601 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, 602 llvm::StringRef StackSlotLabel, ValueType Value) { 603 if (Action == PSK_Reset) { 604 CurrentValue = DefaultValue; 605 CurrentPragmaLocation = PragmaLocation; 606 return; 607 } 608 if (Action & PSK_Push) 609 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation, 610 PragmaLocation); 611 else if (Action & PSK_Pop) { 612 if (!StackSlotLabel.empty()) { 613 // If we've got a label, try to find it and jump there. 614 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) { 615 return x.StackSlotLabel == StackSlotLabel; 616 }); 617 // If we found the label so pop from there. 618 if (I != Stack.rend()) { 619 CurrentValue = I->Value; 620 CurrentPragmaLocation = I->PragmaLocation; 621 Stack.erase(std::prev(I.base()), Stack.end()); 622 } 623 } else if (!Stack.empty()) { 624 // We do not have a label, just pop the last entry. 625 CurrentValue = Stack.back().Value; 626 CurrentPragmaLocation = Stack.back().PragmaLocation; 627 Stack.pop_back(); 628 } 629 } 630 if (Action & PSK_Set) { 631 CurrentValue = Value; 632 CurrentPragmaLocation = PragmaLocation; 633 } 634 } 635 636 // MSVC seems to add artificial slots to #pragma stacks on entering a C++ 637 // method body to restore the stacks on exit, so it works like this: 638 // 639 // struct S { 640 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>) 641 // void Method {} 642 // #pragma <name>(pop, InternalPragmaSlot) 643 // }; 644 // 645 // It works even with #pragma vtordisp, although MSVC doesn't support 646 // #pragma vtordisp(push [, id], n) 647 // syntax. 648 // 649 // Push / pop a named sentinel slot. SentinelActionPragmaStack650 void SentinelAction(PragmaMsStackAction Action, StringRef Label) { 651 assert((Action == PSK_Push || Action == PSK_Pop) && 652 "Can only push / pop #pragma stack sentinels!"); 653 Act(CurrentPragmaLocation, Action, Label, CurrentValue); 654 } 655 656 // Constructors. PragmaStackPragmaStack657 explicit PragmaStack(const ValueType &Default) 658 : DefaultValue(Default), CurrentValue(Default) {} 659 hasValuePragmaStack660 bool hasValue() const { return CurrentValue != DefaultValue; } 661 662 SmallVector<Slot, 2> Stack; 663 ValueType DefaultValue; // Value used for PSK_Reset action. 664 ValueType CurrentValue; 665 SourceLocation CurrentPragmaLocation; 666 }; 667 // FIXME: We should serialize / deserialize these if they occur in a PCH (but 668 // we shouldn't do so if they're in a module). 669 670 /// Whether to insert vtordisps prior to virtual bases in the Microsoft 671 /// C++ ABI. Possible values are 0, 1, and 2, which mean: 672 /// 673 /// 0: Suppress all vtordisps 674 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial 675 /// structors 676 /// 2: Always insert vtordisps to support RTTI on partially constructed 677 /// objects 678 PragmaStack<MSVtorDispMode> VtorDispStack; 679 PragmaStack<AlignPackInfo> AlignPackStack; 680 // The current #pragma align/pack values and locations at each #include. 681 struct AlignPackIncludeState { 682 AlignPackInfo CurrentValue; 683 SourceLocation CurrentPragmaLocation; 684 bool HasNonDefaultValue, ShouldWarnOnInclude; 685 }; 686 SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack; 687 // Segment #pragmas. 688 PragmaStack<StringLiteral *> DataSegStack; 689 PragmaStack<StringLiteral *> BSSSegStack; 690 PragmaStack<StringLiteral *> ConstSegStack; 691 PragmaStack<StringLiteral *> CodeSegStack; 692 693 // This stack tracks the current state of Sema.CurFPFeatures. 694 PragmaStack<FPOptionsOverride> FpPragmaStack; CurFPFeatureOverrides()695 FPOptionsOverride CurFPFeatureOverrides() { 696 FPOptionsOverride result; 697 if (!FpPragmaStack.hasValue()) { 698 result = FPOptionsOverride(); 699 } else { 700 result = FpPragmaStack.CurrentValue; 701 } 702 return result; 703 } 704 705 // RAII object to push / pop sentinel slots for all MS #pragma stacks. 706 // Actions should be performed only if we enter / exit a C++ method body. 707 class PragmaStackSentinelRAII { 708 public: 709 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct); 710 ~PragmaStackSentinelRAII(); 711 712 private: 713 Sema &S; 714 StringRef SlotLabel; 715 bool ShouldAct; 716 }; 717 718 /// A mapping that describes the nullability we've seen in each header file. 719 FileNullabilityMap NullabilityMap; 720 721 /// Last section used with #pragma init_seg. 722 StringLiteral *CurInitSeg; 723 SourceLocation CurInitSegLoc; 724 725 /// VisContext - Manages the stack for \#pragma GCC visibility. 726 void *VisContext; // Really a "PragmaVisStack*" 727 728 /// This an attribute introduced by \#pragma clang attribute. 729 struct PragmaAttributeEntry { 730 SourceLocation Loc; 731 ParsedAttr *Attribute; 732 SmallVector<attr::SubjectMatchRule, 4> MatchRules; 733 bool IsUsed; 734 }; 735 736 /// A push'd group of PragmaAttributeEntries. 737 struct PragmaAttributeGroup { 738 /// The location of the push attribute. 739 SourceLocation Loc; 740 /// The namespace of this push group. 741 const IdentifierInfo *Namespace; 742 SmallVector<PragmaAttributeEntry, 2> Entries; 743 }; 744 745 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack; 746 747 /// The declaration that is currently receiving an attribute from the 748 /// #pragma attribute stack. 749 const Decl *PragmaAttributeCurrentTargetDecl; 750 751 /// This represents the last location of a "#pragma clang optimize off" 752 /// directive if such a directive has not been closed by an "on" yet. If 753 /// optimizations are currently "on", this is set to an invalid location. 754 SourceLocation OptimizeOffPragmaLocation; 755 756 /// Flag indicating if Sema is building a recovery call expression. 757 /// 758 /// This flag is used to avoid building recovery call expressions 759 /// if Sema is already doing so, which would cause infinite recursions. 760 bool IsBuildingRecoveryCallExpr; 761 762 /// Used to control the generation of ExprWithCleanups. 763 CleanupInfo Cleanup; 764 765 /// ExprCleanupObjects - This is the stack of objects requiring 766 /// cleanup that are created by the current full expression. 767 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects; 768 769 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference 770 /// to a variable (constant) that may or may not be odr-used in this Expr, and 771 /// we won't know until all lvalue-to-rvalue and discarded value conversions 772 /// have been applied to all subexpressions of the enclosing full expression. 773 /// This is cleared at the end of each full expression. 774 using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>, 775 llvm::SmallPtrSet<Expr *, 4>>; 776 MaybeODRUseExprSet MaybeODRUseExprs; 777 778 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope; 779 780 /// Stack containing information about each of the nested 781 /// function, block, and method scopes that are currently active. 782 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; 783 784 /// The index of the first FunctionScope that corresponds to the current 785 /// context. 786 unsigned FunctionScopesStart = 0; 787 getFunctionScopes()788 ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const { 789 return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart, 790 FunctionScopes.end()); 791 } 792 793 /// Stack containing information needed when in C++2a an 'auto' is encountered 794 /// in a function declaration parameter type specifier in order to invent a 795 /// corresponding template parameter in the enclosing abbreviated function 796 /// template. This information is also present in LambdaScopeInfo, stored in 797 /// the FunctionScopes stack. 798 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos; 799 800 /// The index of the first InventedParameterInfo that refers to the current 801 /// context. 802 unsigned InventedParameterInfosStart = 0; 803 getInventedParameterInfos()804 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const { 805 return llvm::makeArrayRef(InventedParameterInfos.begin() + 806 InventedParameterInfosStart, 807 InventedParameterInfos.end()); 808 } 809 810 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, 811 &ExternalSemaSource::ReadExtVectorDecls, 2, 2> 812 ExtVectorDeclsType; 813 814 /// ExtVectorDecls - This is a list all the extended vector types. This allows 815 /// us to associate a raw vector type with one of the ext_vector type names. 816 /// This is only necessary for issuing pretty diagnostics. 817 ExtVectorDeclsType ExtVectorDecls; 818 819 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. 820 std::unique_ptr<CXXFieldCollector> FieldCollector; 821 822 typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType; 823 824 /// Set containing all declared private fields that are not used. 825 NamedDeclSetType UnusedPrivateFields; 826 827 /// Set containing all typedefs that are likely unused. 828 llvm::SmallSetVector<const TypedefNameDecl *, 4> 829 UnusedLocalTypedefNameCandidates; 830 831 /// Delete-expressions to be analyzed at the end of translation unit 832 /// 833 /// This list contains class members, and locations of delete-expressions 834 /// that could not be proven as to whether they mismatch with new-expression 835 /// used in initializer of the field. 836 typedef std::pair<SourceLocation, bool> DeleteExprLoc; 837 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs; 838 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs; 839 840 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; 841 842 /// PureVirtualClassDiagSet - a set of class declarations which we have 843 /// emitted a list of pure virtual functions. Used to prevent emitting the 844 /// same list more than once. 845 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet; 846 847 /// ParsingInitForAutoVars - a set of declarations with auto types for which 848 /// we are currently parsing the initializer. 849 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; 850 851 /// Look for a locally scoped extern "C" declaration by the given name. 852 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name); 853 854 typedef LazyVector<VarDecl *, ExternalSemaSource, 855 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> 856 TentativeDefinitionsType; 857 858 /// All the tentative definitions encountered in the TU. 859 TentativeDefinitionsType TentativeDefinitions; 860 861 /// All the external declarations encoutered and used in the TU. 862 SmallVector<VarDecl *, 4> ExternalDeclarations; 863 864 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, 865 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> 866 UnusedFileScopedDeclsType; 867 868 /// The set of file scoped decls seen so far that have not been used 869 /// and must warn if not used. Only contains the first declaration. 870 UnusedFileScopedDeclsType UnusedFileScopedDecls; 871 872 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, 873 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> 874 DelegatingCtorDeclsType; 875 876 /// All the delegating constructors seen so far in the file, used for 877 /// cycle detection at the end of the TU. 878 DelegatingCtorDeclsType DelegatingCtorDecls; 879 880 /// All the overriding functions seen during a class definition 881 /// that had their exception spec checks delayed, plus the overridden 882 /// function. 883 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2> 884 DelayedOverridingExceptionSpecChecks; 885 886 /// All the function redeclarations seen during a class definition that had 887 /// their exception spec checks delayed, plus the prior declaration they 888 /// should be checked against. Except during error recovery, the new decl 889 /// should always be a friend declaration, as that's the only valid way to 890 /// redeclare a special member before its class is complete. 891 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2> 892 DelayedEquivalentExceptionSpecChecks; 893 894 typedef llvm::MapVector<const FunctionDecl *, 895 std::unique_ptr<LateParsedTemplate>> 896 LateParsedTemplateMapT; 897 LateParsedTemplateMapT LateParsedTemplateMap; 898 899 /// Callback to the parser to parse templated functions when needed. 900 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT); 901 typedef void LateTemplateParserCleanupCB(void *P); 902 LateTemplateParserCB *LateTemplateParser; 903 LateTemplateParserCleanupCB *LateTemplateParserCleanup; 904 void *OpaqueParser; 905 SetLateTemplateParser(LateTemplateParserCB * LTP,LateTemplateParserCleanupCB * LTPCleanup,void * P)906 void SetLateTemplateParser(LateTemplateParserCB *LTP, 907 LateTemplateParserCleanupCB *LTPCleanup, 908 void *P) { 909 LateTemplateParser = LTP; 910 LateTemplateParserCleanup = LTPCleanup; 911 OpaqueParser = P; 912 } 913 914 class DelayedDiagnostics; 915 916 class DelayedDiagnosticsState { 917 sema::DelayedDiagnosticPool *SavedPool; 918 friend class Sema::DelayedDiagnostics; 919 }; 920 typedef DelayedDiagnosticsState ParsingDeclState; 921 typedef DelayedDiagnosticsState ProcessingContextState; 922 923 /// A class which encapsulates the logic for delaying diagnostics 924 /// during parsing and other processing. 925 class DelayedDiagnostics { 926 /// The current pool of diagnostics into which delayed 927 /// diagnostics should go. 928 sema::DelayedDiagnosticPool *CurPool; 929 930 public: DelayedDiagnostics()931 DelayedDiagnostics() : CurPool(nullptr) {} 932 933 /// Adds a delayed diagnostic. 934 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h 935 936 /// Determines whether diagnostics should be delayed. shouldDelayDiagnostics()937 bool shouldDelayDiagnostics() { return CurPool != nullptr; } 938 939 /// Returns the current delayed-diagnostics pool. getCurrentPool()940 sema::DelayedDiagnosticPool *getCurrentPool() const { 941 return CurPool; 942 } 943 944 /// Enter a new scope. Access and deprecation diagnostics will be 945 /// collected in this pool. push(sema::DelayedDiagnosticPool & pool)946 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { 947 DelayedDiagnosticsState state; 948 state.SavedPool = CurPool; 949 CurPool = &pool; 950 return state; 951 } 952 953 /// Leave a delayed-diagnostic state that was previously pushed. 954 /// Do not emit any of the diagnostics. This is performed as part 955 /// of the bookkeeping of popping a pool "properly". popWithoutEmitting(DelayedDiagnosticsState state)956 void popWithoutEmitting(DelayedDiagnosticsState state) { 957 CurPool = state.SavedPool; 958 } 959 960 /// Enter a new scope where access and deprecation diagnostics are 961 /// not delayed. pushUndelayed()962 DelayedDiagnosticsState pushUndelayed() { 963 DelayedDiagnosticsState state; 964 state.SavedPool = CurPool; 965 CurPool = nullptr; 966 return state; 967 } 968 969 /// Undo a previous pushUndelayed(). popUndelayed(DelayedDiagnosticsState state)970 void popUndelayed(DelayedDiagnosticsState state) { 971 assert(CurPool == nullptr); 972 CurPool = state.SavedPool; 973 } 974 } DelayedDiagnostics; 975 976 /// A RAII object to temporarily push a declaration context. 977 class ContextRAII { 978 private: 979 Sema &S; 980 DeclContext *SavedContext; 981 ProcessingContextState SavedContextState; 982 QualType SavedCXXThisTypeOverride; 983 unsigned SavedFunctionScopesStart; 984 unsigned SavedInventedParameterInfosStart; 985 986 public: 987 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) S(S)988 : S(S), SavedContext(S.CurContext), 989 SavedContextState(S.DelayedDiagnostics.pushUndelayed()), 990 SavedCXXThisTypeOverride(S.CXXThisTypeOverride), 991 SavedFunctionScopesStart(S.FunctionScopesStart), 992 SavedInventedParameterInfosStart(S.InventedParameterInfosStart) 993 { 994 assert(ContextToPush && "pushing null context"); 995 S.CurContext = ContextToPush; 996 if (NewThisContext) 997 S.CXXThisTypeOverride = QualType(); 998 // Any saved FunctionScopes do not refer to this context. 999 S.FunctionScopesStart = S.FunctionScopes.size(); 1000 S.InventedParameterInfosStart = S.InventedParameterInfos.size(); 1001 } 1002 pop()1003 void pop() { 1004 if (!SavedContext) return; 1005 S.CurContext = SavedContext; 1006 S.DelayedDiagnostics.popUndelayed(SavedContextState); 1007 S.CXXThisTypeOverride = SavedCXXThisTypeOverride; 1008 S.FunctionScopesStart = SavedFunctionScopesStart; 1009 S.InventedParameterInfosStart = SavedInventedParameterInfosStart; 1010 SavedContext = nullptr; 1011 } 1012 ~ContextRAII()1013 ~ContextRAII() { 1014 pop(); 1015 } 1016 }; 1017 1018 /// Whether the AST is currently being rebuilt to correct immediate 1019 /// invocations. Immediate invocation candidates and references to consteval 1020 /// functions aren't tracked when this is set. 1021 bool RebuildingImmediateInvocation = false; 1022 1023 /// Used to change context to isConstantEvaluated without pushing a heavy 1024 /// ExpressionEvaluationContextRecord object. 1025 bool isConstantEvaluatedOverride; 1026 isConstantEvaluated()1027 bool isConstantEvaluated() { 1028 return ExprEvalContexts.back().isConstantEvaluated() || 1029 isConstantEvaluatedOverride; 1030 } 1031 1032 /// RAII object to handle the state changes required to synthesize 1033 /// a function body. 1034 class SynthesizedFunctionScope { 1035 Sema &S; 1036 Sema::ContextRAII SavedContext; 1037 bool PushedCodeSynthesisContext = false; 1038 1039 public: SynthesizedFunctionScope(Sema & S,DeclContext * DC)1040 SynthesizedFunctionScope(Sema &S, DeclContext *DC) 1041 : S(S), SavedContext(S, DC) { 1042 S.PushFunctionScope(); 1043 S.PushExpressionEvaluationContext( 1044 Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 1045 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 1046 FD->setWillHaveBody(true); 1047 else 1048 assert(isa<ObjCMethodDecl>(DC)); 1049 } 1050 addContextNote(SourceLocation UseLoc)1051 void addContextNote(SourceLocation UseLoc) { 1052 assert(!PushedCodeSynthesisContext); 1053 1054 Sema::CodeSynthesisContext Ctx; 1055 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction; 1056 Ctx.PointOfInstantiation = UseLoc; 1057 Ctx.Entity = cast<Decl>(S.CurContext); 1058 S.pushCodeSynthesisContext(Ctx); 1059 1060 PushedCodeSynthesisContext = true; 1061 } 1062 ~SynthesizedFunctionScope()1063 ~SynthesizedFunctionScope() { 1064 if (PushedCodeSynthesisContext) 1065 S.popCodeSynthesisContext(); 1066 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) 1067 FD->setWillHaveBody(false); 1068 S.PopExpressionEvaluationContext(); 1069 S.PopFunctionScopeInfo(); 1070 } 1071 }; 1072 1073 /// WeakUndeclaredIdentifiers - Identifiers contained in 1074 /// \#pragma weak before declared. rare. may alias another 1075 /// identifier, declared or undeclared 1076 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers; 1077 1078 /// ExtnameUndeclaredIdentifiers - Identifiers contained in 1079 /// \#pragma redefine_extname before declared. Used in Solaris system headers 1080 /// to define functions that occur in multiple standards to call the version 1081 /// in the currently selected standard. 1082 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers; 1083 1084 1085 /// Load weak undeclared identifiers from the external source. 1086 void LoadExternalWeakUndeclaredIdentifiers(); 1087 1088 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by 1089 /// \#pragma weak during processing of other Decls. 1090 /// I couldn't figure out a clean way to generate these in-line, so 1091 /// we store them here and handle separately -- which is a hack. 1092 /// It would be best to refactor this. 1093 SmallVector<Decl*,2> WeakTopLevelDecl; 1094 1095 IdentifierResolver IdResolver; 1096 1097 /// Translation Unit Scope - useful to Objective-C actions that need 1098 /// to lookup file scope declarations in the "ordinary" C decl namespace. 1099 /// For example, user-defined classes, built-in "id" type, etc. 1100 Scope *TUScope; 1101 1102 /// The C++ "std" namespace, where the standard library resides. 1103 LazyDeclPtr StdNamespace; 1104 1105 /// The C++ "std::bad_alloc" class, which is defined by the C++ 1106 /// standard library. 1107 LazyDeclPtr StdBadAlloc; 1108 1109 /// The C++ "std::align_val_t" enum class, which is defined by the C++ 1110 /// standard library. 1111 LazyDeclPtr StdAlignValT; 1112 1113 /// The C++ "std::experimental" namespace, where the experimental parts 1114 /// of the standard library resides. 1115 NamespaceDecl *StdExperimentalNamespaceCache; 1116 1117 /// The C++ "std::initializer_list" template, which is defined in 1118 /// \<initializer_list>. 1119 ClassTemplateDecl *StdInitializerList; 1120 1121 /// The C++ "std::coroutine_traits" template, which is defined in 1122 /// \<coroutine_traits> 1123 ClassTemplateDecl *StdCoroutineTraitsCache; 1124 1125 /// The C++ "type_info" declaration, which is defined in \<typeinfo>. 1126 RecordDecl *CXXTypeInfoDecl; 1127 1128 /// The MSVC "_GUID" struct, which is defined in MSVC header files. 1129 RecordDecl *MSVCGuidDecl; 1130 1131 /// Caches identifiers/selectors for NSFoundation APIs. 1132 std::unique_ptr<NSAPI> NSAPIObj; 1133 1134 /// The declaration of the Objective-C NSNumber class. 1135 ObjCInterfaceDecl *NSNumberDecl; 1136 1137 /// The declaration of the Objective-C NSValue class. 1138 ObjCInterfaceDecl *NSValueDecl; 1139 1140 /// Pointer to NSNumber type (NSNumber *). 1141 QualType NSNumberPointer; 1142 1143 /// Pointer to NSValue type (NSValue *). 1144 QualType NSValuePointer; 1145 1146 /// The Objective-C NSNumber methods used to create NSNumber literals. 1147 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; 1148 1149 /// The declaration of the Objective-C NSString class. 1150 ObjCInterfaceDecl *NSStringDecl; 1151 1152 /// Pointer to NSString type (NSString *). 1153 QualType NSStringPointer; 1154 1155 /// The declaration of the stringWithUTF8String: method. 1156 ObjCMethodDecl *StringWithUTF8StringMethod; 1157 1158 /// The declaration of the valueWithBytes:objCType: method. 1159 ObjCMethodDecl *ValueWithBytesObjCTypeMethod; 1160 1161 /// The declaration of the Objective-C NSArray class. 1162 ObjCInterfaceDecl *NSArrayDecl; 1163 1164 /// The declaration of the arrayWithObjects:count: method. 1165 ObjCMethodDecl *ArrayWithObjectsMethod; 1166 1167 /// The declaration of the Objective-C NSDictionary class. 1168 ObjCInterfaceDecl *NSDictionaryDecl; 1169 1170 /// The declaration of the dictionaryWithObjects:forKeys:count: method. 1171 ObjCMethodDecl *DictionaryWithObjectsMethod; 1172 1173 /// id<NSCopying> type. 1174 QualType QIDNSCopying; 1175 1176 /// will hold 'respondsToSelector:' 1177 Selector RespondsToSelectorSel; 1178 1179 /// A flag to remember whether the implicit forms of operator new and delete 1180 /// have been declared. 1181 bool GlobalNewDeleteDeclared; 1182 1183 /// Describes how the expressions currently being parsed are 1184 /// evaluated at run-time, if at all. 1185 enum class ExpressionEvaluationContext { 1186 /// The current expression and its subexpressions occur within an 1187 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of 1188 /// \c sizeof, where the type of the expression may be significant but 1189 /// no code will be generated to evaluate the value of the expression at 1190 /// run time. 1191 Unevaluated, 1192 1193 /// The current expression occurs within a braced-init-list within 1194 /// an unevaluated operand. This is mostly like a regular unevaluated 1195 /// context, except that we still instantiate constexpr functions that are 1196 /// referenced here so that we can perform narrowing checks correctly. 1197 UnevaluatedList, 1198 1199 /// The current expression occurs within a discarded statement. 1200 /// This behaves largely similarly to an unevaluated operand in preventing 1201 /// definitions from being required, but not in other ways. 1202 DiscardedStatement, 1203 1204 /// The current expression occurs within an unevaluated 1205 /// operand that unconditionally permits abstract references to 1206 /// fields, such as a SIZE operator in MS-style inline assembly. 1207 UnevaluatedAbstract, 1208 1209 /// The current context is "potentially evaluated" in C++11 terms, 1210 /// but the expression is evaluated at compile-time (like the values of 1211 /// cases in a switch statement). 1212 ConstantEvaluated, 1213 1214 /// The current expression is potentially evaluated at run time, 1215 /// which means that code may be generated to evaluate the value of the 1216 /// expression at run time. 1217 PotentiallyEvaluated, 1218 1219 /// The current expression is potentially evaluated, but any 1220 /// declarations referenced inside that expression are only used if 1221 /// in fact the current expression is used. 1222 /// 1223 /// This value is used when parsing default function arguments, for which 1224 /// we would like to provide diagnostics (e.g., passing non-POD arguments 1225 /// through varargs) but do not want to mark declarations as "referenced" 1226 /// until the default argument is used. 1227 PotentiallyEvaluatedIfUsed 1228 }; 1229 1230 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>; 1231 1232 /// Data structure used to record current or nested 1233 /// expression evaluation contexts. 1234 struct ExpressionEvaluationContextRecord { 1235 /// The expression evaluation context. 1236 ExpressionEvaluationContext Context; 1237 1238 /// Whether the enclosing context needed a cleanup. 1239 CleanupInfo ParentCleanup; 1240 1241 /// The number of active cleanup objects when we entered 1242 /// this expression evaluation context. 1243 unsigned NumCleanupObjects; 1244 1245 /// The number of typos encountered during this expression evaluation 1246 /// context (i.e. the number of TypoExprs created). 1247 unsigned NumTypos; 1248 1249 MaybeODRUseExprSet SavedMaybeODRUseExprs; 1250 1251 /// The lambdas that are present within this context, if it 1252 /// is indeed an unevaluated context. 1253 SmallVector<LambdaExpr *, 2> Lambdas; 1254 1255 /// The declaration that provides context for lambda expressions 1256 /// and block literals if the normal declaration context does not 1257 /// suffice, e.g., in a default function argument. 1258 Decl *ManglingContextDecl; 1259 1260 /// If we are processing a decltype type, a set of call expressions 1261 /// for which we have deferred checking the completeness of the return type. 1262 SmallVector<CallExpr *, 8> DelayedDecltypeCalls; 1263 1264 /// If we are processing a decltype type, a set of temporary binding 1265 /// expressions for which we have deferred checking the destructor. 1266 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; 1267 1268 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs; 1269 1270 /// Expressions appearing as the LHS of a volatile assignment in this 1271 /// context. We produce a warning for these when popping the context if 1272 /// they are not discarded-value expressions nor unevaluated operands. 1273 SmallVector<Expr*, 2> VolatileAssignmentLHSs; 1274 1275 /// Set of candidates for starting an immediate invocation. 1276 llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates; 1277 1278 /// Set of DeclRefExprs referencing a consteval function when used in a 1279 /// context not already known to be immediately invoked. 1280 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval; 1281 1282 /// \brief Describes whether we are in an expression constext which we have 1283 /// to handle differently. 1284 enum ExpressionKind { 1285 EK_Decltype, EK_TemplateArgument, EK_Other 1286 } ExprContext; 1287 ExpressionEvaluationContextRecordExpressionEvaluationContextRecord1288 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, 1289 unsigned NumCleanupObjects, 1290 CleanupInfo ParentCleanup, 1291 Decl *ManglingContextDecl, 1292 ExpressionKind ExprContext) 1293 : Context(Context), ParentCleanup(ParentCleanup), 1294 NumCleanupObjects(NumCleanupObjects), NumTypos(0), 1295 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {} 1296 isUnevaluatedExpressionEvaluationContextRecord1297 bool isUnevaluated() const { 1298 return Context == ExpressionEvaluationContext::Unevaluated || 1299 Context == ExpressionEvaluationContext::UnevaluatedAbstract || 1300 Context == ExpressionEvaluationContext::UnevaluatedList; 1301 } isConstantEvaluatedExpressionEvaluationContextRecord1302 bool isConstantEvaluated() const { 1303 return Context == ExpressionEvaluationContext::ConstantEvaluated; 1304 } 1305 }; 1306 1307 /// A stack of expression evaluation contexts. 1308 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; 1309 1310 /// Emit a warning for all pending noderef expressions that we recorded. 1311 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec); 1312 1313 /// Compute the mangling number context for a lambda expression or 1314 /// block literal. Also return the extra mangling decl if any. 1315 /// 1316 /// \param DC - The DeclContext containing the lambda expression or 1317 /// block literal. 1318 std::tuple<MangleNumberingContext *, Decl *> 1319 getCurrentMangleNumberContext(const DeclContext *DC); 1320 1321 1322 /// SpecialMemberOverloadResult - The overloading result for a special member 1323 /// function. 1324 /// 1325 /// This is basically a wrapper around PointerIntPair. The lowest bits of the 1326 /// integer are used to determine whether overload resolution succeeded. 1327 class SpecialMemberOverloadResult { 1328 public: 1329 enum Kind { 1330 NoMemberOrDeleted, 1331 Ambiguous, 1332 Success 1333 }; 1334 1335 private: 1336 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; 1337 1338 public: SpecialMemberOverloadResult()1339 SpecialMemberOverloadResult() : Pair() {} SpecialMemberOverloadResult(CXXMethodDecl * MD)1340 SpecialMemberOverloadResult(CXXMethodDecl *MD) 1341 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {} 1342 getMethod()1343 CXXMethodDecl *getMethod() const { return Pair.getPointer(); } setMethod(CXXMethodDecl * MD)1344 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } 1345 getKind()1346 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } setKind(Kind K)1347 void setKind(Kind K) { Pair.setInt(K); } 1348 }; 1349 1350 class SpecialMemberOverloadResultEntry 1351 : public llvm::FastFoldingSetNode, 1352 public SpecialMemberOverloadResult { 1353 public: SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID & ID)1354 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID) 1355 : FastFoldingSetNode(ID) 1356 {} 1357 }; 1358 1359 /// A cache of special member function overload resolution results 1360 /// for C++ records. 1361 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache; 1362 1363 /// A cache of the flags available in enumerations with the flag_bits 1364 /// attribute. 1365 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache; 1366 1367 /// The kind of translation unit we are processing. 1368 /// 1369 /// When we're processing a complete translation unit, Sema will perform 1370 /// end-of-translation-unit semantic tasks (such as creating 1371 /// initializers for tentative definitions in C) once parsing has 1372 /// completed. Modules and precompiled headers perform different kinds of 1373 /// checks. 1374 TranslationUnitKind TUKind; 1375 1376 llvm::BumpPtrAllocator BumpAlloc; 1377 1378 /// The number of SFINAE diagnostics that have been trapped. 1379 unsigned NumSFINAEErrors; 1380 1381 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>> 1382 UnparsedDefaultArgInstantiationsMap; 1383 1384 /// A mapping from parameters with unparsed default arguments to the 1385 /// set of instantiations of each parameter. 1386 /// 1387 /// This mapping is a temporary data structure used when parsing 1388 /// nested class templates or nested classes of class templates, 1389 /// where we might end up instantiating an inner class before the 1390 /// default arguments of its methods have been parsed. 1391 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; 1392 1393 // Contains the locations of the beginning of unparsed default 1394 // argument locations. 1395 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs; 1396 1397 /// UndefinedInternals - all the used, undefined objects which require a 1398 /// definition in this translation unit. 1399 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed; 1400 1401 /// Determine if VD, which must be a variable or function, is an external 1402 /// symbol that nonetheless can't be referenced from outside this translation 1403 /// unit because its type has no linkage and it's not extern "C". 1404 bool isExternalWithNoLinkageType(ValueDecl *VD); 1405 1406 /// Obtain a sorted list of functions that are undefined but ODR-used. 1407 void getUndefinedButUsed( 1408 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined); 1409 1410 /// Retrieves list of suspicious delete-expressions that will be checked at 1411 /// the end of translation unit. 1412 const llvm::MapVector<FieldDecl *, DeleteLocs> & 1413 getMismatchingDeleteExpressions() const; 1414 1415 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods; 1416 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool; 1417 1418 /// Method Pool - allows efficient lookup when typechecking messages to "id". 1419 /// We need to maintain a list, since selectors can have differing signatures 1420 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% 1421 /// of selectors are "overloaded"). 1422 /// At the head of the list it is recorded whether there were 0, 1, or >= 2 1423 /// methods inside categories with a particular selector. 1424 GlobalMethodPool MethodPool; 1425 1426 /// Method selectors used in a \@selector expression. Used for implementation 1427 /// of -Wselector. 1428 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors; 1429 1430 /// List of SourceLocations where 'self' is implicitly retained inside a 1431 /// block. 1432 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1> 1433 ImplicitlyRetainedSelfLocs; 1434 1435 /// Kinds of C++ special members. 1436 enum CXXSpecialMember { 1437 CXXDefaultConstructor, 1438 CXXCopyConstructor, 1439 CXXMoveConstructor, 1440 CXXCopyAssignment, 1441 CXXMoveAssignment, 1442 CXXDestructor, 1443 CXXInvalid 1444 }; 1445 1446 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember> 1447 SpecialMemberDecl; 1448 1449 /// The C++ special members which we are currently in the process of 1450 /// declaring. If this process recursively triggers the declaration of the 1451 /// same special member, we should act as if it is not yet declared. 1452 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; 1453 1454 /// Kinds of defaulted comparison operator functions. 1455 enum class DefaultedComparisonKind : unsigned char { 1456 /// This is not a defaultable comparison operator. 1457 None, 1458 /// This is an operator== that should be implemented as a series of 1459 /// subobject comparisons. 1460 Equal, 1461 /// This is an operator<=> that should be implemented as a series of 1462 /// subobject comparisons. 1463 ThreeWay, 1464 /// This is an operator!= that should be implemented as a rewrite in terms 1465 /// of a == comparison. 1466 NotEqual, 1467 /// This is an <, <=, >, or >= that should be implemented as a rewrite in 1468 /// terms of a <=> comparison. 1469 Relational, 1470 }; 1471 1472 /// The function definitions which were renamed as part of typo-correction 1473 /// to match their respective declarations. We want to keep track of them 1474 /// to ensure that we don't emit a "redefinition" error if we encounter a 1475 /// correctly named definition after the renamed definition. 1476 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions; 1477 1478 /// Stack of types that correspond to the parameter entities that are 1479 /// currently being copy-initialized. Can be empty. 1480 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes; 1481 1482 void ReadMethodPool(Selector Sel); 1483 void updateOutOfDateSelector(Selector Sel); 1484 1485 /// Private Helper predicate to check for 'self'. 1486 bool isSelfExpr(Expr *RExpr); 1487 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method); 1488 1489 /// Cause the active diagnostic on the DiagosticsEngine to be 1490 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and 1491 /// should not be used elsewhere. 1492 void EmitCurrentDiagnostic(unsigned DiagID); 1493 1494 /// Records and restores the CurFPFeatures state on entry/exit of compound 1495 /// statements. 1496 class FPFeaturesStateRAII { 1497 public: FPFeaturesStateRAII(Sema & S)1498 FPFeaturesStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.CurFPFeatures) { 1499 OldOverrides = S.FpPragmaStack.CurrentValue; 1500 } ~FPFeaturesStateRAII()1501 ~FPFeaturesStateRAII() { 1502 S.CurFPFeatures = OldFPFeaturesState; 1503 S.FpPragmaStack.CurrentValue = OldOverrides; 1504 } getOverrides()1505 FPOptionsOverride getOverrides() { return OldOverrides; } 1506 1507 private: 1508 Sema& S; 1509 FPOptions OldFPFeaturesState; 1510 FPOptionsOverride OldOverrides; 1511 }; 1512 1513 void addImplicitTypedef(StringRef Name, QualType T); 1514 1515 bool WarnedStackExhausted = false; 1516 1517 public: 1518 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 1519 TranslationUnitKind TUKind = TU_Complete, 1520 CodeCompleteConsumer *CompletionConsumer = nullptr); 1521 ~Sema(); 1522 1523 /// Perform initialization that occurs after the parser has been 1524 /// initialized but before it parses anything. 1525 void Initialize(); 1526 1527 /// This virtual key function only exists to limit the emission of debug info 1528 /// describing the Sema class. GCC and Clang only emit debug info for a class 1529 /// with a vtable when the vtable is emitted. Sema is final and not 1530 /// polymorphic, but the debug info size savings are so significant that it is 1531 /// worth adding a vtable just to take advantage of this optimization. 1532 virtual void anchor(); 1533 getLangOpts()1534 const LangOptions &getLangOpts() const { return LangOpts; } getOpenCLOptions()1535 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } getCurFPFeatures()1536 FPOptions &getCurFPFeatures() { return CurFPFeatures; } 1537 getDiagnostics()1538 DiagnosticsEngine &getDiagnostics() const { return Diags; } getSourceManager()1539 SourceManager &getSourceManager() const { return SourceMgr; } getPreprocessor()1540 Preprocessor &getPreprocessor() const { return PP; } getASTContext()1541 ASTContext &getASTContext() const { return Context; } getASTConsumer()1542 ASTConsumer &getASTConsumer() const { return Consumer; } 1543 ASTMutationListener *getASTMutationListener() const; getExternalSource()1544 ExternalSemaSource* getExternalSource() const { return ExternalSource; } 1545 1546 ///Registers an external source. If an external source already exists, 1547 /// creates a multiplex external source and appends to it. 1548 /// 1549 ///\param[in] E - A non-null external sema source. 1550 /// 1551 void addExternalSource(ExternalSemaSource *E); 1552 1553 void PrintStats() const; 1554 1555 /// Warn that the stack is nearly exhausted. 1556 void warnStackExhausted(SourceLocation Loc); 1557 1558 /// Run some code with "sufficient" stack space. (Currently, at least 256K is 1559 /// guaranteed). Produces a warning if we're low on stack space and allocates 1560 /// more in that case. Use this in code that may recurse deeply (for example, 1561 /// in template instantiation) to avoid stack overflow. 1562 void runWithSufficientStackSpace(SourceLocation Loc, 1563 llvm::function_ref<void()> Fn); 1564 1565 /// Helper class that creates diagnostics with optional 1566 /// template instantiation stacks. 1567 /// 1568 /// This class provides a wrapper around the basic DiagnosticBuilder 1569 /// class that emits diagnostics. ImmediateDiagBuilder is 1570 /// responsible for emitting the diagnostic (as DiagnosticBuilder 1571 /// does) and, if the diagnostic comes from inside a template 1572 /// instantiation, printing the template instantiation stack as 1573 /// well. 1574 class ImmediateDiagBuilder : public DiagnosticBuilder { 1575 Sema &SemaRef; 1576 unsigned DiagID; 1577 1578 public: ImmediateDiagBuilder(DiagnosticBuilder & DB,Sema & SemaRef,unsigned DiagID)1579 ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) 1580 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {} ImmediateDiagBuilder(DiagnosticBuilder && DB,Sema & SemaRef,unsigned DiagID)1581 ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID) 1582 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {} 1583 1584 // This is a cunning lie. DiagnosticBuilder actually performs move 1585 // construction in its copy constructor (but due to varied uses, it's not 1586 // possible to conveniently express this as actual move construction). So 1587 // the default copy ctor here is fine, because the base class disables the 1588 // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op 1589 // in that case anwyay. 1590 ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default; 1591 ~ImmediateDiagBuilder()1592 ~ImmediateDiagBuilder() { 1593 // If we aren't active, there is nothing to do. 1594 if (!isActive()) return; 1595 1596 // Otherwise, we need to emit the diagnostic. First clear the diagnostic 1597 // builder itself so it won't emit the diagnostic in its own destructor. 1598 // 1599 // This seems wasteful, in that as written the DiagnosticBuilder dtor will 1600 // do its own needless checks to see if the diagnostic needs to be 1601 // emitted. However, because we take care to ensure that the builder 1602 // objects never escape, a sufficiently smart compiler will be able to 1603 // eliminate that code. 1604 Clear(); 1605 1606 // Dispatch to Sema to emit the diagnostic. 1607 SemaRef.EmitCurrentDiagnostic(DiagID); 1608 } 1609 1610 /// Teach operator<< to produce an object of the correct type. 1611 template <typename T> 1612 friend const ImmediateDiagBuilder & 1613 operator<<(const ImmediateDiagBuilder &Diag, const T &Value) { 1614 const DiagnosticBuilder &BaseDiag = Diag; 1615 BaseDiag << Value; 1616 return Diag; 1617 } 1618 1619 // It is necessary to limit this to rvalue reference to avoid calling this 1620 // function with a bitfield lvalue argument since non-const reference to 1621 // bitfield is not allowed. 1622 template <typename T, typename = typename std::enable_if< 1623 !std::is_lvalue_reference<T>::value>::type> 1624 const ImmediateDiagBuilder &operator<<(T &&V) const { 1625 const DiagnosticBuilder &BaseDiag = *this; 1626 BaseDiag << std::move(V); 1627 return *this; 1628 } 1629 }; 1630 1631 /// A generic diagnostic builder for errors which may or may not be deferred. 1632 /// 1633 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch) 1634 /// which are not allowed to appear inside __device__ functions and are 1635 /// allowed to appear in __host__ __device__ functions only if the host+device 1636 /// function is never codegen'ed. 1637 /// 1638 /// To handle this, we use the notion of "deferred diagnostics", where we 1639 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed. 1640 /// 1641 /// This class lets you emit either a regular diagnostic, a deferred 1642 /// diagnostic, or no diagnostic at all, according to an argument you pass to 1643 /// its constructor, thus simplifying the process of creating these "maybe 1644 /// deferred" diagnostics. 1645 class SemaDiagnosticBuilder { 1646 public: 1647 enum Kind { 1648 /// Emit no diagnostics. 1649 K_Nop, 1650 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()). 1651 K_Immediate, 1652 /// Emit the diagnostic immediately, and, if it's a warning or error, also 1653 /// emit a call stack showing how this function can be reached by an a 1654 /// priori known-emitted function. 1655 K_ImmediateWithCallStack, 1656 /// Create a deferred diagnostic, which is emitted only if the function 1657 /// it's attached to is codegen'ed. Also emit a call stack as with 1658 /// K_ImmediateWithCallStack. 1659 K_Deferred 1660 }; 1661 1662 SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID, 1663 FunctionDecl *Fn, Sema &S); 1664 SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D); 1665 SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default; 1666 ~SemaDiagnosticBuilder(); 1667 isImmediate()1668 bool isImmediate() const { return ImmediateDiag.hasValue(); } 1669 1670 /// Convertible to bool: True if we immediately emitted an error, false if 1671 /// we didn't emit an error or we created a deferred error. 1672 /// 1673 /// Example usage: 1674 /// 1675 /// if (SemaDiagnosticBuilder(...) << foo << bar) 1676 /// return ExprError(); 1677 /// 1678 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably 1679 /// want to use these instead of creating a SemaDiagnosticBuilder yourself. 1680 operator bool() const { return isImmediate(); } 1681 1682 template <typename T> 1683 friend const SemaDiagnosticBuilder & 1684 operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) { 1685 if (Diag.ImmediateDiag.hasValue()) 1686 *Diag.ImmediateDiag << Value; 1687 else if (Diag.PartialDiagId.hasValue()) 1688 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second 1689 << Value; 1690 return Diag; 1691 } 1692 1693 // It is necessary to limit this to rvalue reference to avoid calling this 1694 // function with a bitfield lvalue argument since non-const reference to 1695 // bitfield is not allowed. 1696 template <typename T, typename = typename std::enable_if< 1697 !std::is_lvalue_reference<T>::value>::type> 1698 const SemaDiagnosticBuilder &operator<<(T &&V) const { 1699 if (ImmediateDiag.hasValue()) 1700 *ImmediateDiag << std::move(V); 1701 else if (PartialDiagId.hasValue()) 1702 S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V); 1703 return *this; 1704 } 1705 1706 friend const SemaDiagnosticBuilder & 1707 operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) { 1708 if (Diag.ImmediateDiag.hasValue()) 1709 PD.Emit(*Diag.ImmediateDiag); 1710 else if (Diag.PartialDiagId.hasValue()) 1711 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD; 1712 return Diag; 1713 } 1714 AddFixItHint(const FixItHint & Hint)1715 void AddFixItHint(const FixItHint &Hint) const { 1716 if (ImmediateDiag.hasValue()) 1717 ImmediateDiag->AddFixItHint(Hint); 1718 else if (PartialDiagId.hasValue()) 1719 S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint); 1720 } 1721 ExprError(const SemaDiagnosticBuilder &)1722 friend ExprResult ExprError(const SemaDiagnosticBuilder &) { 1723 return ExprError(); 1724 } StmtError(const SemaDiagnosticBuilder &)1725 friend StmtResult StmtError(const SemaDiagnosticBuilder &) { 1726 return StmtError(); 1727 } ExprResult()1728 operator ExprResult() const { return ExprError(); } StmtResult()1729 operator StmtResult() const { return StmtError(); } TypeResult()1730 operator TypeResult() const { return TypeError(); } DeclResult()1731 operator DeclResult() const { return DeclResult(true); } MemInitResult()1732 operator MemInitResult() const { return MemInitResult(true); } 1733 1734 private: 1735 Sema &S; 1736 SourceLocation Loc; 1737 unsigned DiagID; 1738 FunctionDecl *Fn; 1739 bool ShowCallStack; 1740 1741 // Invariant: At most one of these Optionals has a value. 1742 // FIXME: Switch these to a Variant once that exists. 1743 llvm::Optional<ImmediateDiagBuilder> ImmediateDiag; 1744 llvm::Optional<unsigned> PartialDiagId; 1745 }; 1746 1747 /// Is the last error level diagnostic immediate. This is used to determined 1748 /// whether the next info diagnostic should be immediate. 1749 bool IsLastErrorImmediate = true; 1750 1751 /// Emit a diagnostic. 1752 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, 1753 bool DeferHint = false); 1754 1755 /// Emit a partial diagnostic. 1756 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD, 1757 bool DeferHint = false); 1758 1759 /// Build a partial diagnostic. 1760 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h 1761 1762 /// Whether uncompilable error has occurred. This includes error happens 1763 /// in deferred diagnostics. 1764 bool hasUncompilableErrorOccurred() const; 1765 1766 bool findMacroSpelling(SourceLocation &loc, StringRef name); 1767 1768 /// Get a string to suggest for zero-initialization of a type. 1769 std::string 1770 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const; 1771 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const; 1772 1773 /// Calls \c Lexer::getLocForEndOfToken() 1774 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); 1775 1776 /// Retrieve the module loader associated with the preprocessor. 1777 ModuleLoader &getModuleLoader() const; 1778 1779 /// Invent a new identifier for parameters of abbreviated templates. 1780 IdentifierInfo * 1781 InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName, 1782 unsigned Index); 1783 1784 void emitAndClearUnusedLocalTypedefWarnings(); 1785 1786 private: 1787 /// Function or variable declarations to be checked for whether the deferred 1788 /// diagnostics should be emitted. 1789 llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags; 1790 1791 public: 1792 // Emit all deferred diagnostics. 1793 void emitDeferredDiags(); 1794 1795 enum TUFragmentKind { 1796 /// The global module fragment, between 'module;' and a module-declaration. 1797 Global, 1798 /// A normal translation unit fragment. For a non-module unit, this is the 1799 /// entire translation unit. Otherwise, it runs from the module-declaration 1800 /// to the private-module-fragment (if any) or the end of the TU (if not). 1801 Normal, 1802 /// The private module fragment, between 'module :private;' and the end of 1803 /// the translation unit. 1804 Private 1805 }; 1806 1807 void ActOnStartOfTranslationUnit(); 1808 void ActOnEndOfTranslationUnit(); 1809 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind); 1810 1811 void CheckDelegatingCtorCycles(); 1812 1813 Scope *getScopeForContext(DeclContext *Ctx); 1814 1815 void PushFunctionScope(); 1816 void PushBlockScope(Scope *BlockScope, BlockDecl *Block); 1817 sema::LambdaScopeInfo *PushLambdaScope(); 1818 1819 /// This is used to inform Sema what the current TemplateParameterDepth 1820 /// is during Parsing. Currently it is used to pass on the depth 1821 /// when parsing generic lambda 'auto' parameters. 1822 void RecordParsingTemplateParameterDepth(unsigned Depth); 1823 1824 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, 1825 RecordDecl *RD, CapturedRegionKind K, 1826 unsigned OpenMPCaptureLevel = 0); 1827 1828 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short 1829 /// time after they've been popped. 1830 class PoppedFunctionScopeDeleter { 1831 Sema *Self; 1832 1833 public: PoppedFunctionScopeDeleter(Sema * Self)1834 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {} 1835 void operator()(sema::FunctionScopeInfo *Scope) const; 1836 }; 1837 1838 using PoppedFunctionScopePtr = 1839 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>; 1840 1841 PoppedFunctionScopePtr 1842 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, 1843 const Decl *D = nullptr, 1844 QualType BlockType = QualType()); 1845 getCurFunction()1846 sema::FunctionScopeInfo *getCurFunction() const { 1847 return FunctionScopes.empty() ? nullptr : FunctionScopes.back(); 1848 } 1849 1850 sema::FunctionScopeInfo *getEnclosingFunction() const; 1851 1852 void setFunctionHasBranchIntoScope(); 1853 void setFunctionHasBranchProtectedScope(); 1854 void setFunctionHasIndirectGoto(); 1855 void setFunctionHasMustTail(); 1856 1857 void PushCompoundScope(bool IsStmtExpr); 1858 void PopCompoundScope(); 1859 1860 sema::CompoundScopeInfo &getCurCompoundScope() const; 1861 1862 bool hasAnyUnrecoverableErrorsInThisFunction() const; 1863 1864 /// Retrieve the current block, if any. 1865 sema::BlockScopeInfo *getCurBlock(); 1866 1867 /// Get the innermost lambda enclosing the current location, if any. This 1868 /// looks through intervening non-lambda scopes such as local functions and 1869 /// blocks. 1870 sema::LambdaScopeInfo *getEnclosingLambda() const; 1871 1872 /// Retrieve the current lambda scope info, if any. 1873 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most 1874 /// lambda scope info ignoring all inner capturing scopes that are not 1875 /// lambda scopes. 1876 sema::LambdaScopeInfo * 1877 getCurLambda(bool IgnoreNonLambdaCapturingScope = false); 1878 1879 /// Retrieve the current generic lambda info, if any. 1880 sema::LambdaScopeInfo *getCurGenericLambda(); 1881 1882 /// Retrieve the current captured region, if any. 1883 sema::CapturedRegionScopeInfo *getCurCapturedRegion(); 1884 1885 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls WeakTopLevelDecls()1886 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } 1887 1888 /// Called before parsing a function declarator belonging to a function 1889 /// declaration. 1890 void ActOnStartFunctionDeclarationDeclarator(Declarator &D, 1891 unsigned TemplateParameterDepth); 1892 1893 /// Called after parsing a function declarator belonging to a function 1894 /// declaration. 1895 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D); 1896 1897 void ActOnComment(SourceRange Comment); 1898 1899 //===--------------------------------------------------------------------===// 1900 // Type Analysis / Processing: SemaType.cpp. 1901 // 1902 1903 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, 1904 const DeclSpec *DS = nullptr); 1905 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, 1906 const DeclSpec *DS = nullptr); 1907 QualType BuildPointerType(QualType T, 1908 SourceLocation Loc, DeclarationName Entity); 1909 QualType BuildReferenceType(QualType T, bool LValueRef, 1910 SourceLocation Loc, DeclarationName Entity); 1911 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, 1912 Expr *ArraySize, unsigned Quals, 1913 SourceRange Brackets, DeclarationName Entity); 1914 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc); 1915 QualType BuildExtVectorType(QualType T, Expr *ArraySize, 1916 SourceLocation AttrLoc); 1917 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, 1918 SourceLocation AttrLoc); 1919 1920 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, 1921 SourceLocation AttrLoc); 1922 1923 /// Same as above, but constructs the AddressSpace index if not provided. 1924 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, 1925 SourceLocation AttrLoc); 1926 1927 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc); 1928 1929 bool CheckFunctionReturnType(QualType T, SourceLocation Loc); 1930 1931 /// Build a function type. 1932 /// 1933 /// This routine checks the function type according to C++ rules and 1934 /// under the assumption that the result type and parameter types have 1935 /// just been instantiated from a template. It therefore duplicates 1936 /// some of the behavior of GetTypeForDeclarator, but in a much 1937 /// simpler form that is only suitable for this narrow use case. 1938 /// 1939 /// \param T The return type of the function. 1940 /// 1941 /// \param ParamTypes The parameter types of the function. This array 1942 /// will be modified to account for adjustments to the types of the 1943 /// function parameters. 1944 /// 1945 /// \param Loc The location of the entity whose type involves this 1946 /// function type or, if there is no such entity, the location of the 1947 /// type that will have function type. 1948 /// 1949 /// \param Entity The name of the entity that involves the function 1950 /// type, if known. 1951 /// 1952 /// \param EPI Extra information about the function type. Usually this will 1953 /// be taken from an existing function with the same prototype. 1954 /// 1955 /// \returns A suitable function type, if there are no errors. The 1956 /// unqualified type will always be a FunctionProtoType. 1957 /// Otherwise, returns a NULL type. 1958 QualType BuildFunctionType(QualType T, 1959 MutableArrayRef<QualType> ParamTypes, 1960 SourceLocation Loc, DeclarationName Entity, 1961 const FunctionProtoType::ExtProtoInfo &EPI); 1962 1963 QualType BuildMemberPointerType(QualType T, QualType Class, 1964 SourceLocation Loc, 1965 DeclarationName Entity); 1966 QualType BuildBlockPointerType(QualType T, 1967 SourceLocation Loc, DeclarationName Entity); 1968 QualType BuildParenType(QualType T); 1969 QualType BuildAtomicType(QualType T, SourceLocation Loc); 1970 QualType BuildReadPipeType(QualType T, 1971 SourceLocation Loc); 1972 QualType BuildWritePipeType(QualType T, 1973 SourceLocation Loc); 1974 QualType BuildExtIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc); 1975 1976 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); 1977 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); 1978 1979 /// Package the given type and TSI into a ParsedType. 1980 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); 1981 DeclarationNameInfo GetNameForDeclarator(Declarator &D); 1982 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); 1983 static QualType GetTypeFromParser(ParsedType Ty, 1984 TypeSourceInfo **TInfo = nullptr); 1985 CanThrowResult canThrow(const Stmt *E); 1986 /// Determine whether the callee of a particular function call can throw. 1987 /// E, D and Loc are all optional. 1988 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D, 1989 SourceLocation Loc = SourceLocation()); 1990 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, 1991 const FunctionProtoType *FPT); 1992 void UpdateExceptionSpec(FunctionDecl *FD, 1993 const FunctionProtoType::ExceptionSpecInfo &ESI); 1994 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range); 1995 bool CheckDistantExceptionSpec(QualType T); 1996 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); 1997 bool CheckEquivalentExceptionSpec( 1998 const FunctionProtoType *Old, SourceLocation OldLoc, 1999 const FunctionProtoType *New, SourceLocation NewLoc); 2000 bool CheckEquivalentExceptionSpec( 2001 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, 2002 const FunctionProtoType *Old, SourceLocation OldLoc, 2003 const FunctionProtoType *New, SourceLocation NewLoc); 2004 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType); 2005 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID, 2006 const PartialDiagnostic &NestedDiagID, 2007 const PartialDiagnostic &NoteID, 2008 const PartialDiagnostic &NoThrowDiagID, 2009 const FunctionProtoType *Superset, 2010 SourceLocation SuperLoc, 2011 const FunctionProtoType *Subset, 2012 SourceLocation SubLoc); 2013 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID, 2014 const PartialDiagnostic &NoteID, 2015 const FunctionProtoType *Target, 2016 SourceLocation TargetLoc, 2017 const FunctionProtoType *Source, 2018 SourceLocation SourceLoc); 2019 2020 TypeResult ActOnTypeName(Scope *S, Declarator &D); 2021 2022 /// The parser has parsed the context-sensitive type 'instancetype' 2023 /// in an Objective-C message declaration. Return the appropriate type. 2024 ParsedType ActOnObjCInstanceType(SourceLocation Loc); 2025 2026 /// Abstract class used to diagnose incomplete types. 2027 struct TypeDiagnoser { TypeDiagnoserTypeDiagnoser2028 TypeDiagnoser() {} 2029 2030 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0; ~TypeDiagnoserTypeDiagnoser2031 virtual ~TypeDiagnoser() {} 2032 }; 2033 getPrintable(int I)2034 static int getPrintable(int I) { return I; } getPrintable(unsigned I)2035 static unsigned getPrintable(unsigned I) { return I; } getPrintable(bool B)2036 static bool getPrintable(bool B) { return B; } getPrintable(const char * S)2037 static const char * getPrintable(const char *S) { return S; } getPrintable(StringRef S)2038 static StringRef getPrintable(StringRef S) { return S; } getPrintable(const std::string & S)2039 static const std::string &getPrintable(const std::string &S) { return S; } getPrintable(const IdentifierInfo * II)2040 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) { 2041 return II; 2042 } getPrintable(DeclarationName N)2043 static DeclarationName getPrintable(DeclarationName N) { return N; } getPrintable(QualType T)2044 static QualType getPrintable(QualType T) { return T; } getPrintable(SourceRange R)2045 static SourceRange getPrintable(SourceRange R) { return R; } getPrintable(SourceLocation L)2046 static SourceRange getPrintable(SourceLocation L) { return L; } getPrintable(const Expr * E)2047 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); } getPrintable(TypeLoc TL)2048 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();} 2049 2050 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser { 2051 protected: 2052 unsigned DiagID; 2053 std::tuple<const Ts &...> Args; 2054 2055 template <std::size_t... Is> emit(const SemaDiagnosticBuilder & DB,std::index_sequence<Is...>)2056 void emit(const SemaDiagnosticBuilder &DB, 2057 std::index_sequence<Is...>) const { 2058 // Apply all tuple elements to the builder in order. 2059 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...}; 2060 (void)Dummy; 2061 } 2062 2063 public: BoundTypeDiagnoser(unsigned DiagID,const Ts &...Args)2064 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args) 2065 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) { 2066 assert(DiagID != 0 && "no diagnostic for type diagnoser"); 2067 } 2068 diagnose(Sema & S,SourceLocation Loc,QualType T)2069 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 2070 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID); 2071 emit(DB, std::index_sequence_for<Ts...>()); 2072 DB << T; 2073 } 2074 }; 2075 2076 /// Do a check to make sure \p Name looks like a legal argument for the 2077 /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name 2078 /// is invalid for the given declaration. 2079 /// 2080 /// \p AL is used to provide caret diagnostics in case of a malformed name. 2081 /// 2082 /// \returns true if the name is a valid swift name for \p D, false otherwise. 2083 bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc, 2084 const ParsedAttr &AL, bool IsAsync); 2085 2086 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type 2087 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless. 2088 /// For example, a diagnostic with no other parameters would generally have 2089 /// the form "...%select{incomplete|sizeless}0 type %1...". 2090 template <typename... Ts> 2091 class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> { 2092 public: SizelessTypeDiagnoser(unsigned DiagID,const Ts &...Args)2093 SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args) 2094 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {} 2095 diagnose(Sema & S,SourceLocation Loc,QualType T)2096 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 2097 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID); 2098 this->emit(DB, std::index_sequence_for<Ts...>()); 2099 DB << T->isSizelessType() << T; 2100 } 2101 }; 2102 2103 enum class CompleteTypeKind { 2104 /// Apply the normal rules for complete types. In particular, 2105 /// treat all sizeless types as incomplete. 2106 Normal, 2107 2108 /// Relax the normal rules for complete types so that they include 2109 /// sizeless built-in types. 2110 AcceptSizeless, 2111 2112 // FIXME: Eventually we should flip the default to Normal and opt in 2113 // to AcceptSizeless rather than opt out of it. 2114 Default = AcceptSizeless 2115 }; 2116 2117 private: 2118 /// Methods for marking which expressions involve dereferencing a pointer 2119 /// marked with the 'noderef' attribute. Expressions are checked bottom up as 2120 /// they are parsed, meaning that a noderef pointer may not be accessed. For 2121 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the 2122 /// `*p`, but need to check that `address of` is called on it. This requires 2123 /// keeping a container of all pending expressions and checking if the address 2124 /// of them are eventually taken. 2125 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E); 2126 void CheckAddressOfNoDeref(const Expr *E); 2127 void CheckMemberAccessOfNoDeref(const MemberExpr *E); 2128 2129 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, 2130 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser); 2131 2132 struct ModuleScope { 2133 SourceLocation BeginLoc; 2134 clang::Module *Module = nullptr; 2135 bool ModuleInterface = false; 2136 bool ImplicitGlobalModuleFragment = false; 2137 VisibleModuleSet OuterVisibleModules; 2138 }; 2139 /// The modules we're currently parsing. 2140 llvm::SmallVector<ModuleScope, 16> ModuleScopes; 2141 2142 /// Namespace definitions that we will export when they finish. 2143 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces; 2144 2145 /// Get the module whose scope we are currently within. getCurrentModule()2146 Module *getCurrentModule() const { 2147 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module; 2148 } 2149 2150 VisibleModuleSet VisibleModules; 2151 2152 public: 2153 /// Get the module owning an entity. getOwningModule(const Decl * Entity)2154 Module *getOwningModule(const Decl *Entity) { 2155 return Entity->getOwningModule(); 2156 } 2157 2158 /// Make a merged definition of an existing hidden definition \p ND 2159 /// visible at the specified location. 2160 void makeMergedDefinitionVisible(NamedDecl *ND); 2161 2162 bool isModuleVisible(const Module *M, bool ModulePrivate = false); 2163 2164 // When loading a non-modular PCH files, this is used to restore module 2165 // visibility. makeModuleVisible(Module * Mod,SourceLocation ImportLoc)2166 void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) { 2167 VisibleModules.setVisible(Mod, ImportLoc); 2168 } 2169 2170 /// Determine whether a declaration is visible to name lookup. isVisible(const NamedDecl * D)2171 bool isVisible(const NamedDecl *D) { 2172 return D->isUnconditionallyVisible() || isVisibleSlow(D); 2173 } 2174 2175 /// Determine whether any declaration of an entity is visible. 2176 bool 2177 hasVisibleDeclaration(const NamedDecl *D, 2178 llvm::SmallVectorImpl<Module *> *Modules = nullptr) { 2179 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules); 2180 } 2181 bool hasVisibleDeclarationSlow(const NamedDecl *D, 2182 llvm::SmallVectorImpl<Module *> *Modules); 2183 2184 bool hasVisibleMergedDefinition(NamedDecl *Def); 2185 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def); 2186 2187 /// Determine if \p D and \p Suggested have a structurally compatible 2188 /// layout as described in C11 6.2.7/1. 2189 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested); 2190 2191 /// Determine if \p D has a visible definition. If not, suggest a declaration 2192 /// that should be made visible to expose the definition. 2193 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, 2194 bool OnlyNeedComplete = false); hasVisibleDefinition(const NamedDecl * D)2195 bool hasVisibleDefinition(const NamedDecl *D) { 2196 NamedDecl *Hidden; 2197 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden); 2198 } 2199 2200 /// Determine if the template parameter \p D has a visible default argument. 2201 bool 2202 hasVisibleDefaultArgument(const NamedDecl *D, 2203 llvm::SmallVectorImpl<Module *> *Modules = nullptr); 2204 2205 /// Determine if there is a visible declaration of \p D that is an explicit 2206 /// specialization declaration for a specialization of a template. (For a 2207 /// member specialization, use hasVisibleMemberSpecialization.) 2208 bool hasVisibleExplicitSpecialization( 2209 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); 2210 2211 /// Determine if there is a visible declaration of \p D that is a member 2212 /// specialization declaration (as opposed to an instantiated declaration). 2213 bool hasVisibleMemberSpecialization( 2214 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); 2215 2216 /// Determine if \p A and \p B are equivalent internal linkage declarations 2217 /// from different modules, and thus an ambiguity error can be downgraded to 2218 /// an extension warning. 2219 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 2220 const NamedDecl *B); 2221 void diagnoseEquivalentInternalLinkageDeclarations( 2222 SourceLocation Loc, const NamedDecl *D, 2223 ArrayRef<const NamedDecl *> Equiv); 2224 2225 bool isUsualDeallocationFunction(const CXXMethodDecl *FD); 2226 2227 bool isCompleteType(SourceLocation Loc, QualType T, 2228 CompleteTypeKind Kind = CompleteTypeKind::Default) { 2229 return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr); 2230 } 2231 bool RequireCompleteType(SourceLocation Loc, QualType T, 2232 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser); 2233 bool RequireCompleteType(SourceLocation Loc, QualType T, 2234 CompleteTypeKind Kind, unsigned DiagID); 2235 RequireCompleteType(SourceLocation Loc,QualType T,TypeDiagnoser & Diagnoser)2236 bool RequireCompleteType(SourceLocation Loc, QualType T, 2237 TypeDiagnoser &Diagnoser) { 2238 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser); 2239 } RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID)2240 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) { 2241 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID); 2242 } 2243 2244 template <typename... Ts> RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)2245 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, 2246 const Ts &...Args) { 2247 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 2248 return RequireCompleteType(Loc, T, Diagnoser); 2249 } 2250 2251 template <typename... Ts> RequireCompleteSizedType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)2252 bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, 2253 const Ts &... Args) { 2254 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 2255 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser); 2256 } 2257 2258 /// Get the type of expression E, triggering instantiation to complete the 2259 /// type if necessary -- that is, if the expression refers to a templated 2260 /// static data member of incomplete array type. 2261 /// 2262 /// May still return an incomplete type if instantiation was not possible or 2263 /// if the type is incomplete for a different reason. Use 2264 /// RequireCompleteExprType instead if a diagnostic is expected for an 2265 /// incomplete expression type. 2266 QualType getCompletedType(Expr *E); 2267 2268 void completeExprArrayBound(Expr *E); 2269 bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, 2270 TypeDiagnoser &Diagnoser); 2271 bool RequireCompleteExprType(Expr *E, unsigned DiagID); 2272 2273 template <typename... Ts> RequireCompleteExprType(Expr * E,unsigned DiagID,const Ts &...Args)2274 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) { 2275 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 2276 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser); 2277 } 2278 2279 template <typename... Ts> RequireCompleteSizedExprType(Expr * E,unsigned DiagID,const Ts &...Args)2280 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, 2281 const Ts &... Args) { 2282 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 2283 return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser); 2284 } 2285 2286 bool RequireLiteralType(SourceLocation Loc, QualType T, 2287 TypeDiagnoser &Diagnoser); 2288 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); 2289 2290 template <typename... Ts> RequireLiteralType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)2291 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, 2292 const Ts &...Args) { 2293 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 2294 return RequireLiteralType(Loc, T, Diagnoser); 2295 } 2296 2297 QualType getElaboratedType(ElaboratedTypeKeyword Keyword, 2298 const CXXScopeSpec &SS, QualType T, 2299 TagDecl *OwnedTagDecl = nullptr); 2300 2301 QualType getDecltypeForParenthesizedExpr(Expr *E); 2302 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc); 2303 /// If AsUnevaluated is false, E is treated as though it were an evaluated 2304 /// context, such as when building a type for decltype(auto). 2305 QualType BuildDecltypeType(Expr *E, SourceLocation Loc, 2306 bool AsUnevaluated = true); 2307 QualType BuildUnaryTransformType(QualType BaseType, 2308 UnaryTransformType::UTTKind UKind, 2309 SourceLocation Loc); 2310 2311 //===--------------------------------------------------------------------===// 2312 // Symbol table / Decl tracking callbacks: SemaDecl.cpp. 2313 // 2314 2315 struct SkipBodyInfo { SkipBodyInfoSkipBodyInfo2316 SkipBodyInfo() 2317 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr), 2318 New(nullptr) {} 2319 bool ShouldSkip; 2320 bool CheckSameAsPrevious; 2321 NamedDecl *Previous; 2322 NamedDecl *New; 2323 }; 2324 2325 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); 2326 2327 void DiagnoseUseOfUnimplementedSelectors(); 2328 2329 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const; 2330 2331 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 2332 Scope *S, CXXScopeSpec *SS = nullptr, 2333 bool isClassName = false, bool HasTrailingDot = false, 2334 ParsedType ObjectType = nullptr, 2335 bool IsCtorOrDtorName = false, 2336 bool WantNontrivialTypeSourceInfo = false, 2337 bool IsClassTemplateDeductionContext = true, 2338 IdentifierInfo **CorrectedII = nullptr); 2339 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); 2340 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); 2341 void DiagnoseUnknownTypeName(IdentifierInfo *&II, 2342 SourceLocation IILoc, 2343 Scope *S, 2344 CXXScopeSpec *SS, 2345 ParsedType &SuggestedType, 2346 bool IsTemplateName = false); 2347 2348 /// Attempt to behave like MSVC in situations where lookup of an unqualified 2349 /// type name has failed in a dependent context. In these situations, we 2350 /// automatically form a DependentTypeName that will retry lookup in a related 2351 /// scope during instantiation. 2352 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 2353 SourceLocation NameLoc, 2354 bool IsTemplateTypeArg); 2355 2356 /// Describes the result of the name lookup and resolution performed 2357 /// by \c ClassifyName(). 2358 enum NameClassificationKind { 2359 /// This name is not a type or template in this context, but might be 2360 /// something else. 2361 NC_Unknown, 2362 /// Classification failed; an error has been produced. 2363 NC_Error, 2364 /// The name has been typo-corrected to a keyword. 2365 NC_Keyword, 2366 /// The name was classified as a type. 2367 NC_Type, 2368 /// The name was classified as a specific non-type, non-template 2369 /// declaration. ActOnNameClassifiedAsNonType should be called to 2370 /// convert the declaration to an expression. 2371 NC_NonType, 2372 /// The name was classified as an ADL-only function name. 2373 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the 2374 /// result to an expression. 2375 NC_UndeclaredNonType, 2376 /// The name denotes a member of a dependent type that could not be 2377 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to 2378 /// convert the result to an expression. 2379 NC_DependentNonType, 2380 /// The name was classified as an overload set, and an expression 2381 /// representing that overload set has been formed. 2382 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable 2383 /// expression referencing the overload set. 2384 NC_OverloadSet, 2385 /// The name was classified as a template whose specializations are types. 2386 NC_TypeTemplate, 2387 /// The name was classified as a variable template name. 2388 NC_VarTemplate, 2389 /// The name was classified as a function template name. 2390 NC_FunctionTemplate, 2391 /// The name was classified as an ADL-only function template name. 2392 NC_UndeclaredTemplate, 2393 /// The name was classified as a concept name. 2394 NC_Concept, 2395 }; 2396 2397 class NameClassification { 2398 NameClassificationKind Kind; 2399 union { 2400 ExprResult Expr; 2401 NamedDecl *NonTypeDecl; 2402 TemplateName Template; 2403 ParsedType Type; 2404 }; 2405 NameClassification(NameClassificationKind Kind)2406 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} 2407 2408 public: NameClassification(ParsedType Type)2409 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} 2410 NameClassification(const IdentifierInfo * Keyword)2411 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {} 2412 Error()2413 static NameClassification Error() { 2414 return NameClassification(NC_Error); 2415 } 2416 Unknown()2417 static NameClassification Unknown() { 2418 return NameClassification(NC_Unknown); 2419 } 2420 OverloadSet(ExprResult E)2421 static NameClassification OverloadSet(ExprResult E) { 2422 NameClassification Result(NC_OverloadSet); 2423 Result.Expr = E; 2424 return Result; 2425 } 2426 NonType(NamedDecl * D)2427 static NameClassification NonType(NamedDecl *D) { 2428 NameClassification Result(NC_NonType); 2429 Result.NonTypeDecl = D; 2430 return Result; 2431 } 2432 UndeclaredNonType()2433 static NameClassification UndeclaredNonType() { 2434 return NameClassification(NC_UndeclaredNonType); 2435 } 2436 DependentNonType()2437 static NameClassification DependentNonType() { 2438 return NameClassification(NC_DependentNonType); 2439 } 2440 TypeTemplate(TemplateName Name)2441 static NameClassification TypeTemplate(TemplateName Name) { 2442 NameClassification Result(NC_TypeTemplate); 2443 Result.Template = Name; 2444 return Result; 2445 } 2446 VarTemplate(TemplateName Name)2447 static NameClassification VarTemplate(TemplateName Name) { 2448 NameClassification Result(NC_VarTemplate); 2449 Result.Template = Name; 2450 return Result; 2451 } 2452 FunctionTemplate(TemplateName Name)2453 static NameClassification FunctionTemplate(TemplateName Name) { 2454 NameClassification Result(NC_FunctionTemplate); 2455 Result.Template = Name; 2456 return Result; 2457 } 2458 Concept(TemplateName Name)2459 static NameClassification Concept(TemplateName Name) { 2460 NameClassification Result(NC_Concept); 2461 Result.Template = Name; 2462 return Result; 2463 } 2464 UndeclaredTemplate(TemplateName Name)2465 static NameClassification UndeclaredTemplate(TemplateName Name) { 2466 NameClassification Result(NC_UndeclaredTemplate); 2467 Result.Template = Name; 2468 return Result; 2469 } 2470 getKind()2471 NameClassificationKind getKind() const { return Kind; } 2472 getExpression()2473 ExprResult getExpression() const { 2474 assert(Kind == NC_OverloadSet); 2475 return Expr; 2476 } 2477 getType()2478 ParsedType getType() const { 2479 assert(Kind == NC_Type); 2480 return Type; 2481 } 2482 getNonTypeDecl()2483 NamedDecl *getNonTypeDecl() const { 2484 assert(Kind == NC_NonType); 2485 return NonTypeDecl; 2486 } 2487 getTemplateName()2488 TemplateName getTemplateName() const { 2489 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || 2490 Kind == NC_VarTemplate || Kind == NC_Concept || 2491 Kind == NC_UndeclaredTemplate); 2492 return Template; 2493 } 2494 getTemplateNameKind()2495 TemplateNameKind getTemplateNameKind() const { 2496 switch (Kind) { 2497 case NC_TypeTemplate: 2498 return TNK_Type_template; 2499 case NC_FunctionTemplate: 2500 return TNK_Function_template; 2501 case NC_VarTemplate: 2502 return TNK_Var_template; 2503 case NC_Concept: 2504 return TNK_Concept_template; 2505 case NC_UndeclaredTemplate: 2506 return TNK_Undeclared_template; 2507 default: 2508 llvm_unreachable("unsupported name classification."); 2509 } 2510 } 2511 }; 2512 2513 /// Perform name lookup on the given name, classifying it based on 2514 /// the results of name lookup and the following token. 2515 /// 2516 /// This routine is used by the parser to resolve identifiers and help direct 2517 /// parsing. When the identifier cannot be found, this routine will attempt 2518 /// to correct the typo and classify based on the resulting name. 2519 /// 2520 /// \param S The scope in which we're performing name lookup. 2521 /// 2522 /// \param SS The nested-name-specifier that precedes the name. 2523 /// 2524 /// \param Name The identifier. If typo correction finds an alternative name, 2525 /// this pointer parameter will be updated accordingly. 2526 /// 2527 /// \param NameLoc The location of the identifier. 2528 /// 2529 /// \param NextToken The token following the identifier. Used to help 2530 /// disambiguate the name. 2531 /// 2532 /// \param CCC The correction callback, if typo correction is desired. 2533 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, 2534 IdentifierInfo *&Name, SourceLocation NameLoc, 2535 const Token &NextToken, 2536 CorrectionCandidateCallback *CCC = nullptr); 2537 2538 /// Act on the result of classifying a name as an undeclared (ADL-only) 2539 /// non-type declaration. 2540 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 2541 SourceLocation NameLoc); 2542 /// Act on the result of classifying a name as an undeclared member of a 2543 /// dependent base class. 2544 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 2545 IdentifierInfo *Name, 2546 SourceLocation NameLoc, 2547 bool IsAddressOfOperand); 2548 /// Act on the result of classifying a name as a specific non-type 2549 /// declaration. 2550 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 2551 NamedDecl *Found, 2552 SourceLocation NameLoc, 2553 const Token &NextToken); 2554 /// Act on the result of classifying a name as an overload set. 2555 ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet); 2556 2557 /// Describes the detailed kind of a template name. Used in diagnostics. 2558 enum class TemplateNameKindForDiagnostics { 2559 ClassTemplate, 2560 FunctionTemplate, 2561 VarTemplate, 2562 AliasTemplate, 2563 TemplateTemplateParam, 2564 Concept, 2565 DependentTemplate 2566 }; 2567 TemplateNameKindForDiagnostics 2568 getTemplateNameKindForDiagnostics(TemplateName Name); 2569 2570 /// Determine whether it's plausible that E was intended to be a 2571 /// template-name. mightBeIntendedToBeTemplateName(ExprResult E,bool & Dependent)2572 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) { 2573 if (!getLangOpts().CPlusPlus || E.isInvalid()) 2574 return false; 2575 Dependent = false; 2576 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get())) 2577 return !DRE->hasExplicitTemplateArgs(); 2578 if (auto *ME = dyn_cast<MemberExpr>(E.get())) 2579 return !ME->hasExplicitTemplateArgs(); 2580 Dependent = true; 2581 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get())) 2582 return !DSDRE->hasExplicitTemplateArgs(); 2583 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get())) 2584 return !DSME->hasExplicitTemplateArgs(); 2585 // Any additional cases recognized here should also be handled by 2586 // diagnoseExprIntendedAsTemplateName. 2587 return false; 2588 } 2589 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, 2590 SourceLocation Less, 2591 SourceLocation Greater); 2592 2593 void warnOnReservedIdentifier(const NamedDecl *D); 2594 2595 Decl *ActOnDeclarator(Scope *S, Declarator &D); 2596 2597 NamedDecl *HandleDeclarator(Scope *S, Declarator &D, 2598 MultiTemplateParamsArg TemplateParameterLists); 2599 bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, 2600 QualType &T, SourceLocation Loc, 2601 unsigned FailedFoldDiagID); 2602 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S); 2603 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); 2604 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 2605 DeclarationName Name, SourceLocation Loc, 2606 bool IsTemplateId); 2607 void 2608 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, 2609 SourceLocation FallbackLoc, 2610 SourceLocation ConstQualLoc = SourceLocation(), 2611 SourceLocation VolatileQualLoc = SourceLocation(), 2612 SourceLocation RestrictQualLoc = SourceLocation(), 2613 SourceLocation AtomicQualLoc = SourceLocation(), 2614 SourceLocation UnalignedQualLoc = SourceLocation()); 2615 2616 static bool adjustContextForLocalExternDecl(DeclContext *&DC); 2617 void DiagnoseFunctionSpecifiers(const DeclSpec &DS); 2618 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D, 2619 const LookupResult &R); 2620 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R); 2621 NamedDecl *getShadowedDeclaration(const BindingDecl *D, 2622 const LookupResult &R); 2623 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 2624 const LookupResult &R); 2625 void CheckShadow(Scope *S, VarDecl *D); 2626 2627 /// Warn if 'E', which is an expression that is about to be modified, refers 2628 /// to a shadowing declaration. 2629 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc); 2630 2631 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI); 2632 2633 private: 2634 /// Map of current shadowing declarations to shadowed declarations. Warn if 2635 /// it looks like the user is trying to modify the shadowing declaration. 2636 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls; 2637 2638 public: 2639 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); 2640 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope); 2641 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 2642 TypedefNameDecl *NewTD); 2643 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); 2644 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 2645 TypeSourceInfo *TInfo, 2646 LookupResult &Previous); 2647 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, 2648 LookupResult &Previous, bool &Redeclaration); 2649 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 2650 TypeSourceInfo *TInfo, 2651 LookupResult &Previous, 2652 MultiTemplateParamsArg TemplateParamLists, 2653 bool &AddToScope, 2654 ArrayRef<BindingDecl *> Bindings = None); 2655 NamedDecl * 2656 ActOnDecompositionDeclarator(Scope *S, Declarator &D, 2657 MultiTemplateParamsArg TemplateParamLists); 2658 // Returns true if the variable declaration is a redeclaration 2659 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); 2660 void CheckVariableDeclarationType(VarDecl *NewVD); 2661 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 2662 Expr *Init); 2663 void CheckCompleteVariableDeclaration(VarDecl *VD); 2664 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD); 2665 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); 2666 2667 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, 2668 TypeSourceInfo *TInfo, 2669 LookupResult &Previous, 2670 MultiTemplateParamsArg TemplateParamLists, 2671 bool &AddToScope); 2672 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); 2673 2674 enum class CheckConstexprKind { 2675 /// Diagnose issues that are non-constant or that are extensions. 2676 Diagnose, 2677 /// Identify whether this function satisfies the formal rules for constexpr 2678 /// functions in the current lanugage mode (with no extensions). 2679 CheckValid 2680 }; 2681 2682 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, 2683 CheckConstexprKind Kind); 2684 2685 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); 2686 void FindHiddenVirtualMethods(CXXMethodDecl *MD, 2687 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); 2688 void NoteHiddenVirtualMethods(CXXMethodDecl *MD, 2689 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); 2690 // Returns true if the function declaration is a redeclaration 2691 bool CheckFunctionDeclaration(Scope *S, 2692 FunctionDecl *NewFD, LookupResult &Previous, 2693 bool IsMemberSpecialization); 2694 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl); 2695 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 2696 QualType NewT, QualType OldT); 2697 void CheckMain(FunctionDecl *FD, const DeclSpec &D); 2698 void CheckMSVCRTEntryPoint(FunctionDecl *FD); 2699 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 2700 bool IsDefinition); 2701 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D); 2702 Decl *ActOnParamDeclarator(Scope *S, Declarator &D); 2703 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, 2704 SourceLocation Loc, 2705 QualType T); 2706 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, 2707 SourceLocation NameLoc, IdentifierInfo *Name, 2708 QualType T, TypeSourceInfo *TSInfo, 2709 StorageClass SC); 2710 void ActOnParamDefaultArgument(Decl *param, 2711 SourceLocation EqualLoc, 2712 Expr *defarg); 2713 void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, 2714 SourceLocation ArgLoc); 2715 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc); 2716 ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, 2717 SourceLocation EqualLoc); 2718 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, 2719 SourceLocation EqualLoc); 2720 2721 // Contexts where using non-trivial C union types can be disallowed. This is 2722 // passed to err_non_trivial_c_union_in_invalid_context. 2723 enum NonTrivialCUnionContext { 2724 // Function parameter. 2725 NTCUC_FunctionParam, 2726 // Function return. 2727 NTCUC_FunctionReturn, 2728 // Default-initialized object. 2729 NTCUC_DefaultInitializedObject, 2730 // Variable with automatic storage duration. 2731 NTCUC_AutoVar, 2732 // Initializer expression that might copy from another object. 2733 NTCUC_CopyInit, 2734 // Assignment. 2735 NTCUC_Assignment, 2736 // Compound literal. 2737 NTCUC_CompoundLiteral, 2738 // Block capture. 2739 NTCUC_BlockCapture, 2740 // lvalue-to-rvalue conversion of volatile type. 2741 NTCUC_LValueToRValueVolatile, 2742 }; 2743 2744 /// Emit diagnostics if the initializer or any of its explicit or 2745 /// implicitly-generated subexpressions require copying or 2746 /// default-initializing a type that is or contains a C union type that is 2747 /// non-trivial to copy or default-initialize. 2748 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc); 2749 2750 // These flags are passed to checkNonTrivialCUnion. 2751 enum NonTrivialCUnionKind { 2752 NTCUK_Init = 0x1, 2753 NTCUK_Destruct = 0x2, 2754 NTCUK_Copy = 0x4, 2755 }; 2756 2757 /// Emit diagnostics if a non-trivial C union type or a struct that contains 2758 /// a non-trivial C union is used in an invalid context. 2759 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 2760 NonTrivialCUnionContext UseContext, 2761 unsigned NonTrivialKind); 2762 2763 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit); 2764 void ActOnUninitializedDecl(Decl *dcl); 2765 void ActOnInitializerError(Decl *Dcl); 2766 2767 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc); 2768 void ActOnCXXForRangeDecl(Decl *D); 2769 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 2770 IdentifierInfo *Ident, 2771 ParsedAttributes &Attrs, 2772 SourceLocation AttrEnd); 2773 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); 2774 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); 2775 void CheckStaticLocalForDllExport(VarDecl *VD); 2776 void FinalizeDeclaration(Decl *D); 2777 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 2778 ArrayRef<Decl *> Group); 2779 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group); 2780 2781 /// Should be called on all declarations that might have attached 2782 /// documentation comments. 2783 void ActOnDocumentableDecl(Decl *D); 2784 void ActOnDocumentableDecls(ArrayRef<Decl *> Group); 2785 2786 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 2787 SourceLocation LocAfterDecls); 2788 void CheckForFunctionRedefinition( 2789 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr, 2790 SkipBodyInfo *SkipBody = nullptr); 2791 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D, 2792 MultiTemplateParamsArg TemplateParamLists, 2793 SkipBodyInfo *SkipBody = nullptr); 2794 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D, 2795 SkipBodyInfo *SkipBody = nullptr); 2796 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D); 2797 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr); 2798 ExprResult ActOnRequiresClause(ExprResult ConstraintExpr); 2799 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); isObjCMethodDecl(Decl * D)2800 bool isObjCMethodDecl(Decl *D) { 2801 return D && isa<ObjCMethodDecl>(D); 2802 } 2803 2804 /// Determine whether we can delay parsing the body of a function or 2805 /// function template until it is used, assuming we don't care about emitting 2806 /// code for that function. 2807 /// 2808 /// This will be \c false if we may need the body of the function in the 2809 /// middle of parsing an expression (where it's impractical to switch to 2810 /// parsing a different function), for instance, if it's constexpr in C++11 2811 /// or has an 'auto' return type in C++14. These cases are essentially bugs. 2812 bool canDelayFunctionBody(const Declarator &D); 2813 2814 /// Determine whether we can skip parsing the body of a function 2815 /// definition, assuming we don't care about analyzing its body or emitting 2816 /// code for that function. 2817 /// 2818 /// This will be \c false only if we may need the body of the function in 2819 /// order to parse the rest of the program (for instance, if it is 2820 /// \c constexpr in C++11 or has an 'auto' return type in C++14). 2821 bool canSkipFunctionBody(Decl *D); 2822 2823 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); 2824 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); 2825 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); 2826 Decl *ActOnSkippedFunctionBody(Decl *Decl); 2827 void ActOnFinishInlineFunctionDef(FunctionDecl *D); 2828 2829 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an 2830 /// attribute for which parsing is delayed. 2831 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); 2832 2833 /// Diagnose any unused parameters in the given sequence of 2834 /// ParmVarDecl pointers. 2835 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters); 2836 2837 /// Diagnose whether the size of parameters or return value of a 2838 /// function or obj-c method definition is pass-by-value and larger than a 2839 /// specified threshold. 2840 void 2841 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters, 2842 QualType ReturnTy, NamedDecl *D); 2843 2844 void DiagnoseInvalidJumps(Stmt *Body); 2845 Decl *ActOnFileScopeAsmDecl(Expr *expr, 2846 SourceLocation AsmLoc, 2847 SourceLocation RParenLoc); 2848 2849 /// Handle a C++11 empty-declaration and attribute-declaration. 2850 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, 2851 SourceLocation SemiLoc); 2852 2853 enum class ModuleDeclKind { 2854 Interface, ///< 'export module X;' 2855 Implementation, ///< 'module X;' 2856 }; 2857 2858 /// The parser has processed a module-declaration that begins the definition 2859 /// of a module interface or implementation. 2860 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, 2861 SourceLocation ModuleLoc, ModuleDeclKind MDK, 2862 ModuleIdPath Path, bool IsFirstDecl); 2863 2864 /// The parser has processed a global-module-fragment declaration that begins 2865 /// the definition of the global module fragment of the current module unit. 2866 /// \param ModuleLoc The location of the 'module' keyword. 2867 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc); 2868 2869 /// The parser has processed a private-module-fragment declaration that begins 2870 /// the definition of the private module fragment of the current module unit. 2871 /// \param ModuleLoc The location of the 'module' keyword. 2872 /// \param PrivateLoc The location of the 'private' keyword. 2873 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, 2874 SourceLocation PrivateLoc); 2875 2876 /// The parser has processed a module import declaration. 2877 /// 2878 /// \param StartLoc The location of the first token in the declaration. This 2879 /// could be the location of an '@', 'export', or 'import'. 2880 /// \param ExportLoc The location of the 'export' keyword, if any. 2881 /// \param ImportLoc The location of the 'import' keyword. 2882 /// \param Path The module access path. 2883 DeclResult ActOnModuleImport(SourceLocation StartLoc, 2884 SourceLocation ExportLoc, 2885 SourceLocation ImportLoc, ModuleIdPath Path); 2886 DeclResult ActOnModuleImport(SourceLocation StartLoc, 2887 SourceLocation ExportLoc, 2888 SourceLocation ImportLoc, Module *M, 2889 ModuleIdPath Path = {}); 2890 2891 /// The parser has processed a module import translated from a 2892 /// #include or similar preprocessing directive. 2893 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod); 2894 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod); 2895 2896 /// The parsed has entered a submodule. 2897 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod); 2898 /// The parser has left a submodule. 2899 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod); 2900 2901 /// Create an implicit import of the given module at the given 2902 /// source location, for error recovery, if possible. 2903 /// 2904 /// This routine is typically used when an entity found by name lookup 2905 /// is actually hidden within a module that we know about but the user 2906 /// has forgotten to import. 2907 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 2908 Module *Mod); 2909 2910 /// Kinds of missing import. Note, the values of these enumerators correspond 2911 /// to %select values in diagnostics. 2912 enum class MissingImportKind { 2913 Declaration, 2914 Definition, 2915 DefaultArgument, 2916 ExplicitSpecialization, 2917 PartialSpecialization 2918 }; 2919 2920 /// Diagnose that the specified declaration needs to be visible but 2921 /// isn't, and suggest a module import that would resolve the problem. 2922 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, 2923 MissingImportKind MIK, bool Recover = true); 2924 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, 2925 SourceLocation DeclLoc, ArrayRef<Module *> Modules, 2926 MissingImportKind MIK, bool Recover); 2927 2928 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 2929 SourceLocation LBraceLoc); 2930 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, 2931 SourceLocation RBraceLoc); 2932 2933 /// We've found a use of a templated declaration that would trigger an 2934 /// implicit instantiation. Check that any relevant explicit specializations 2935 /// and partial specializations are visible, and diagnose if not. 2936 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); 2937 2938 /// Retrieve a suitable printing policy for diagnostics. getPrintingPolicy()2939 PrintingPolicy getPrintingPolicy() const { 2940 return getPrintingPolicy(Context, PP); 2941 } 2942 2943 /// Retrieve a suitable printing policy for diagnostics. 2944 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, 2945 const Preprocessor &PP); 2946 2947 /// Scope actions. 2948 void ActOnPopScope(SourceLocation Loc, Scope *S); 2949 void ActOnTranslationUnitScope(Scope *S); 2950 2951 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 2952 RecordDecl *&AnonRecord); 2953 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 2954 MultiTemplateParamsArg TemplateParams, 2955 bool IsExplicitInstantiation, 2956 RecordDecl *&AnonRecord); 2957 2958 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 2959 AccessSpecifier AS, 2960 RecordDecl *Record, 2961 const PrintingPolicy &Policy); 2962 2963 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 2964 RecordDecl *Record); 2965 2966 /// Common ways to introduce type names without a tag for use in diagnostics. 2967 /// Keep in sync with err_tag_reference_non_tag. 2968 enum NonTagKind { 2969 NTK_NonStruct, 2970 NTK_NonClass, 2971 NTK_NonUnion, 2972 NTK_NonEnum, 2973 NTK_Typedef, 2974 NTK_TypeAlias, 2975 NTK_Template, 2976 NTK_TypeAliasTemplate, 2977 NTK_TemplateTemplateArgument, 2978 }; 2979 2980 /// Given a non-tag type declaration, returns an enum useful for indicating 2981 /// what kind of non-tag type this is. 2982 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK); 2983 2984 bool isAcceptableTagRedeclaration(const TagDecl *Previous, 2985 TagTypeKind NewTag, bool isDefinition, 2986 SourceLocation NewTagLoc, 2987 const IdentifierInfo *Name); 2988 2989 enum TagUseKind { 2990 TUK_Reference, // Reference to a tag: 'struct foo *X;' 2991 TUK_Declaration, // Fwd decl of a tag: 'struct foo;' 2992 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' 2993 TUK_Friend // Friend declaration: 'friend struct foo;' 2994 }; 2995 2996 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 2997 SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, 2998 SourceLocation NameLoc, const ParsedAttributesView &Attr, 2999 AccessSpecifier AS, SourceLocation ModulePrivateLoc, 3000 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, 3001 bool &IsDependent, SourceLocation ScopedEnumKWLoc, 3002 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 3003 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 3004 SkipBodyInfo *SkipBody = nullptr); 3005 3006 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 3007 unsigned TagSpec, SourceLocation TagLoc, 3008 CXXScopeSpec &SS, IdentifierInfo *Name, 3009 SourceLocation NameLoc, 3010 const ParsedAttributesView &Attr, 3011 MultiTemplateParamsArg TempParamLists); 3012 3013 TypeResult ActOnDependentTag(Scope *S, 3014 unsigned TagSpec, 3015 TagUseKind TUK, 3016 const CXXScopeSpec &SS, 3017 IdentifierInfo *Name, 3018 SourceLocation TagLoc, 3019 SourceLocation NameLoc); 3020 3021 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, 3022 IdentifierInfo *ClassName, 3023 SmallVectorImpl<Decl *> &Decls); 3024 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 3025 Declarator &D, Expr *BitfieldWidth); 3026 3027 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, 3028 Declarator &D, Expr *BitfieldWidth, 3029 InClassInitStyle InitStyle, 3030 AccessSpecifier AS); 3031 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, 3032 SourceLocation DeclStart, Declarator &D, 3033 Expr *BitfieldWidth, 3034 InClassInitStyle InitStyle, 3035 AccessSpecifier AS, 3036 const ParsedAttr &MSPropertyAttr); 3037 3038 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, 3039 TypeSourceInfo *TInfo, 3040 RecordDecl *Record, SourceLocation Loc, 3041 bool Mutable, Expr *BitfieldWidth, 3042 InClassInitStyle InitStyle, 3043 SourceLocation TSSL, 3044 AccessSpecifier AS, NamedDecl *PrevDecl, 3045 Declarator *D = nullptr); 3046 3047 bool CheckNontrivialField(FieldDecl *FD); 3048 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM); 3049 3050 enum TrivialABIHandling { 3051 /// The triviality of a method unaffected by "trivial_abi". 3052 TAH_IgnoreTrivialABI, 3053 3054 /// The triviality of a method affected by "trivial_abi". 3055 TAH_ConsiderTrivialABI 3056 }; 3057 3058 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 3059 TrivialABIHandling TAH = TAH_IgnoreTrivialABI, 3060 bool Diagnose = false); 3061 3062 /// For a defaulted function, the kind of defaulted function that it is. 3063 class DefaultedFunctionKind { 3064 CXXSpecialMember SpecialMember : 8; 3065 DefaultedComparisonKind Comparison : 8; 3066 3067 public: DefaultedFunctionKind()3068 DefaultedFunctionKind() 3069 : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) { 3070 } DefaultedFunctionKind(CXXSpecialMember CSM)3071 DefaultedFunctionKind(CXXSpecialMember CSM) 3072 : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {} DefaultedFunctionKind(DefaultedComparisonKind Comp)3073 DefaultedFunctionKind(DefaultedComparisonKind Comp) 3074 : SpecialMember(CXXInvalid), Comparison(Comp) {} 3075 isSpecialMember()3076 bool isSpecialMember() const { return SpecialMember != CXXInvalid; } isComparison()3077 bool isComparison() const { 3078 return Comparison != DefaultedComparisonKind::None; 3079 } 3080 3081 explicit operator bool() const { 3082 return isSpecialMember() || isComparison(); 3083 } 3084 asSpecialMember()3085 CXXSpecialMember asSpecialMember() const { return SpecialMember; } asComparison()3086 DefaultedComparisonKind asComparison() const { return Comparison; } 3087 3088 /// Get the index of this function kind for use in diagnostics. getDiagnosticIndex()3089 unsigned getDiagnosticIndex() const { 3090 static_assert(CXXInvalid > CXXDestructor, 3091 "invalid should have highest index"); 3092 static_assert((unsigned)DefaultedComparisonKind::None == 0, 3093 "none should be equal to zero"); 3094 return SpecialMember + (unsigned)Comparison; 3095 } 3096 }; 3097 3098 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD); 3099 getSpecialMember(const CXXMethodDecl * MD)3100 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) { 3101 return getDefaultedFunctionKind(MD).asSpecialMember(); 3102 } getDefaultedComparisonKind(const FunctionDecl * FD)3103 DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) { 3104 return getDefaultedFunctionKind(FD).asComparison(); 3105 } 3106 3107 void ActOnLastBitfield(SourceLocation DeclStart, 3108 SmallVectorImpl<Decl *> &AllIvarDecls); 3109 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, 3110 Declarator &D, Expr *BitfieldWidth, 3111 tok::ObjCKeywordKind visibility); 3112 3113 // This is used for both record definitions and ObjC interface declarations. 3114 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, 3115 ArrayRef<Decl *> Fields, SourceLocation LBrac, 3116 SourceLocation RBrac, const ParsedAttributesView &AttrList); 3117 3118 /// ActOnTagStartDefinition - Invoked when we have entered the 3119 /// scope of a tag's definition (e.g., for an enumeration, class, 3120 /// struct, or union). 3121 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); 3122 3123 /// Perform ODR-like check for C/ObjC when merging tag types from modules. 3124 /// Differently from C++, actually parse the body and reject / error out 3125 /// in case of a structural mismatch. 3126 bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 3127 SkipBodyInfo &SkipBody); 3128 3129 typedef void *SkippedDefinitionContext; 3130 3131 /// Invoked when we enter a tag definition that we're skipping. 3132 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD); 3133 3134 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl); 3135 3136 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a 3137 /// C++ record definition's base-specifiers clause and are starting its 3138 /// member declarations. 3139 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, 3140 SourceLocation FinalLoc, 3141 bool IsFinalSpelledSealed, 3142 SourceLocation LBraceLoc); 3143 3144 /// ActOnTagFinishDefinition - Invoked once we have finished parsing 3145 /// the definition of a tag (enumeration, class, struct, or union). 3146 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, 3147 SourceRange BraceRange); 3148 3149 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context); 3150 3151 void ActOnObjCContainerFinishDefinition(); 3152 3153 /// Invoked when we must temporarily exit the objective-c container 3154 /// scope for parsing/looking-up C constructs. 3155 /// 3156 /// Must be followed by a call to \see ActOnObjCReenterContainerContext 3157 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC); 3158 void ActOnObjCReenterContainerContext(DeclContext *DC); 3159 3160 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable 3161 /// error parsing the definition of a tag. 3162 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); 3163 3164 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, 3165 EnumConstantDecl *LastEnumConst, 3166 SourceLocation IdLoc, 3167 IdentifierInfo *Id, 3168 Expr *val); 3169 bool CheckEnumUnderlyingType(TypeSourceInfo *TI); 3170 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 3171 QualType EnumUnderlyingTy, bool IsFixed, 3172 const EnumDecl *Prev); 3173 3174 /// Determine whether the body of an anonymous enumeration should be skipped. 3175 /// \param II The name of the first enumerator. 3176 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 3177 SourceLocation IILoc); 3178 3179 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, 3180 SourceLocation IdLoc, IdentifierInfo *Id, 3181 const ParsedAttributesView &Attrs, 3182 SourceLocation EqualLoc, Expr *Val); 3183 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 3184 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S, 3185 const ParsedAttributesView &Attr); 3186 3187 /// Set the current declaration context until it gets popped. 3188 void PushDeclContext(Scope *S, DeclContext *DC); 3189 void PopDeclContext(); 3190 3191 /// EnterDeclaratorContext - Used when we must lookup names in the context 3192 /// of a declarator's nested name specifier. 3193 void EnterDeclaratorContext(Scope *S, DeclContext *DC); 3194 void ExitDeclaratorContext(Scope *S); 3195 3196 /// Enter a template parameter scope, after it's been associated with a particular 3197 /// DeclContext. Causes lookup within the scope to chain through enclosing contexts 3198 /// in the correct order. 3199 void EnterTemplatedContext(Scope *S, DeclContext *DC); 3200 3201 /// Push the parameters of D, which must be a function, into scope. 3202 void ActOnReenterFunctionContext(Scope* S, Decl* D); 3203 void ActOnExitFunctionContext(); 3204 3205 DeclContext *getFunctionLevelDeclContext(); 3206 3207 /// getCurFunctionDecl - If inside of a function body, this returns a pointer 3208 /// to the function decl for the function being parsed. If we're currently 3209 /// in a 'block', this returns the containing context. 3210 FunctionDecl *getCurFunctionDecl(); 3211 3212 /// getCurMethodDecl - If inside of a method body, this returns a pointer to 3213 /// the method decl for the method being parsed. If we're currently 3214 /// in a 'block', this returns the containing context. 3215 ObjCMethodDecl *getCurMethodDecl(); 3216 3217 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method 3218 /// or C function we're in, otherwise return null. If we're currently 3219 /// in a 'block', this returns the containing context. 3220 NamedDecl *getCurFunctionOrMethodDecl(); 3221 3222 /// Add this decl to the scope shadowed decl chains. 3223 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); 3224 3225 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true 3226 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns 3227 /// true if 'D' belongs to the given declaration context. 3228 /// 3229 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the 3230 /// enclosing namespace set of the context, rather than contained 3231 /// directly within it. 3232 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr, 3233 bool AllowInlineNamespace = false); 3234 3235 /// Finds the scope corresponding to the given decl context, if it 3236 /// happens to be an enclosing scope. Otherwise return NULL. 3237 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); 3238 3239 /// Subroutines of ActOnDeclarator(). 3240 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 3241 TypeSourceInfo *TInfo); 3242 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New); 3243 3244 /// Describes the kind of merge to perform for availability 3245 /// attributes (including "deprecated", "unavailable", and "availability"). 3246 enum AvailabilityMergeKind { 3247 /// Don't merge availability attributes at all. 3248 AMK_None, 3249 /// Merge availability attributes for a redeclaration, which requires 3250 /// an exact match. 3251 AMK_Redeclaration, 3252 /// Merge availability attributes for an override, which requires 3253 /// an exact match or a weakening of constraints. 3254 AMK_Override, 3255 /// Merge availability attributes for an implementation of 3256 /// a protocol requirement. 3257 AMK_ProtocolImplementation, 3258 /// Merge availability attributes for an implementation of 3259 /// an optional protocol requirement. 3260 AMK_OptionalProtocolImplementation 3261 }; 3262 3263 /// Describes the kind of priority given to an availability attribute. 3264 /// 3265 /// The sum of priorities deteremines the final priority of the attribute. 3266 /// The final priority determines how the attribute will be merged. 3267 /// An attribute with a lower priority will always remove higher priority 3268 /// attributes for the specified platform when it is being applied. An 3269 /// attribute with a higher priority will not be applied if the declaration 3270 /// already has an availability attribute with a lower priority for the 3271 /// specified platform. The final prirority values are not expected to match 3272 /// the values in this enumeration, but instead should be treated as a plain 3273 /// integer value. This enumeration just names the priority weights that are 3274 /// used to calculate that final vaue. 3275 enum AvailabilityPriority : int { 3276 /// The availability attribute was specified explicitly next to the 3277 /// declaration. 3278 AP_Explicit = 0, 3279 3280 /// The availability attribute was applied using '#pragma clang attribute'. 3281 AP_PragmaClangAttribute = 1, 3282 3283 /// The availability attribute for a specific platform was inferred from 3284 /// an availability attribute for another platform. 3285 AP_InferredFromOtherPlatform = 2 3286 }; 3287 3288 /// Attribute merging methods. Return true if a new attribute was added. 3289 AvailabilityAttr * 3290 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, 3291 IdentifierInfo *Platform, bool Implicit, 3292 VersionTuple Introduced, VersionTuple Deprecated, 3293 VersionTuple Obsoleted, bool IsUnavailable, 3294 StringRef Message, bool IsStrict, StringRef Replacement, 3295 AvailabilityMergeKind AMK, int Priority); 3296 TypeVisibilityAttr * 3297 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, 3298 TypeVisibilityAttr::VisibilityType Vis); 3299 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, 3300 VisibilityAttr::VisibilityType Vis); 3301 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, 3302 StringRef UuidAsWritten, MSGuidDecl *GuidDecl); 3303 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI); 3304 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI); 3305 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D, 3306 const AttributeCommonInfo &CI, 3307 bool BestCase, 3308 MSInheritanceModel Model); 3309 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, 3310 IdentifierInfo *Format, int FormatIdx, 3311 int FirstArg); 3312 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, 3313 StringRef Name); 3314 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, 3315 StringRef Name); 3316 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, 3317 const AttributeCommonInfo &CI, 3318 const IdentifierInfo *Ident); 3319 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI); 3320 SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA, 3321 StringRef Name); 3322 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, 3323 const AttributeCommonInfo &CI); 3324 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL); 3325 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, 3326 const InternalLinkageAttr &AL); 3327 WebAssemblyImportNameAttr *mergeImportNameAttr( 3328 Decl *D, const WebAssemblyImportNameAttr &AL); 3329 WebAssemblyImportModuleAttr *mergeImportModuleAttr( 3330 Decl *D, const WebAssemblyImportModuleAttr &AL); 3331 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL); 3332 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D, 3333 const EnforceTCBLeafAttr &AL); 3334 3335 void mergeDeclAttributes(NamedDecl *New, Decl *Old, 3336 AvailabilityMergeKind AMK = AMK_Redeclaration); 3337 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 3338 LookupResult &OldDecls); 3339 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, 3340 bool MergeTypeWithOld); 3341 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3342 Scope *S, bool MergeTypeWithOld); 3343 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); 3344 void MergeVarDecl(VarDecl *New, LookupResult &Previous); 3345 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld); 3346 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); 3347 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn); 3348 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New); 3349 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); 3350 3351 // AssignmentAction - This is used by all the assignment diagnostic functions 3352 // to represent what is actually causing the operation 3353 enum AssignmentAction { 3354 AA_Assigning, 3355 AA_Passing, 3356 AA_Returning, 3357 AA_Converting, 3358 AA_Initializing, 3359 AA_Sending, 3360 AA_Casting, 3361 AA_Passing_CFAudited 3362 }; 3363 3364 /// C++ Overloading. 3365 enum OverloadKind { 3366 /// This is a legitimate overload: the existing declarations are 3367 /// functions or function templates with different signatures. 3368 Ovl_Overload, 3369 3370 /// This is not an overload because the signature exactly matches 3371 /// an existing declaration. 3372 Ovl_Match, 3373 3374 /// This is not an overload because the lookup results contain a 3375 /// non-function. 3376 Ovl_NonFunction 3377 }; 3378 OverloadKind CheckOverload(Scope *S, 3379 FunctionDecl *New, 3380 const LookupResult &OldDecls, 3381 NamedDecl *&OldDecl, 3382 bool IsForUsingDecl); 3383 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl, 3384 bool ConsiderCudaAttrs = true, 3385 bool ConsiderRequiresClauses = true); 3386 3387 enum class AllowedExplicit { 3388 /// Allow no explicit functions to be used. 3389 None, 3390 /// Allow explicit conversion functions but not explicit constructors. 3391 Conversions, 3392 /// Allow both explicit conversion functions and explicit constructors. 3393 All 3394 }; 3395 3396 ImplicitConversionSequence 3397 TryImplicitConversion(Expr *From, QualType ToType, 3398 bool SuppressUserConversions, 3399 AllowedExplicit AllowExplicit, 3400 bool InOverloadResolution, 3401 bool CStyle, 3402 bool AllowObjCWritebackConversion); 3403 3404 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); 3405 bool IsFloatingPointPromotion(QualType FromType, QualType ToType); 3406 bool IsComplexPromotion(QualType FromType, QualType ToType); 3407 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 3408 bool InOverloadResolution, 3409 QualType& ConvertedType, bool &IncompatibleObjC); 3410 bool isObjCPointerConversion(QualType FromType, QualType ToType, 3411 QualType& ConvertedType, bool &IncompatibleObjC); 3412 bool isObjCWritebackConversion(QualType FromType, QualType ToType, 3413 QualType &ConvertedType); 3414 bool IsBlockPointerConversion(QualType FromType, QualType ToType, 3415 QualType& ConvertedType); 3416 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 3417 const FunctionProtoType *NewType, 3418 unsigned *ArgPos = nullptr); 3419 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 3420 QualType FromType, QualType ToType); 3421 3422 void maybeExtendBlockObject(ExprResult &E); 3423 CastKind PrepareCastToObjCObjectPointer(ExprResult &E); 3424 bool CheckPointerConversion(Expr *From, QualType ToType, 3425 CastKind &Kind, 3426 CXXCastPath& BasePath, 3427 bool IgnoreBaseAccess, 3428 bool Diagnose = true); 3429 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, 3430 bool InOverloadResolution, 3431 QualType &ConvertedType); 3432 bool CheckMemberPointerConversion(Expr *From, QualType ToType, 3433 CastKind &Kind, 3434 CXXCastPath &BasePath, 3435 bool IgnoreBaseAccess); 3436 bool IsQualificationConversion(QualType FromType, QualType ToType, 3437 bool CStyle, bool &ObjCLifetimeConversion); 3438 bool IsFunctionConversion(QualType FromType, QualType ToType, 3439 QualType &ResultTy); 3440 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); 3441 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg); 3442 3443 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, 3444 const VarDecl *NRVOCandidate, 3445 QualType ResultType, 3446 Expr *Value, 3447 bool AllowNRVO = true); 3448 3449 bool CanPerformAggregateInitializationForOverloadResolution( 3450 const InitializedEntity &Entity, InitListExpr *From); 3451 3452 bool IsStringInit(Expr *Init, const ArrayType *AT); 3453 3454 bool CanPerformCopyInitialization(const InitializedEntity &Entity, 3455 ExprResult Init); 3456 ExprResult PerformCopyInitialization(const InitializedEntity &Entity, 3457 SourceLocation EqualLoc, 3458 ExprResult Init, 3459 bool TopLevelOfInitList = false, 3460 bool AllowExplicit = false); 3461 ExprResult PerformObjectArgumentInitialization(Expr *From, 3462 NestedNameSpecifier *Qualifier, 3463 NamedDecl *FoundDecl, 3464 CXXMethodDecl *Method); 3465 3466 /// Check that the lifetime of the initializer (and its subobjects) is 3467 /// sufficient for initializing the entity, and perform lifetime extension 3468 /// (when permitted) if not. 3469 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init); 3470 3471 ExprResult PerformContextuallyConvertToBool(Expr *From); 3472 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); 3473 3474 /// Contexts in which a converted constant expression is required. 3475 enum CCEKind { 3476 CCEK_CaseValue, ///< Expression in a case label. 3477 CCEK_Enumerator, ///< Enumerator value with fixed underlying type. 3478 CCEK_TemplateArg, ///< Value of a non-type template parameter. 3479 CCEK_ArrayBound, ///< Array bound in array declarator or new-expression. 3480 CCEK_ConstexprIf, ///< Condition in a constexpr if statement. 3481 CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier. 3482 }; 3483 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, 3484 llvm::APSInt &Value, CCEKind CCE); 3485 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, 3486 APValue &Value, CCEKind CCE, 3487 NamedDecl *Dest = nullptr); 3488 3489 /// Abstract base class used to perform a contextual implicit 3490 /// conversion from an expression to any type passing a filter. 3491 class ContextualImplicitConverter { 3492 public: 3493 bool Suppress; 3494 bool SuppressConversion; 3495 3496 ContextualImplicitConverter(bool Suppress = false, 3497 bool SuppressConversion = false) Suppress(Suppress)3498 : Suppress(Suppress), SuppressConversion(SuppressConversion) {} 3499 3500 /// Determine whether the specified type is a valid destination type 3501 /// for this conversion. 3502 virtual bool match(QualType T) = 0; 3503 3504 /// Emits a diagnostic complaining that the expression does not have 3505 /// integral or enumeration type. 3506 virtual SemaDiagnosticBuilder 3507 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0; 3508 3509 /// Emits a diagnostic when the expression has incomplete class type. 3510 virtual SemaDiagnosticBuilder 3511 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; 3512 3513 /// Emits a diagnostic when the only matching conversion function 3514 /// is explicit. 3515 virtual SemaDiagnosticBuilder diagnoseExplicitConv( 3516 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; 3517 3518 /// Emits a note for the explicit conversion function. 3519 virtual SemaDiagnosticBuilder 3520 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; 3521 3522 /// Emits a diagnostic when there are multiple possible conversion 3523 /// functions. 3524 virtual SemaDiagnosticBuilder 3525 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0; 3526 3527 /// Emits a note for one of the candidate conversions. 3528 virtual SemaDiagnosticBuilder 3529 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; 3530 3531 /// Emits a diagnostic when we picked a conversion function 3532 /// (for cases when we are not allowed to pick a conversion function). 3533 virtual SemaDiagnosticBuilder diagnoseConversion( 3534 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; 3535 ~ContextualImplicitConverter()3536 virtual ~ContextualImplicitConverter() {} 3537 }; 3538 3539 class ICEConvertDiagnoser : public ContextualImplicitConverter { 3540 bool AllowScopedEnumerations; 3541 3542 public: ICEConvertDiagnoser(bool AllowScopedEnumerations,bool Suppress,bool SuppressConversion)3543 ICEConvertDiagnoser(bool AllowScopedEnumerations, 3544 bool Suppress, bool SuppressConversion) 3545 : ContextualImplicitConverter(Suppress, SuppressConversion), 3546 AllowScopedEnumerations(AllowScopedEnumerations) {} 3547 3548 /// Match an integral or (possibly scoped) enumeration type. 3549 bool match(QualType T) override; 3550 3551 SemaDiagnosticBuilder diagnoseNoMatch(Sema & S,SourceLocation Loc,QualType T)3552 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override { 3553 return diagnoseNotInt(S, Loc, T); 3554 } 3555 3556 /// Emits a diagnostic complaining that the expression does not have 3557 /// integral or enumeration type. 3558 virtual SemaDiagnosticBuilder 3559 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0; 3560 }; 3561 3562 /// Perform a contextual implicit conversion. 3563 ExprResult PerformContextualImplicitConversion( 3564 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter); 3565 3566 3567 enum ObjCSubscriptKind { 3568 OS_Array, 3569 OS_Dictionary, 3570 OS_Error 3571 }; 3572 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); 3573 3574 // Note that LK_String is intentionally after the other literals, as 3575 // this is used for diagnostics logic. 3576 enum ObjCLiteralKind { 3577 LK_Array, 3578 LK_Dictionary, 3579 LK_Numeric, 3580 LK_Boxed, 3581 LK_String, 3582 LK_Block, 3583 LK_None 3584 }; 3585 ObjCLiteralKind CheckLiteralKind(Expr *FromE); 3586 3587 ExprResult PerformObjectMemberConversion(Expr *From, 3588 NestedNameSpecifier *Qualifier, 3589 NamedDecl *FoundDecl, 3590 NamedDecl *Member); 3591 3592 // Members have to be NamespaceDecl* or TranslationUnitDecl*. 3593 // TODO: make this is a typesafe union. 3594 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet; 3595 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet; 3596 3597 using ADLCallKind = CallExpr::ADLCallKind; 3598 3599 void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, 3600 ArrayRef<Expr *> Args, 3601 OverloadCandidateSet &CandidateSet, 3602 bool SuppressUserConversions = false, 3603 bool PartialOverloading = false, 3604 bool AllowExplicit = true, 3605 bool AllowExplicitConversion = false, 3606 ADLCallKind IsADLCandidate = ADLCallKind::NotADL, 3607 ConversionSequenceList EarlyConversions = None, 3608 OverloadCandidateParamOrder PO = {}); 3609 void AddFunctionCandidates(const UnresolvedSetImpl &Functions, 3610 ArrayRef<Expr *> Args, 3611 OverloadCandidateSet &CandidateSet, 3612 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, 3613 bool SuppressUserConversions = false, 3614 bool PartialOverloading = false, 3615 bool FirstArgumentIsBase = false); 3616 void AddMethodCandidate(DeclAccessPair FoundDecl, 3617 QualType ObjectType, 3618 Expr::Classification ObjectClassification, 3619 ArrayRef<Expr *> Args, 3620 OverloadCandidateSet& CandidateSet, 3621 bool SuppressUserConversion = false, 3622 OverloadCandidateParamOrder PO = {}); 3623 void AddMethodCandidate(CXXMethodDecl *Method, 3624 DeclAccessPair FoundDecl, 3625 CXXRecordDecl *ActingContext, QualType ObjectType, 3626 Expr::Classification ObjectClassification, 3627 ArrayRef<Expr *> Args, 3628 OverloadCandidateSet& CandidateSet, 3629 bool SuppressUserConversions = false, 3630 bool PartialOverloading = false, 3631 ConversionSequenceList EarlyConversions = None, 3632 OverloadCandidateParamOrder PO = {}); 3633 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 3634 DeclAccessPair FoundDecl, 3635 CXXRecordDecl *ActingContext, 3636 TemplateArgumentListInfo *ExplicitTemplateArgs, 3637 QualType ObjectType, 3638 Expr::Classification ObjectClassification, 3639 ArrayRef<Expr *> Args, 3640 OverloadCandidateSet& CandidateSet, 3641 bool SuppressUserConversions = false, 3642 bool PartialOverloading = false, 3643 OverloadCandidateParamOrder PO = {}); 3644 void AddTemplateOverloadCandidate( 3645 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 3646 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 3647 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, 3648 bool PartialOverloading = false, bool AllowExplicit = true, 3649 ADLCallKind IsADLCandidate = ADLCallKind::NotADL, 3650 OverloadCandidateParamOrder PO = {}); 3651 bool CheckNonDependentConversions( 3652 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 3653 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 3654 ConversionSequenceList &Conversions, bool SuppressUserConversions, 3655 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(), 3656 Expr::Classification ObjectClassification = {}, 3657 OverloadCandidateParamOrder PO = {}); 3658 void AddConversionCandidate( 3659 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 3660 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 3661 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 3662 bool AllowExplicit, bool AllowResultConversion = true); 3663 void AddTemplateConversionCandidate( 3664 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 3665 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 3666 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 3667 bool AllowExplicit, bool AllowResultConversion = true); 3668 void AddSurrogateCandidate(CXXConversionDecl *Conversion, 3669 DeclAccessPair FoundDecl, 3670 CXXRecordDecl *ActingContext, 3671 const FunctionProtoType *Proto, 3672 Expr *Object, ArrayRef<Expr *> Args, 3673 OverloadCandidateSet& CandidateSet); 3674 void AddNonMemberOperatorCandidates( 3675 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, 3676 OverloadCandidateSet &CandidateSet, 3677 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); 3678 void AddMemberOperatorCandidates(OverloadedOperatorKind Op, 3679 SourceLocation OpLoc, ArrayRef<Expr *> Args, 3680 OverloadCandidateSet &CandidateSet, 3681 OverloadCandidateParamOrder PO = {}); 3682 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 3683 OverloadCandidateSet& CandidateSet, 3684 bool IsAssignmentOperator = false, 3685 unsigned NumContextualBoolArguments = 0); 3686 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 3687 SourceLocation OpLoc, ArrayRef<Expr *> Args, 3688 OverloadCandidateSet& CandidateSet); 3689 void AddArgumentDependentLookupCandidates(DeclarationName Name, 3690 SourceLocation Loc, 3691 ArrayRef<Expr *> Args, 3692 TemplateArgumentListInfo *ExplicitTemplateArgs, 3693 OverloadCandidateSet& CandidateSet, 3694 bool PartialOverloading = false); 3695 3696 // Emit as a 'note' the specific overload candidate 3697 void NoteOverloadCandidate( 3698 NamedDecl *Found, FunctionDecl *Fn, 3699 OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(), 3700 QualType DestType = QualType(), bool TakingAddress = false); 3701 3702 // Emit as a series of 'note's all template and non-templates identified by 3703 // the expression Expr 3704 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(), 3705 bool TakingAddress = false); 3706 3707 /// Check the enable_if expressions on the given function. Returns the first 3708 /// failing attribute, or NULL if they were all successful. 3709 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, 3710 ArrayRef<Expr *> Args, 3711 bool MissingImplicitThis = false); 3712 3713 /// Find the failed Boolean condition within a given Boolean 3714 /// constant expression, and describe it with a string. 3715 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond); 3716 3717 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any 3718 /// non-ArgDependent DiagnoseIfAttrs. 3719 /// 3720 /// Argument-dependent diagnose_if attributes should be checked each time a 3721 /// function is used as a direct callee of a function call. 3722 /// 3723 /// Returns true if any errors were emitted. 3724 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 3725 const Expr *ThisArg, 3726 ArrayRef<const Expr *> Args, 3727 SourceLocation Loc); 3728 3729 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any 3730 /// ArgDependent DiagnoseIfAttrs. 3731 /// 3732 /// Argument-independent diagnose_if attributes should be checked on every use 3733 /// of a function. 3734 /// 3735 /// Returns true if any errors were emitted. 3736 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 3737 SourceLocation Loc); 3738 3739 /// Returns whether the given function's address can be taken or not, 3740 /// optionally emitting a diagnostic if the address can't be taken. 3741 /// 3742 /// Returns false if taking the address of the function is illegal. 3743 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 3744 bool Complain = false, 3745 SourceLocation Loc = SourceLocation()); 3746 3747 // [PossiblyAFunctionType] --> [Return] 3748 // NonFunctionType --> NonFunctionType 3749 // R (A) --> R(A) 3750 // R (*)(A) --> R (A) 3751 // R (&)(A) --> R (A) 3752 // R (S::*)(A) --> R (A) 3753 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); 3754 3755 FunctionDecl * 3756 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 3757 QualType TargetType, 3758 bool Complain, 3759 DeclAccessPair &Found, 3760 bool *pHadMultipleCandidates = nullptr); 3761 3762 FunctionDecl * 3763 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult); 3764 3765 bool resolveAndFixAddressOfSingleOverloadCandidate( 3766 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false); 3767 3768 FunctionDecl * 3769 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 3770 bool Complain = false, 3771 DeclAccessPair *Found = nullptr); 3772 3773 bool ResolveAndFixSingleFunctionTemplateSpecialization( 3774 ExprResult &SrcExpr, 3775 bool DoFunctionPointerConverion = false, 3776 bool Complain = false, 3777 SourceRange OpRangeForComplaining = SourceRange(), 3778 QualType DestTypeForComplaining = QualType(), 3779 unsigned DiagIDForComplaining = 0); 3780 3781 3782 Expr *FixOverloadedFunctionReference(Expr *E, 3783 DeclAccessPair FoundDecl, 3784 FunctionDecl *Fn); 3785 ExprResult FixOverloadedFunctionReference(ExprResult, 3786 DeclAccessPair FoundDecl, 3787 FunctionDecl *Fn); 3788 3789 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 3790 ArrayRef<Expr *> Args, 3791 OverloadCandidateSet &CandidateSet, 3792 bool PartialOverloading = false); 3793 void AddOverloadedCallCandidates( 3794 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, 3795 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet); 3796 3797 // An enum used to represent the different possible results of building a 3798 // range-based for loop. 3799 enum ForRangeStatus { 3800 FRS_Success, 3801 FRS_NoViableFunction, 3802 FRS_DiagnosticIssued 3803 }; 3804 3805 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, 3806 SourceLocation RangeLoc, 3807 const DeclarationNameInfo &NameInfo, 3808 LookupResult &MemberLookup, 3809 OverloadCandidateSet *CandidateSet, 3810 Expr *Range, ExprResult *CallExpr); 3811 3812 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, 3813 UnresolvedLookupExpr *ULE, 3814 SourceLocation LParenLoc, 3815 MultiExprArg Args, 3816 SourceLocation RParenLoc, 3817 Expr *ExecConfig, 3818 bool AllowTypoCorrection=true, 3819 bool CalleesAddressIsTaken=false); 3820 3821 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, 3822 MultiExprArg Args, SourceLocation RParenLoc, 3823 OverloadCandidateSet *CandidateSet, 3824 ExprResult *Result); 3825 3826 ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, 3827 NestedNameSpecifierLoc NNSLoc, 3828 DeclarationNameInfo DNI, 3829 const UnresolvedSetImpl &Fns, 3830 bool PerformADL = true); 3831 3832 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, 3833 UnaryOperatorKind Opc, 3834 const UnresolvedSetImpl &Fns, 3835 Expr *input, bool RequiresADL = true); 3836 3837 void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 3838 OverloadedOperatorKind Op, 3839 const UnresolvedSetImpl &Fns, 3840 ArrayRef<Expr *> Args, bool RequiresADL = true); 3841 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, 3842 BinaryOperatorKind Opc, 3843 const UnresolvedSetImpl &Fns, 3844 Expr *LHS, Expr *RHS, 3845 bool RequiresADL = true, 3846 bool AllowRewrittenCandidates = true, 3847 FunctionDecl *DefaultedFn = nullptr); 3848 ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, 3849 const UnresolvedSetImpl &Fns, 3850 Expr *LHS, Expr *RHS, 3851 FunctionDecl *DefaultedFn); 3852 3853 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 3854 SourceLocation RLoc, 3855 Expr *Base,Expr *Idx); 3856 3857 ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, 3858 SourceLocation LParenLoc, 3859 MultiExprArg Args, 3860 SourceLocation RParenLoc, 3861 bool AllowRecovery = false); 3862 ExprResult 3863 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, 3864 MultiExprArg Args, 3865 SourceLocation RParenLoc); 3866 3867 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, 3868 SourceLocation OpLoc, 3869 bool *NoArrowOperatorFound = nullptr); 3870 3871 /// CheckCallReturnType - Checks that a call expression's return type is 3872 /// complete. Returns true on failure. The location passed in is the location 3873 /// that best represents the call. 3874 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 3875 CallExpr *CE, FunctionDecl *FD); 3876 3877 /// Helpers for dealing with blocks and functions. 3878 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 3879 bool CheckParameterNames); 3880 void CheckCXXDefaultArguments(FunctionDecl *FD); 3881 void CheckExtraCXXDefaultArguments(Declarator &D); 3882 Scope *getNonFieldDeclScope(Scope *S); 3883 3884 /// \name Name lookup 3885 /// 3886 /// These routines provide name lookup that is used during semantic 3887 /// analysis to resolve the various kinds of names (identifiers, 3888 /// overloaded operator names, constructor names, etc.) into zero or 3889 /// more declarations within a particular scope. The major entry 3890 /// points are LookupName, which performs unqualified name lookup, 3891 /// and LookupQualifiedName, which performs qualified name lookup. 3892 /// 3893 /// All name lookup is performed based on some specific criteria, 3894 /// which specify what names will be visible to name lookup and how 3895 /// far name lookup should work. These criteria are important both 3896 /// for capturing language semantics (certain lookups will ignore 3897 /// certain names, for example) and for performance, since name 3898 /// lookup is often a bottleneck in the compilation of C++. Name 3899 /// lookup criteria is specified via the LookupCriteria enumeration. 3900 /// 3901 /// The results of name lookup can vary based on the kind of name 3902 /// lookup performed, the current language, and the translation 3903 /// unit. In C, for example, name lookup will either return nothing 3904 /// (no entity found) or a single declaration. In C++, name lookup 3905 /// can additionally refer to a set of overloaded functions or 3906 /// result in an ambiguity. All of the possible results of name 3907 /// lookup are captured by the LookupResult class, which provides 3908 /// the ability to distinguish among them. 3909 //@{ 3910 3911 /// Describes the kind of name lookup to perform. 3912 enum LookupNameKind { 3913 /// Ordinary name lookup, which finds ordinary names (functions, 3914 /// variables, typedefs, etc.) in C and most kinds of names 3915 /// (functions, variables, members, types, etc.) in C++. 3916 LookupOrdinaryName = 0, 3917 /// Tag name lookup, which finds the names of enums, classes, 3918 /// structs, and unions. 3919 LookupTagName, 3920 /// Label name lookup. 3921 LookupLabel, 3922 /// Member name lookup, which finds the names of 3923 /// class/struct/union members. 3924 LookupMemberName, 3925 /// Look up of an operator name (e.g., operator+) for use with 3926 /// operator overloading. This lookup is similar to ordinary name 3927 /// lookup, but will ignore any declarations that are class members. 3928 LookupOperatorName, 3929 /// Look up a name following ~ in a destructor name. This is an ordinary 3930 /// lookup, but prefers tags to typedefs. 3931 LookupDestructorName, 3932 /// Look up of a name that precedes the '::' scope resolution 3933 /// operator in C++. This lookup completely ignores operator, object, 3934 /// function, and enumerator names (C++ [basic.lookup.qual]p1). 3935 LookupNestedNameSpecifierName, 3936 /// Look up a namespace name within a C++ using directive or 3937 /// namespace alias definition, ignoring non-namespace names (C++ 3938 /// [basic.lookup.udir]p1). 3939 LookupNamespaceName, 3940 /// Look up all declarations in a scope with the given name, 3941 /// including resolved using declarations. This is appropriate 3942 /// for checking redeclarations for a using declaration. 3943 LookupUsingDeclName, 3944 /// Look up an ordinary name that is going to be redeclared as a 3945 /// name with linkage. This lookup ignores any declarations that 3946 /// are outside of the current scope unless they have linkage. See 3947 /// C99 6.2.2p4-5 and C++ [basic.link]p6. 3948 LookupRedeclarationWithLinkage, 3949 /// Look up a friend of a local class. This lookup does not look 3950 /// outside the innermost non-class scope. See C++11 [class.friend]p11. 3951 LookupLocalFriendName, 3952 /// Look up the name of an Objective-C protocol. 3953 LookupObjCProtocolName, 3954 /// Look up implicit 'self' parameter of an objective-c method. 3955 LookupObjCImplicitSelfParam, 3956 /// Look up the name of an OpenMP user-defined reduction operation. 3957 LookupOMPReductionName, 3958 /// Look up the name of an OpenMP user-defined mapper. 3959 LookupOMPMapperName, 3960 /// Look up any declaration with any name. 3961 LookupAnyName 3962 }; 3963 3964 /// Specifies whether (or how) name lookup is being performed for a 3965 /// redeclaration (vs. a reference). 3966 enum RedeclarationKind { 3967 /// The lookup is a reference to this name that is not for the 3968 /// purpose of redeclaring the name. 3969 NotForRedeclaration = 0, 3970 /// The lookup results will be used for redeclaration of a name, 3971 /// if an entity by that name already exists and is visible. 3972 ForVisibleRedeclaration, 3973 /// The lookup results will be used for redeclaration of a name 3974 /// with external linkage; non-visible lookup results with external linkage 3975 /// may also be found. 3976 ForExternalRedeclaration 3977 }; 3978 forRedeclarationInCurContext()3979 RedeclarationKind forRedeclarationInCurContext() { 3980 // A declaration with an owning module for linkage can never link against 3981 // anything that is not visible. We don't need to check linkage here; if 3982 // the context has internal linkage, redeclaration lookup won't find things 3983 // from other TUs, and we can't safely compute linkage yet in general. 3984 if (cast<Decl>(CurContext) 3985 ->getOwningModuleForLinkage(/*IgnoreLinkage*/true)) 3986 return ForVisibleRedeclaration; 3987 return ForExternalRedeclaration; 3988 } 3989 3990 /// The possible outcomes of name lookup for a literal operator. 3991 enum LiteralOperatorLookupResult { 3992 /// The lookup resulted in an error. 3993 LOLR_Error, 3994 /// The lookup found no match but no diagnostic was issued. 3995 LOLR_ErrorNoDiagnostic, 3996 /// The lookup found a single 'cooked' literal operator, which 3997 /// expects a normal literal to be built and passed to it. 3998 LOLR_Cooked, 3999 /// The lookup found a single 'raw' literal operator, which expects 4000 /// a string literal containing the spelling of the literal token. 4001 LOLR_Raw, 4002 /// The lookup found an overload set of literal operator templates, 4003 /// which expect the characters of the spelling of the literal token to be 4004 /// passed as a non-type template argument pack. 4005 LOLR_Template, 4006 /// The lookup found an overload set of literal operator templates, 4007 /// which expect the character type and characters of the spelling of the 4008 /// string literal token to be passed as template arguments. 4009 LOLR_StringTemplatePack, 4010 }; 4011 4012 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, 4013 CXXSpecialMember SM, 4014 bool ConstArg, 4015 bool VolatileArg, 4016 bool RValueThis, 4017 bool ConstThis, 4018 bool VolatileThis); 4019 4020 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator; 4021 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)> 4022 TypoRecoveryCallback; 4023 4024 private: 4025 bool CppLookupName(LookupResult &R, Scope *S); 4026 4027 struct TypoExprState { 4028 std::unique_ptr<TypoCorrectionConsumer> Consumer; 4029 TypoDiagnosticGenerator DiagHandler; 4030 TypoRecoveryCallback RecoveryHandler; 4031 TypoExprState(); 4032 TypoExprState(TypoExprState &&other) noexcept; 4033 TypoExprState &operator=(TypoExprState &&other) noexcept; 4034 }; 4035 4036 /// The set of unhandled TypoExprs and their associated state. 4037 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos; 4038 4039 /// Creates a new TypoExpr AST node. 4040 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, 4041 TypoDiagnosticGenerator TDG, 4042 TypoRecoveryCallback TRC, SourceLocation TypoLoc); 4043 4044 // The set of known/encountered (unique, canonicalized) NamespaceDecls. 4045 // 4046 // The boolean value will be true to indicate that the namespace was loaded 4047 // from an AST/PCH file, or false otherwise. 4048 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces; 4049 4050 /// Whether we have already loaded known namespaces from an extenal 4051 /// source. 4052 bool LoadedExternalKnownNamespaces; 4053 4054 /// Helper for CorrectTypo and CorrectTypoDelayed used to create and 4055 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction 4056 /// should be skipped entirely. 4057 std::unique_ptr<TypoCorrectionConsumer> 4058 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo, 4059 Sema::LookupNameKind LookupKind, Scope *S, 4060 CXXScopeSpec *SS, 4061 CorrectionCandidateCallback &CCC, 4062 DeclContext *MemberContext, bool EnteringContext, 4063 const ObjCObjectPointerType *OPT, 4064 bool ErrorRecovery); 4065 4066 public: 4067 const TypoExprState &getTypoExprState(TypoExpr *TE) const; 4068 4069 /// Clears the state of the given TypoExpr. 4070 void clearDelayedTypo(TypoExpr *TE); 4071 4072 /// Look up a name, looking for a single declaration. Return 4073 /// null if the results were absent, ambiguous, or overloaded. 4074 /// 4075 /// It is preferable to use the elaborated form and explicitly handle 4076 /// ambiguity and overloaded. 4077 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, 4078 SourceLocation Loc, 4079 LookupNameKind NameKind, 4080 RedeclarationKind Redecl 4081 = NotForRedeclaration); 4082 bool LookupBuiltin(LookupResult &R); 4083 void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID); 4084 bool LookupName(LookupResult &R, Scope *S, 4085 bool AllowBuiltinCreation = false); 4086 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 4087 bool InUnqualifiedLookup = false); 4088 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 4089 CXXScopeSpec &SS); 4090 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 4091 bool AllowBuiltinCreation = false, 4092 bool EnteringContext = false); 4093 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, 4094 RedeclarationKind Redecl 4095 = NotForRedeclaration); 4096 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class); 4097 4098 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, 4099 UnresolvedSetImpl &Functions); 4100 4101 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, 4102 SourceLocation GnuLabelLoc = SourceLocation()); 4103 4104 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); 4105 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); 4106 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, 4107 unsigned Quals); 4108 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, 4109 bool RValueThis, unsigned ThisQuals); 4110 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, 4111 unsigned Quals); 4112 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, 4113 bool RValueThis, unsigned ThisQuals); 4114 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); 4115 4116 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id); 4117 LiteralOperatorLookupResult 4118 LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys, 4119 bool AllowRaw, bool AllowTemplate, 4120 bool AllowStringTemplate, bool DiagnoseMissing, 4121 StringLiteral *StringLit = nullptr); 4122 bool isKnownName(StringRef name); 4123 4124 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs. 4125 enum class FunctionEmissionStatus { 4126 Emitted, 4127 CUDADiscarded, // Discarded due to CUDA/HIP hostness 4128 OMPDiscarded, // Discarded due to OpenMP hostness 4129 TemplateDiscarded, // Discarded due to uninstantiated templates 4130 Unknown, 4131 }; 4132 FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl, 4133 bool Final = false); 4134 4135 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check. 4136 bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee); 4137 4138 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, 4139 ArrayRef<Expr *> Args, ADLResult &Functions); 4140 4141 void LookupVisibleDecls(Scope *S, LookupNameKind Kind, 4142 VisibleDeclConsumer &Consumer, 4143 bool IncludeGlobalScope = true, 4144 bool LoadExternal = true); 4145 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, 4146 VisibleDeclConsumer &Consumer, 4147 bool IncludeGlobalScope = true, 4148 bool IncludeDependentBases = false, 4149 bool LoadExternal = true); 4150 4151 enum CorrectTypoKind { 4152 CTK_NonError, // CorrectTypo used in a non error recovery situation. 4153 CTK_ErrorRecovery // CorrectTypo used in normal error recovery. 4154 }; 4155 4156 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, 4157 Sema::LookupNameKind LookupKind, 4158 Scope *S, CXXScopeSpec *SS, 4159 CorrectionCandidateCallback &CCC, 4160 CorrectTypoKind Mode, 4161 DeclContext *MemberContext = nullptr, 4162 bool EnteringContext = false, 4163 const ObjCObjectPointerType *OPT = nullptr, 4164 bool RecordFailure = true); 4165 4166 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo, 4167 Sema::LookupNameKind LookupKind, Scope *S, 4168 CXXScopeSpec *SS, 4169 CorrectionCandidateCallback &CCC, 4170 TypoDiagnosticGenerator TDG, 4171 TypoRecoveryCallback TRC, CorrectTypoKind Mode, 4172 DeclContext *MemberContext = nullptr, 4173 bool EnteringContext = false, 4174 const ObjCObjectPointerType *OPT = nullptr); 4175 4176 /// Process any TypoExprs in the given Expr and its children, 4177 /// generating diagnostics as appropriate and returning a new Expr if there 4178 /// were typos that were all successfully corrected and ExprError if one or 4179 /// more typos could not be corrected. 4180 /// 4181 /// \param E The Expr to check for TypoExprs. 4182 /// 4183 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its 4184 /// initializer. 4185 /// 4186 /// \param RecoverUncorrectedTypos If true, when typo correction fails, it 4187 /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs. 4188 /// 4189 /// \param Filter A function applied to a newly rebuilt Expr to determine if 4190 /// it is an acceptable/usable result from a single combination of typo 4191 /// corrections. As long as the filter returns ExprError, different 4192 /// combinations of corrections will be tried until all are exhausted. 4193 ExprResult CorrectDelayedTyposInExpr( 4194 Expr *E, VarDecl *InitDecl = nullptr, 4195 bool RecoverUncorrectedTypos = false, 4196 llvm::function_ref<ExprResult(Expr *)> Filter = 4197 [](Expr *E) -> ExprResult { return E; }); 4198 4199 ExprResult CorrectDelayedTyposInExpr( 4200 ExprResult ER, VarDecl *InitDecl = nullptr, 4201 bool RecoverUncorrectedTypos = false, 4202 llvm::function_ref<ExprResult(Expr *)> Filter = 4203 [](Expr *E) -> ExprResult { return E; }) { 4204 return ER.isInvalid() 4205 ? ER 4206 : CorrectDelayedTyposInExpr(ER.get(), InitDecl, 4207 RecoverUncorrectedTypos, Filter); 4208 } 4209 4210 void diagnoseTypo(const TypoCorrection &Correction, 4211 const PartialDiagnostic &TypoDiag, 4212 bool ErrorRecovery = true); 4213 4214 void diagnoseTypo(const TypoCorrection &Correction, 4215 const PartialDiagnostic &TypoDiag, 4216 const PartialDiagnostic &PrevNote, 4217 bool ErrorRecovery = true); 4218 4219 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F); 4220 4221 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, 4222 ArrayRef<Expr *> Args, 4223 AssociatedNamespaceSet &AssociatedNamespaces, 4224 AssociatedClassSet &AssociatedClasses); 4225 4226 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 4227 bool ConsiderLinkage, bool AllowInlineNamespace); 4228 4229 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old); 4230 4231 void DiagnoseAmbiguousLookup(LookupResult &Result); 4232 //@} 4233 4234 /// Attempts to produce a RecoveryExpr after some AST node cannot be created. 4235 ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 4236 ArrayRef<Expr *> SubExprs, 4237 QualType T = QualType()); 4238 4239 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, 4240 SourceLocation IdLoc, 4241 bool TypoCorrection = false); 4242 FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, 4243 SourceLocation Loc); 4244 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 4245 Scope *S, bool ForRedeclaration, 4246 SourceLocation Loc); 4247 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, 4248 Scope *S); 4249 void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 4250 FunctionDecl *FD); 4251 void AddKnownFunctionAttributes(FunctionDecl *FD); 4252 4253 // More parsing and symbol table subroutines. 4254 4255 void ProcessPragmaWeak(Scope *S, Decl *D); 4256 // Decl attributes - this routine is the top level dispatcher. 4257 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); 4258 // Helper for delayed processing of attributes. 4259 void ProcessDeclAttributeDelayed(Decl *D, 4260 const ParsedAttributesView &AttrList); 4261 void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL, 4262 bool IncludeCXX11Attributes = true); 4263 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, 4264 const ParsedAttributesView &AttrList); 4265 4266 void checkUnusedDeclAttributes(Declarator &D); 4267 4268 /// Handles semantic checking for features that are common to all attributes, 4269 /// such as checking whether a parameter was properly specified, or the 4270 /// correct number of arguments were passed, etc. Returns true if the 4271 /// attribute has been diagnosed. 4272 bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A); 4273 bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A); 4274 4275 /// Determine if type T is a valid subject for a nonnull and similar 4276 /// attributes. By default, we look through references (the behavior used by 4277 /// nonnull), but if the second parameter is true, then we treat a reference 4278 /// type as valid. 4279 bool isValidPointerAttrType(QualType T, bool RefOkay = false); 4280 4281 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value); 4282 bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, 4283 const FunctionDecl *FD = nullptr); 4284 bool CheckAttrTarget(const ParsedAttr &CurrAttr); 4285 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr); 4286 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum, 4287 StringRef &Str, 4288 SourceLocation *ArgLocation = nullptr); 4289 llvm::Error isValidSectionSpecifier(StringRef Str); 4290 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str); 4291 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str); 4292 bool checkMSInheritanceAttrOnDefinition( 4293 CXXRecordDecl *RD, SourceRange Range, bool BestCase, 4294 MSInheritanceModel SemanticSpelling); 4295 4296 void CheckAlignasUnderalignment(Decl *D); 4297 4298 /// Adjust the calling convention of a method to be the ABI default if it 4299 /// wasn't specified explicitly. This handles method types formed from 4300 /// function type typedefs and typename template arguments. 4301 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, 4302 SourceLocation Loc); 4303 4304 // Check if there is an explicit attribute, but only look through parens. 4305 // The intent is to look for an attribute on the current declarator, but not 4306 // one that came from a typedef. 4307 bool hasExplicitCallingConv(QualType T); 4308 4309 /// Get the outermost AttributedType node that sets a calling convention. 4310 /// Valid types should not have multiple attributes with different CCs. 4311 const AttributedType *getCallingConvAttributedType(QualType T) const; 4312 4313 /// Process the attributes before creating an attributed statement. Returns 4314 /// the semantic attributes that have been processed. 4315 void ProcessStmtAttributes(Stmt *Stmt, 4316 const ParsedAttributesWithRange &InAttrs, 4317 SmallVectorImpl<const Attr *> &OutAttrs); 4318 4319 void WarnConflictingTypedMethods(ObjCMethodDecl *Method, 4320 ObjCMethodDecl *MethodDecl, 4321 bool IsProtocolMethodDecl); 4322 4323 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, 4324 ObjCMethodDecl *Overridden, 4325 bool IsProtocolMethodDecl); 4326 4327 /// WarnExactTypedMethods - This routine issues a warning if method 4328 /// implementation declaration matches exactly that of its declaration. 4329 void WarnExactTypedMethods(ObjCMethodDecl *Method, 4330 ObjCMethodDecl *MethodDecl, 4331 bool IsProtocolMethodDecl); 4332 4333 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet; 4334 4335 /// CheckImplementationIvars - This routine checks if the instance variables 4336 /// listed in the implelementation match those listed in the interface. 4337 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, 4338 ObjCIvarDecl **Fields, unsigned nIvars, 4339 SourceLocation Loc); 4340 4341 /// ImplMethodsVsClassMethods - This is main routine to warn if any method 4342 /// remains unimplemented in the class or category \@implementation. 4343 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, 4344 ObjCContainerDecl* IDecl, 4345 bool IncompleteImpl = false); 4346 4347 /// DiagnoseUnimplementedProperties - This routine warns on those properties 4348 /// which must be implemented by this implementation. 4349 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, 4350 ObjCContainerDecl *CDecl, 4351 bool SynthesizeProperties); 4352 4353 /// Diagnose any null-resettable synthesized setters. 4354 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl); 4355 4356 /// DefaultSynthesizeProperties - This routine default synthesizes all 4357 /// properties which must be synthesized in the class's \@implementation. 4358 void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl, 4359 ObjCInterfaceDecl *IDecl, 4360 SourceLocation AtEnd); 4361 void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd); 4362 4363 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is 4364 /// an ivar synthesized for 'Method' and 'Method' is a property accessor 4365 /// declared in class 'IFace'. 4366 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, 4367 ObjCMethodDecl *Method, ObjCIvarDecl *IV); 4368 4369 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which 4370 /// backs the property is not used in the property's accessor. 4371 void DiagnoseUnusedBackingIvarInAccessor(Scope *S, 4372 const ObjCImplementationDecl *ImplD); 4373 4374 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and 4375 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL. 4376 /// It also returns ivar's property on success. 4377 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, 4378 const ObjCPropertyDecl *&PDecl) const; 4379 4380 /// Called by ActOnProperty to handle \@property declarations in 4381 /// class extensions. 4382 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S, 4383 SourceLocation AtLoc, 4384 SourceLocation LParenLoc, 4385 FieldDeclarator &FD, 4386 Selector GetterSel, 4387 SourceLocation GetterNameLoc, 4388 Selector SetterSel, 4389 SourceLocation SetterNameLoc, 4390 const bool isReadWrite, 4391 unsigned &Attributes, 4392 const unsigned AttributesAsWritten, 4393 QualType T, 4394 TypeSourceInfo *TSI, 4395 tok::ObjCKeywordKind MethodImplKind); 4396 4397 /// Called by ActOnProperty and HandlePropertyInClassExtension to 4398 /// handle creating the ObjcPropertyDecl for a category or \@interface. 4399 ObjCPropertyDecl *CreatePropertyDecl(Scope *S, 4400 ObjCContainerDecl *CDecl, 4401 SourceLocation AtLoc, 4402 SourceLocation LParenLoc, 4403 FieldDeclarator &FD, 4404 Selector GetterSel, 4405 SourceLocation GetterNameLoc, 4406 Selector SetterSel, 4407 SourceLocation SetterNameLoc, 4408 const bool isReadWrite, 4409 const unsigned Attributes, 4410 const unsigned AttributesAsWritten, 4411 QualType T, 4412 TypeSourceInfo *TSI, 4413 tok::ObjCKeywordKind MethodImplKind, 4414 DeclContext *lexicalDC = nullptr); 4415 4416 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via 4417 /// warning) when atomic property has one but not the other user-declared 4418 /// setter or getter. 4419 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, 4420 ObjCInterfaceDecl* IDecl); 4421 4422 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); 4423 4424 void DiagnoseMissingDesignatedInitOverrides( 4425 const ObjCImplementationDecl *ImplD, 4426 const ObjCInterfaceDecl *IFD); 4427 4428 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); 4429 4430 enum MethodMatchStrategy { 4431 MMS_loose, 4432 MMS_strict 4433 }; 4434 4435 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns 4436 /// true, or false, accordingly. 4437 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, 4438 const ObjCMethodDecl *PrevMethod, 4439 MethodMatchStrategy strategy = MMS_strict); 4440 4441 /// MatchAllMethodDeclarations - Check methods declaraed in interface or 4442 /// or protocol against those declared in their implementations. 4443 void MatchAllMethodDeclarations(const SelectorSet &InsMap, 4444 const SelectorSet &ClsMap, 4445 SelectorSet &InsMapSeen, 4446 SelectorSet &ClsMapSeen, 4447 ObjCImplDecl* IMPDecl, 4448 ObjCContainerDecl* IDecl, 4449 bool &IncompleteImpl, 4450 bool ImmediateClass, 4451 bool WarnCategoryMethodImpl=false); 4452 4453 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in 4454 /// category matches with those implemented in its primary class and 4455 /// warns each time an exact match is found. 4456 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); 4457 4458 /// Add the given method to the list of globally-known methods. 4459 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); 4460 4461 /// Returns default addr space for method qualifiers. 4462 LangAS getDefaultCXXMethodAddrSpace() const; 4463 4464 private: 4465 /// AddMethodToGlobalPool - Add an instance or factory method to the global 4466 /// pool. See descriptoin of AddInstanceMethodToGlobalPool. 4467 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); 4468 4469 /// LookupMethodInGlobalPool - Returns the instance or factory method and 4470 /// optionally warns if there are multiple signatures. 4471 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, 4472 bool receiverIdOrClass, 4473 bool instance); 4474 4475 public: 4476 /// - Returns instance or factory methods in global method pool for 4477 /// given selector. It checks the desired kind first, if none is found, and 4478 /// parameter checkTheOther is set, it then checks the other kind. If no such 4479 /// method or only one method is found, function returns false; otherwise, it 4480 /// returns true. 4481 bool 4482 CollectMultipleMethodsInGlobalPool(Selector Sel, 4483 SmallVectorImpl<ObjCMethodDecl*>& Methods, 4484 bool InstanceFirst, bool CheckTheOther, 4485 const ObjCObjectType *TypeBound = nullptr); 4486 4487 bool 4488 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, 4489 SourceRange R, bool receiverIdOrClass, 4490 SmallVectorImpl<ObjCMethodDecl*>& Methods); 4491 4492 void 4493 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, 4494 Selector Sel, SourceRange R, 4495 bool receiverIdOrClass); 4496 4497 private: 4498 /// - Returns a selector which best matches given argument list or 4499 /// nullptr if none could be found 4500 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args, 4501 bool IsInstance, 4502 SmallVectorImpl<ObjCMethodDecl*>& Methods); 4503 4504 4505 /// Record the typo correction failure and return an empty correction. 4506 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc, 4507 bool RecordFailure = true) { 4508 if (RecordFailure) 4509 TypoCorrectionFailures[Typo].insert(TypoLoc); 4510 return TypoCorrection(); 4511 } 4512 4513 public: 4514 /// AddInstanceMethodToGlobalPool - All instance methods in a translation 4515 /// unit are added to a global pool. This allows us to efficiently associate 4516 /// a selector with a method declaraation for purposes of typechecking 4517 /// messages sent to "id" (where the class of the object is unknown). 4518 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 4519 AddMethodToGlobalPool(Method, impl, /*instance*/true); 4520 } 4521 4522 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. 4523 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 4524 AddMethodToGlobalPool(Method, impl, /*instance*/false); 4525 } 4526 4527 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global 4528 /// pool. 4529 void AddAnyMethodToGlobalPool(Decl *D); 4530 4531 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if 4532 /// there are multiple signatures. 4533 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, 4534 bool receiverIdOrClass=false) { 4535 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 4536 /*instance*/true); 4537 } 4538 4539 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if 4540 /// there are multiple signatures. 4541 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, 4542 bool receiverIdOrClass=false) { 4543 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 4544 /*instance*/false); 4545 } 4546 4547 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel, 4548 QualType ObjectType=QualType()); 4549 /// LookupImplementedMethodInGlobalPool - Returns the method which has an 4550 /// implementation. 4551 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); 4552 4553 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require 4554 /// initialization. 4555 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, 4556 SmallVectorImpl<ObjCIvarDecl*> &Ivars); 4557 4558 //===--------------------------------------------------------------------===// 4559 // Statement Parsing Callbacks: SemaStmt.cpp. 4560 public: 4561 class FullExprArg { 4562 public: FullExprArg()4563 FullExprArg() : E(nullptr) { } FullExprArg(Sema & actions)4564 FullExprArg(Sema &actions) : E(nullptr) { } 4565 release()4566 ExprResult release() { 4567 return E; 4568 } 4569 get()4570 Expr *get() const { return E; } 4571 4572 Expr *operator->() { 4573 return E; 4574 } 4575 4576 private: 4577 // FIXME: No need to make the entire Sema class a friend when it's just 4578 // Sema::MakeFullExpr that needs access to the constructor below. 4579 friend class Sema; 4580 FullExprArg(Expr * expr)4581 explicit FullExprArg(Expr *expr) : E(expr) {} 4582 4583 Expr *E; 4584 }; 4585 MakeFullExpr(Expr * Arg)4586 FullExprArg MakeFullExpr(Expr *Arg) { 4587 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation()); 4588 } MakeFullExpr(Expr * Arg,SourceLocation CC)4589 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { 4590 return FullExprArg( 4591 ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get()); 4592 } MakeFullDiscardedValueExpr(Expr * Arg)4593 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { 4594 ExprResult FE = 4595 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), 4596 /*DiscardedValue*/ true); 4597 return FullExprArg(FE.get()); 4598 } 4599 4600 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true); 4601 StmtResult ActOnExprStmtError(); 4602 4603 StmtResult ActOnNullStmt(SourceLocation SemiLoc, 4604 bool HasLeadingEmptyMacro = false); 4605 4606 void ActOnStartOfCompoundStmt(bool IsStmtExpr); 4607 void ActOnAfterCompoundStatementLeadingPragmas(); 4608 void ActOnFinishOfCompoundStmt(); 4609 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, 4610 ArrayRef<Stmt *> Elts, bool isStmtExpr); 4611 4612 /// A RAII object to enter scope of a compound statement. 4613 class CompoundScopeRAII { 4614 public: S(S)4615 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) { 4616 S.ActOnStartOfCompoundStmt(IsStmtExpr); 4617 } 4618 ~CompoundScopeRAII()4619 ~CompoundScopeRAII() { 4620 S.ActOnFinishOfCompoundStmt(); 4621 } 4622 4623 private: 4624 Sema &S; 4625 }; 4626 4627 /// An RAII helper that pops function a function scope on exit. 4628 struct FunctionScopeRAII { 4629 Sema &S; 4630 bool Active; FunctionScopeRAIIFunctionScopeRAII4631 FunctionScopeRAII(Sema &S) : S(S), Active(true) {} ~FunctionScopeRAIIFunctionScopeRAII4632 ~FunctionScopeRAII() { 4633 if (Active) 4634 S.PopFunctionScopeInfo(); 4635 } disableFunctionScopeRAII4636 void disable() { Active = false; } 4637 }; 4638 4639 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, 4640 SourceLocation StartLoc, 4641 SourceLocation EndLoc); 4642 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); 4643 StmtResult ActOnForEachLValueExpr(Expr *E); 4644 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val); 4645 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS, 4646 SourceLocation DotDotDotLoc, ExprResult RHS, 4647 SourceLocation ColonLoc); 4648 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); 4649 4650 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, 4651 SourceLocation ColonLoc, 4652 Stmt *SubStmt, Scope *CurScope); 4653 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, 4654 SourceLocation ColonLoc, Stmt *SubStmt); 4655 4656 StmtResult BuildAttributedStmt(SourceLocation AttrsLoc, 4657 ArrayRef<const Attr *> Attrs, Stmt *SubStmt); 4658 StmtResult ActOnAttributedStmt(const ParsedAttributesWithRange &AttrList, 4659 Stmt *SubStmt); 4660 4661 class ConditionResult; 4662 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, 4663 SourceLocation LParenLoc, Stmt *InitStmt, 4664 ConditionResult Cond, SourceLocation RParenLoc, 4665 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); 4666 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr, 4667 SourceLocation LParenLoc, Stmt *InitStmt, 4668 ConditionResult Cond, SourceLocation RParenLoc, 4669 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); 4670 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, 4671 SourceLocation LParenLoc, Stmt *InitStmt, 4672 ConditionResult Cond, 4673 SourceLocation RParenLoc); 4674 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, 4675 Stmt *Switch, Stmt *Body); 4676 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc, 4677 ConditionResult Cond, SourceLocation RParenLoc, 4678 Stmt *Body); 4679 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 4680 SourceLocation WhileLoc, SourceLocation CondLParen, 4681 Expr *Cond, SourceLocation CondRParen); 4682 4683 StmtResult ActOnForStmt(SourceLocation ForLoc, 4684 SourceLocation LParenLoc, 4685 Stmt *First, 4686 ConditionResult Second, 4687 FullExprArg Third, 4688 SourceLocation RParenLoc, 4689 Stmt *Body); 4690 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, 4691 Expr *collection); 4692 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, 4693 Stmt *First, Expr *collection, 4694 SourceLocation RParenLoc); 4695 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body); 4696 4697 enum BuildForRangeKind { 4698 /// Initial building of a for-range statement. 4699 BFRK_Build, 4700 /// Instantiation or recovery rebuild of a for-range statement. Don't 4701 /// attempt any typo-correction. 4702 BFRK_Rebuild, 4703 /// Determining whether a for-range statement could be built. Avoid any 4704 /// unnecessary or irreversible actions. 4705 BFRK_Check 4706 }; 4707 4708 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, 4709 SourceLocation CoawaitLoc, 4710 Stmt *InitStmt, 4711 Stmt *LoopVar, 4712 SourceLocation ColonLoc, Expr *Collection, 4713 SourceLocation RParenLoc, 4714 BuildForRangeKind Kind); 4715 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, 4716 SourceLocation CoawaitLoc, 4717 Stmt *InitStmt, 4718 SourceLocation ColonLoc, 4719 Stmt *RangeDecl, Stmt *Begin, Stmt *End, 4720 Expr *Cond, Expr *Inc, 4721 Stmt *LoopVarDecl, 4722 SourceLocation RParenLoc, 4723 BuildForRangeKind Kind); 4724 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); 4725 4726 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, 4727 SourceLocation LabelLoc, 4728 LabelDecl *TheDecl); 4729 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, 4730 SourceLocation StarLoc, 4731 Expr *DestExp); 4732 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); 4733 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); 4734 4735 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, 4736 CapturedRegionKind Kind, unsigned NumParams); 4737 typedef std::pair<StringRef, QualType> CapturedParamNameType; 4738 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, 4739 CapturedRegionKind Kind, 4740 ArrayRef<CapturedParamNameType> Params, 4741 unsigned OpenMPCaptureLevel = 0); 4742 StmtResult ActOnCapturedRegionEnd(Stmt *S); 4743 void ActOnCapturedRegionError(); 4744 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, 4745 SourceLocation Loc, 4746 unsigned NumParams); 4747 4748 enum CopyElisionSemanticsKind { 4749 CES_Strict = 0, 4750 CES_AllowParameters = 1, 4751 CES_AllowDifferentTypes = 2, 4752 CES_AllowExceptionVariables = 4, 4753 CES_AllowRValueReferenceType = 8, 4754 CES_ImplicitlyMovableCXX11CXX14CXX17 = 4755 (CES_AllowParameters | CES_AllowDifferentTypes), 4756 CES_ImplicitlyMovableCXX20 = 4757 (CES_AllowParameters | CES_AllowDifferentTypes | 4758 CES_AllowExceptionVariables | CES_AllowRValueReferenceType), 4759 }; 4760 4761 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E, 4762 CopyElisionSemanticsKind CESK); 4763 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD, 4764 CopyElisionSemanticsKind CESK); 4765 4766 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, 4767 Scope *CurScope); 4768 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); 4769 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); 4770 4771 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, 4772 bool IsVolatile, unsigned NumOutputs, 4773 unsigned NumInputs, IdentifierInfo **Names, 4774 MultiExprArg Constraints, MultiExprArg Exprs, 4775 Expr *AsmString, MultiExprArg Clobbers, 4776 unsigned NumLabels, 4777 SourceLocation RParenLoc); 4778 4779 void FillInlineAsmIdentifierInfo(Expr *Res, 4780 llvm::InlineAsmIdentifierInfo &Info); 4781 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, 4782 SourceLocation TemplateKWLoc, 4783 UnqualifiedId &Id, 4784 bool IsUnevaluatedContext); 4785 bool LookupInlineAsmField(StringRef Base, StringRef Member, 4786 unsigned &Offset, SourceLocation AsmLoc); 4787 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, 4788 SourceLocation AsmLoc); 4789 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, 4790 ArrayRef<Token> AsmToks, 4791 StringRef AsmString, 4792 unsigned NumOutputs, unsigned NumInputs, 4793 ArrayRef<StringRef> Constraints, 4794 ArrayRef<StringRef> Clobbers, 4795 ArrayRef<Expr*> Exprs, 4796 SourceLocation EndLoc); 4797 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName, 4798 SourceLocation Location, 4799 bool AlwaysCreate); 4800 4801 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, 4802 SourceLocation StartLoc, 4803 SourceLocation IdLoc, IdentifierInfo *Id, 4804 bool Invalid = false); 4805 4806 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); 4807 4808 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, 4809 Decl *Parm, Stmt *Body); 4810 4811 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); 4812 4813 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 4814 MultiStmtArg Catch, Stmt *Finally); 4815 4816 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); 4817 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 4818 Scope *CurScope); 4819 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, 4820 Expr *operand); 4821 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, 4822 Expr *SynchExpr, 4823 Stmt *SynchBody); 4824 4825 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); 4826 4827 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, 4828 SourceLocation StartLoc, 4829 SourceLocation IdLoc, 4830 IdentifierInfo *Id); 4831 4832 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); 4833 4834 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, 4835 Decl *ExDecl, Stmt *HandlerBlock); 4836 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 4837 ArrayRef<Stmt *> Handlers); 4838 4839 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? 4840 SourceLocation TryLoc, Stmt *TryBlock, 4841 Stmt *Handler); 4842 StmtResult ActOnSEHExceptBlock(SourceLocation Loc, 4843 Expr *FilterExpr, 4844 Stmt *Block); 4845 void ActOnStartSEHFinallyBlock(); 4846 void ActOnAbortSEHFinallyBlock(); 4847 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block); 4848 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope); 4849 4850 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); 4851 4852 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; 4853 4854 /// If it's a file scoped decl that must warn if not used, keep track 4855 /// of it. 4856 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); 4857 4858 /// DiagnoseUnusedExprResult - If the statement passed in is an expression 4859 /// whose result is unused, warn. 4860 void DiagnoseUnusedExprResult(const Stmt *S); 4861 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D); 4862 void DiagnoseUnusedDecl(const NamedDecl *ND); 4863 4864 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null 4865 /// statement as a \p Body, and it is located on the same line. 4866 /// 4867 /// This helps prevent bugs due to typos, such as: 4868 /// if (condition); 4869 /// do_stuff(); 4870 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 4871 const Stmt *Body, 4872 unsigned DiagID); 4873 4874 /// Warn if a for/while loop statement \p S, which is followed by 4875 /// \p PossibleBody, has a suspicious null statement as a body. 4876 void DiagnoseEmptyLoopBody(const Stmt *S, 4877 const Stmt *PossibleBody); 4878 4879 /// Warn if a value is moved to itself. 4880 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 4881 SourceLocation OpLoc); 4882 4883 /// Warn if we're implicitly casting from a _Nullable pointer type to a 4884 /// _Nonnull one. 4885 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, 4886 SourceLocation Loc); 4887 4888 /// Warn when implicitly casting 0 to nullptr. 4889 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E); 4890 PushParsingDeclaration(sema::DelayedDiagnosticPool & pool)4891 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { 4892 return DelayedDiagnostics.push(pool); 4893 } 4894 void PopParsingDeclaration(ParsingDeclState state, Decl *decl); 4895 4896 typedef ProcessingContextState ParsingClassState; PushParsingClass()4897 ParsingClassState PushParsingClass() { 4898 ParsingClassDepth++; 4899 return DelayedDiagnostics.pushUndelayed(); 4900 } PopParsingClass(ParsingClassState state)4901 void PopParsingClass(ParsingClassState state) { 4902 ParsingClassDepth--; 4903 DelayedDiagnostics.popUndelayed(state); 4904 } 4905 4906 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); 4907 4908 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 4909 const ObjCInterfaceDecl *UnknownObjCClass, 4910 bool ObjCPropertyAccess, 4911 bool AvoidPartialAvailabilityChecks = false, 4912 ObjCInterfaceDecl *ClassReceiver = nullptr); 4913 4914 bool makeUnavailableInSystemHeader(SourceLocation loc, 4915 UnavailableAttr::ImplicitReason reason); 4916 4917 /// Issue any -Wunguarded-availability warnings in \c FD 4918 void DiagnoseUnguardedAvailabilityViolations(Decl *FD); 4919 4920 void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 4921 4922 //===--------------------------------------------------------------------===// 4923 // Expression Parsing Callbacks: SemaExpr.cpp. 4924 4925 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid); 4926 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 4927 const ObjCInterfaceDecl *UnknownObjCClass = nullptr, 4928 bool ObjCPropertyAccess = false, 4929 bool AvoidPartialAvailabilityChecks = false, 4930 ObjCInterfaceDecl *ClassReciever = nullptr); 4931 void NoteDeletedFunction(FunctionDecl *FD); 4932 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD); 4933 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, 4934 ObjCMethodDecl *Getter, 4935 SourceLocation Loc); 4936 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 4937 ArrayRef<Expr *> Args); 4938 4939 void PushExpressionEvaluationContext( 4940 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, 4941 ExpressionEvaluationContextRecord::ExpressionKind Type = 4942 ExpressionEvaluationContextRecord::EK_Other); 4943 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; 4944 void PushExpressionEvaluationContext( 4945 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 4946 ExpressionEvaluationContextRecord::ExpressionKind Type = 4947 ExpressionEvaluationContextRecord::EK_Other); 4948 void PopExpressionEvaluationContext(); 4949 4950 void DiscardCleanupsInEvaluationContext(); 4951 4952 ExprResult TransformToPotentiallyEvaluated(Expr *E); 4953 ExprResult HandleExprEvaluationContextForTypeof(Expr *E); 4954 4955 ExprResult CheckUnevaluatedOperand(Expr *E); 4956 void CheckUnusedVolatileAssignment(Expr *E); 4957 4958 ExprResult ActOnConstantExpression(ExprResult Res); 4959 4960 // Functions for marking a declaration referenced. These functions also 4961 // contain the relevant logic for marking if a reference to a function or 4962 // variable is an odr-use (in the C++11 sense). There are separate variants 4963 // for expressions referring to a decl; these exist because odr-use marking 4964 // needs to be delayed for some constant variables when we build one of the 4965 // named expressions. 4966 // 4967 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and 4968 // should usually be true. This only needs to be set to false if the lack of 4969 // odr-use cannot be determined from the current context (for instance, 4970 // because the name denotes a virtual function and was written without an 4971 // explicit nested-name-specifier). 4972 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse); 4973 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 4974 bool MightBeOdrUse = true); 4975 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); 4976 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr); 4977 void MarkMemberReferenced(MemberExpr *E); 4978 void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E); 4979 void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc, 4980 unsigned CapturingScopeIndex); 4981 4982 ExprResult CheckLValueToRValueConversionOperand(Expr *E); 4983 void CleanupVarDeclMarking(); 4984 4985 enum TryCaptureKind { 4986 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef 4987 }; 4988 4989 /// Try to capture the given variable. 4990 /// 4991 /// \param Var The variable to capture. 4992 /// 4993 /// \param Loc The location at which the capture occurs. 4994 /// 4995 /// \param Kind The kind of capture, which may be implicit (for either a 4996 /// block or a lambda), or explicit by-value or by-reference (for a lambda). 4997 /// 4998 /// \param EllipsisLoc The location of the ellipsis, if one is provided in 4999 /// an explicit lambda capture. 5000 /// 5001 /// \param BuildAndDiagnose Whether we are actually supposed to add the 5002 /// captures or diagnose errors. If false, this routine merely check whether 5003 /// the capture can occur without performing the capture itself or complaining 5004 /// if the variable cannot be captured. 5005 /// 5006 /// \param CaptureType Will be set to the type of the field used to capture 5007 /// this variable in the innermost block or lambda. Only valid when the 5008 /// variable can be captured. 5009 /// 5010 /// \param DeclRefType Will be set to the type of a reference to the capture 5011 /// from within the current scope. Only valid when the variable can be 5012 /// captured. 5013 /// 5014 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index 5015 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. 5016 /// This is useful when enclosing lambdas must speculatively capture 5017 /// variables that may or may not be used in certain specializations of 5018 /// a nested generic lambda. 5019 /// 5020 /// \returns true if an error occurred (i.e., the variable cannot be 5021 /// captured) and false if the capture succeeded. 5022 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, 5023 SourceLocation EllipsisLoc, bool BuildAndDiagnose, 5024 QualType &CaptureType, 5025 QualType &DeclRefType, 5026 const unsigned *const FunctionScopeIndexToStopAt); 5027 5028 /// Try to capture the given variable. 5029 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 5030 TryCaptureKind Kind = TryCapture_Implicit, 5031 SourceLocation EllipsisLoc = SourceLocation()); 5032 5033 /// Checks if the variable must be captured. 5034 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc); 5035 5036 /// Given a variable, determine the type that a reference to that 5037 /// variable will have in the given scope. 5038 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); 5039 5040 /// Mark all of the declarations referenced within a particular AST node as 5041 /// referenced. Used when template instantiation instantiates a non-dependent 5042 /// type -- entities referenced by the type are now referenced. 5043 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); 5044 void MarkDeclarationsReferencedInExpr(Expr *E, 5045 bool SkipLocalVariables = false); 5046 5047 /// Try to recover by turning the given expression into a 5048 /// call. Returns true if recovery was attempted or an error was 5049 /// emitted; this may also leave the ExprResult invalid. 5050 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, 5051 bool ForceComplain = false, 5052 bool (*IsPlausibleResult)(QualType) = nullptr); 5053 5054 /// Figure out if an expression could be turned into a call. 5055 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, 5056 UnresolvedSetImpl &NonTemplateOverloads); 5057 5058 /// Try to convert an expression \p E to type \p Ty. Returns the result of the 5059 /// conversion. 5060 ExprResult tryConvertExprToType(Expr *E, QualType Ty); 5061 5062 /// Conditionally issue a diagnostic based on the current 5063 /// evaluation context. 5064 /// 5065 /// \param Statement If Statement is non-null, delay reporting the 5066 /// diagnostic until the function body is parsed, and then do a basic 5067 /// reachability analysis to determine if the statement is reachable. 5068 /// If it is unreachable, the diagnostic will not be emitted. 5069 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 5070 const PartialDiagnostic &PD); 5071 /// Similar, but diagnostic is only produced if all the specified statements 5072 /// are reachable. 5073 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 5074 const PartialDiagnostic &PD); 5075 5076 // Primary Expressions. 5077 SourceRange getExprRange(Expr *E) const; 5078 5079 ExprResult ActOnIdExpression( 5080 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 5081 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, 5082 CorrectionCandidateCallback *CCC = nullptr, 5083 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr); 5084 5085 void DecomposeUnqualifiedId(const UnqualifiedId &Id, 5086 TemplateArgumentListInfo &Buffer, 5087 DeclarationNameInfo &NameInfo, 5088 const TemplateArgumentListInfo *&TemplateArgs); 5089 5090 bool DiagnoseDependentMemberLookup(LookupResult &R); 5091 5092 bool 5093 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 5094 CorrectionCandidateCallback &CCC, 5095 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, 5096 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr); 5097 5098 DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 5099 IdentifierInfo *II); 5100 ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV); 5101 5102 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, 5103 IdentifierInfo *II, 5104 bool AllowBuiltinCreation=false); 5105 5106 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, 5107 SourceLocation TemplateKWLoc, 5108 const DeclarationNameInfo &NameInfo, 5109 bool isAddressOfOperand, 5110 const TemplateArgumentListInfo *TemplateArgs); 5111 5112 /// If \p D cannot be odr-used in the current expression evaluation context, 5113 /// return a reason explaining why. Otherwise, return NOUR_None. 5114 NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D); 5115 5116 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 5117 SourceLocation Loc, 5118 const CXXScopeSpec *SS = nullptr); 5119 DeclRefExpr * 5120 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 5121 const DeclarationNameInfo &NameInfo, 5122 const CXXScopeSpec *SS = nullptr, 5123 NamedDecl *FoundD = nullptr, 5124 SourceLocation TemplateKWLoc = SourceLocation(), 5125 const TemplateArgumentListInfo *TemplateArgs = nullptr); 5126 DeclRefExpr * 5127 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 5128 const DeclarationNameInfo &NameInfo, 5129 NestedNameSpecifierLoc NNS, 5130 NamedDecl *FoundD = nullptr, 5131 SourceLocation TemplateKWLoc = SourceLocation(), 5132 const TemplateArgumentListInfo *TemplateArgs = nullptr); 5133 5134 ExprResult 5135 BuildAnonymousStructUnionMemberReference( 5136 const CXXScopeSpec &SS, 5137 SourceLocation nameLoc, 5138 IndirectFieldDecl *indirectField, 5139 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none), 5140 Expr *baseObjectExpr = nullptr, 5141 SourceLocation opLoc = SourceLocation()); 5142 5143 ExprResult BuildPossibleImplicitMemberExpr( 5144 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, 5145 const TemplateArgumentListInfo *TemplateArgs, const Scope *S, 5146 UnresolvedLookupExpr *AsULE = nullptr); 5147 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, 5148 SourceLocation TemplateKWLoc, 5149 LookupResult &R, 5150 const TemplateArgumentListInfo *TemplateArgs, 5151 bool IsDefiniteInstance, 5152 const Scope *S); 5153 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, 5154 const LookupResult &R, 5155 bool HasTrailingLParen); 5156 5157 ExprResult 5158 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 5159 const DeclarationNameInfo &NameInfo, 5160 bool IsAddressOfOperand, const Scope *S, 5161 TypeSourceInfo **RecoveryTSI = nullptr); 5162 5163 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, 5164 SourceLocation TemplateKWLoc, 5165 const DeclarationNameInfo &NameInfo, 5166 const TemplateArgumentListInfo *TemplateArgs); 5167 5168 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, 5169 LookupResult &R, 5170 bool NeedsADL, 5171 bool AcceptInvalidDecl = false); 5172 ExprResult BuildDeclarationNameExpr( 5173 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 5174 NamedDecl *FoundD = nullptr, 5175 const TemplateArgumentListInfo *TemplateArgs = nullptr, 5176 bool AcceptInvalidDecl = false); 5177 5178 ExprResult BuildLiteralOperatorCall(LookupResult &R, 5179 DeclarationNameInfo &SuffixInfo, 5180 ArrayRef<Expr *> Args, 5181 SourceLocation LitEndLoc, 5182 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); 5183 5184 ExprResult BuildPredefinedExpr(SourceLocation Loc, 5185 PredefinedExpr::IdentKind IK); 5186 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); 5187 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); 5188 5189 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc); 5190 5191 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr); 5192 ExprResult ActOnCharacterConstant(const Token &Tok, 5193 Scope *UDLScope = nullptr); 5194 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); 5195 ExprResult ActOnParenListExpr(SourceLocation L, 5196 SourceLocation R, 5197 MultiExprArg Val); 5198 5199 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 5200 /// fragments (e.g. "foo" "bar" L"baz"). 5201 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks, 5202 Scope *UDLScope = nullptr); 5203 5204 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, 5205 SourceLocation DefaultLoc, 5206 SourceLocation RParenLoc, 5207 Expr *ControllingExpr, 5208 ArrayRef<ParsedType> ArgTypes, 5209 ArrayRef<Expr *> ArgExprs); 5210 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, 5211 SourceLocation DefaultLoc, 5212 SourceLocation RParenLoc, 5213 Expr *ControllingExpr, 5214 ArrayRef<TypeSourceInfo *> Types, 5215 ArrayRef<Expr *> Exprs); 5216 5217 // Binary/Unary Operators. 'Tok' is the token for the operator. 5218 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 5219 Expr *InputExpr); 5220 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, 5221 UnaryOperatorKind Opc, Expr *Input); 5222 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 5223 tok::TokenKind Op, Expr *Input); 5224 5225 bool isQualifiedMemberAccess(Expr *E); 5226 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc); 5227 5228 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 5229 SourceLocation OpLoc, 5230 UnaryExprOrTypeTrait ExprKind, 5231 SourceRange R); 5232 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 5233 UnaryExprOrTypeTrait ExprKind); 5234 ExprResult 5235 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 5236 UnaryExprOrTypeTrait ExprKind, 5237 bool IsType, void *TyOrEx, 5238 SourceRange ArgRange); 5239 5240 ExprResult CheckPlaceholderExpr(Expr *E); 5241 bool CheckVecStepExpr(Expr *E); 5242 5243 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); 5244 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, 5245 SourceRange ExprRange, 5246 UnaryExprOrTypeTrait ExprKind); 5247 ExprResult ActOnSizeofParameterPackExpr(Scope *S, 5248 SourceLocation OpLoc, 5249 IdentifierInfo &Name, 5250 SourceLocation NameLoc, 5251 SourceLocation RParenLoc); 5252 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 5253 tok::TokenKind Kind, Expr *Input); 5254 5255 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, 5256 Expr *Idx, SourceLocation RLoc); 5257 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5258 Expr *Idx, SourceLocation RLoc); 5259 5260 ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 5261 Expr *ColumnIdx, 5262 SourceLocation RBLoc); 5263 5264 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 5265 Expr *LowerBound, 5266 SourceLocation ColonLocFirst, 5267 SourceLocation ColonLocSecond, 5268 Expr *Length, Expr *Stride, 5269 SourceLocation RBLoc); 5270 ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5271 SourceLocation RParenLoc, 5272 ArrayRef<Expr *> Dims, 5273 ArrayRef<SourceRange> Brackets); 5274 5275 /// Data structure for iterator expression. 5276 struct OMPIteratorData { 5277 IdentifierInfo *DeclIdent = nullptr; 5278 SourceLocation DeclIdentLoc; 5279 ParsedType Type; 5280 OMPIteratorExpr::IteratorRange Range; 5281 SourceLocation AssignLoc; 5282 SourceLocation ColonLoc; 5283 SourceLocation SecColonLoc; 5284 }; 5285 5286 ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5287 SourceLocation LLoc, SourceLocation RLoc, 5288 ArrayRef<OMPIteratorData> Data); 5289 5290 // This struct is for use by ActOnMemberAccess to allow 5291 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after 5292 // changing the access operator from a '.' to a '->' (to see if that is the 5293 // change needed to fix an error about an unknown member, e.g. when the class 5294 // defines a custom operator->). 5295 struct ActOnMemberAccessExtraArgs { 5296 Scope *S; 5297 UnqualifiedId &Id; 5298 Decl *ObjCImpDecl; 5299 }; 5300 5301 ExprResult BuildMemberReferenceExpr( 5302 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, 5303 CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 5304 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, 5305 const TemplateArgumentListInfo *TemplateArgs, 5306 const Scope *S, 5307 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); 5308 5309 ExprResult 5310 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, 5311 bool IsArrow, const CXXScopeSpec &SS, 5312 SourceLocation TemplateKWLoc, 5313 NamedDecl *FirstQualifierInScope, LookupResult &R, 5314 const TemplateArgumentListInfo *TemplateArgs, 5315 const Scope *S, 5316 bool SuppressQualifierCheck = false, 5317 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); 5318 5319 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, 5320 SourceLocation OpLoc, 5321 const CXXScopeSpec &SS, FieldDecl *Field, 5322 DeclAccessPair FoundDecl, 5323 const DeclarationNameInfo &MemberNameInfo); 5324 5325 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); 5326 5327 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, 5328 const CXXScopeSpec &SS, 5329 const LookupResult &R); 5330 5331 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, 5332 bool IsArrow, SourceLocation OpLoc, 5333 const CXXScopeSpec &SS, 5334 SourceLocation TemplateKWLoc, 5335 NamedDecl *FirstQualifierInScope, 5336 const DeclarationNameInfo &NameInfo, 5337 const TemplateArgumentListInfo *TemplateArgs); 5338 5339 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, 5340 SourceLocation OpLoc, 5341 tok::TokenKind OpKind, 5342 CXXScopeSpec &SS, 5343 SourceLocation TemplateKWLoc, 5344 UnqualifiedId &Member, 5345 Decl *ObjCImpDecl); 5346 5347 MemberExpr * 5348 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, 5349 const CXXScopeSpec *SS, SourceLocation TemplateKWLoc, 5350 ValueDecl *Member, DeclAccessPair FoundDecl, 5351 bool HadMultipleCandidates, 5352 const DeclarationNameInfo &MemberNameInfo, QualType Ty, 5353 ExprValueKind VK, ExprObjectKind OK, 5354 const TemplateArgumentListInfo *TemplateArgs = nullptr); 5355 MemberExpr * 5356 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, 5357 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, 5358 ValueDecl *Member, DeclAccessPair FoundDecl, 5359 bool HadMultipleCandidates, 5360 const DeclarationNameInfo &MemberNameInfo, QualType Ty, 5361 ExprValueKind VK, ExprObjectKind OK, 5362 const TemplateArgumentListInfo *TemplateArgs = nullptr); 5363 5364 void ActOnDefaultCtorInitializers(Decl *CDtorDecl); 5365 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5366 FunctionDecl *FDecl, 5367 const FunctionProtoType *Proto, 5368 ArrayRef<Expr *> Args, 5369 SourceLocation RParenLoc, 5370 bool ExecConfig = false); 5371 void CheckStaticArrayArgument(SourceLocation CallLoc, 5372 ParmVarDecl *Param, 5373 const Expr *ArgExpr); 5374 5375 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5376 /// This provides the location of the left/right parens and a list of comma 5377 /// locations. 5378 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 5379 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5380 Expr *ExecConfig = nullptr); 5381 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 5382 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5383 Expr *ExecConfig = nullptr, 5384 bool IsExecConfig = false, 5385 bool AllowRecovery = false); 5386 enum class AtomicArgumentOrder { API, AST }; 5387 ExprResult 5388 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 5389 SourceLocation RParenLoc, MultiExprArg Args, 5390 AtomicExpr::AtomicOp Op, 5391 AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API); 5392 ExprResult 5393 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, 5394 ArrayRef<Expr *> Arg, SourceLocation RParenLoc, 5395 Expr *Config = nullptr, bool IsExecConfig = false, 5396 ADLCallKind UsesADL = ADLCallKind::NotADL); 5397 5398 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 5399 MultiExprArg ExecConfig, 5400 SourceLocation GGGLoc); 5401 5402 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5403 Declarator &D, ParsedType &Ty, 5404 SourceLocation RParenLoc, Expr *CastExpr); 5405 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, 5406 TypeSourceInfo *Ty, 5407 SourceLocation RParenLoc, 5408 Expr *Op); 5409 CastKind PrepareScalarCast(ExprResult &src, QualType destType); 5410 5411 /// Build an altivec or OpenCL literal. 5412 ExprResult BuildVectorLiteral(SourceLocation LParenLoc, 5413 SourceLocation RParenLoc, Expr *E, 5414 TypeSourceInfo *TInfo); 5415 5416 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); 5417 5418 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, 5419 ParsedType Ty, 5420 SourceLocation RParenLoc, 5421 Expr *InitExpr); 5422 5423 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, 5424 TypeSourceInfo *TInfo, 5425 SourceLocation RParenLoc, 5426 Expr *LiteralExpr); 5427 5428 ExprResult ActOnInitList(SourceLocation LBraceLoc, 5429 MultiExprArg InitArgList, 5430 SourceLocation RBraceLoc); 5431 5432 ExprResult BuildInitList(SourceLocation LBraceLoc, 5433 MultiExprArg InitArgList, 5434 SourceLocation RBraceLoc); 5435 5436 ExprResult ActOnDesignatedInitializer(Designation &Desig, 5437 SourceLocation EqualOrColonLoc, 5438 bool GNUSyntax, 5439 ExprResult Init); 5440 5441 private: 5442 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind); 5443 5444 public: 5445 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, 5446 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); 5447 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, 5448 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); 5449 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, 5450 Expr *LHSExpr, Expr *RHSExpr); 5451 void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 5452 UnresolvedSetImpl &Functions); 5453 5454 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc); 5455 5456 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 5457 /// in the case of a the GNU conditional expr extension. 5458 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, 5459 SourceLocation ColonLoc, 5460 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); 5461 5462 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 5463 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 5464 LabelDecl *TheDecl); 5465 5466 void ActOnStartStmtExpr(); 5467 ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 5468 SourceLocation RPLoc); 5469 ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 5470 SourceLocation RPLoc, unsigned TemplateDepth); 5471 // Handle the final expression in a statement expression. 5472 ExprResult ActOnStmtExprResult(ExprResult E); 5473 void ActOnStmtExprError(); 5474 5475 // __builtin_offsetof(type, identifier(.identifier|[expr])*) 5476 struct OffsetOfComponent { 5477 SourceLocation LocStart, LocEnd; 5478 bool isBrackets; // true if [expr], false if .ident 5479 union { 5480 IdentifierInfo *IdentInfo; 5481 Expr *E; 5482 } U; 5483 }; 5484 5485 /// __builtin_offsetof(type, a.b[123][456].c) 5486 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 5487 TypeSourceInfo *TInfo, 5488 ArrayRef<OffsetOfComponent> Components, 5489 SourceLocation RParenLoc); 5490 ExprResult ActOnBuiltinOffsetOf(Scope *S, 5491 SourceLocation BuiltinLoc, 5492 SourceLocation TypeLoc, 5493 ParsedType ParsedArgTy, 5494 ArrayRef<OffsetOfComponent> Components, 5495 SourceLocation RParenLoc); 5496 5497 // __builtin_choose_expr(constExpr, expr1, expr2) 5498 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, 5499 Expr *CondExpr, Expr *LHSExpr, 5500 Expr *RHSExpr, SourceLocation RPLoc); 5501 5502 // __builtin_va_arg(expr, type) 5503 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 5504 SourceLocation RPLoc); 5505 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, 5506 TypeSourceInfo *TInfo, SourceLocation RPLoc); 5507 5508 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(), 5509 // __builtin_COLUMN() 5510 ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 5511 SourceLocation BuiltinLoc, 5512 SourceLocation RPLoc); 5513 5514 // Build a potentially resolved SourceLocExpr. 5515 ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 5516 SourceLocation BuiltinLoc, SourceLocation RPLoc, 5517 DeclContext *ParentContext); 5518 5519 // __null 5520 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); 5521 5522 bool CheckCaseExpression(Expr *E); 5523 5524 /// Describes the result of an "if-exists" condition check. 5525 enum IfExistsResult { 5526 /// The symbol exists. 5527 IER_Exists, 5528 5529 /// The symbol does not exist. 5530 IER_DoesNotExist, 5531 5532 /// The name is a dependent name, so the results will differ 5533 /// from one instantiation to the next. 5534 IER_Dependent, 5535 5536 /// An error occurred. 5537 IER_Error 5538 }; 5539 5540 IfExistsResult 5541 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, 5542 const DeclarationNameInfo &TargetNameInfo); 5543 5544 IfExistsResult 5545 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, 5546 bool IsIfExists, CXXScopeSpec &SS, 5547 UnqualifiedId &Name); 5548 5549 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, 5550 bool IsIfExists, 5551 NestedNameSpecifierLoc QualifierLoc, 5552 DeclarationNameInfo NameInfo, 5553 Stmt *Nested); 5554 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, 5555 bool IsIfExists, 5556 CXXScopeSpec &SS, UnqualifiedId &Name, 5557 Stmt *Nested); 5558 5559 //===------------------------- "Block" Extension ------------------------===// 5560 5561 /// ActOnBlockStart - This callback is invoked when a block literal is 5562 /// started. 5563 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); 5564 5565 /// ActOnBlockArguments - This callback allows processing of block arguments. 5566 /// If there are no arguments, this is still invoked. 5567 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 5568 Scope *CurScope); 5569 5570 /// ActOnBlockError - If there is an error parsing a block, this callback 5571 /// is invoked to pop the information about the block from the action impl. 5572 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); 5573 5574 /// ActOnBlockStmtExpr - This is called when the body of a block statement 5575 /// literal was successfully completed. ^(int x){...} 5576 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, 5577 Scope *CurScope); 5578 5579 //===---------------------------- Clang Extensions ----------------------===// 5580 5581 /// __builtin_convertvector(...) 5582 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5583 SourceLocation BuiltinLoc, 5584 SourceLocation RParenLoc); 5585 5586 //===---------------------------- OpenCL Features -----------------------===// 5587 5588 /// __builtin_astype(...) 5589 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5590 SourceLocation BuiltinLoc, 5591 SourceLocation RParenLoc); 5592 ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, 5593 SourceLocation BuiltinLoc, 5594 SourceLocation RParenLoc); 5595 5596 //===---------------------------- C++ Features --------------------------===// 5597 5598 // Act on C++ namespaces 5599 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, 5600 SourceLocation NamespaceLoc, 5601 SourceLocation IdentLoc, IdentifierInfo *Ident, 5602 SourceLocation LBrace, 5603 const ParsedAttributesView &AttrList, 5604 UsingDirectiveDecl *&UsingDecl); 5605 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); 5606 5607 NamespaceDecl *getStdNamespace() const; 5608 NamespaceDecl *getOrCreateStdNamespace(); 5609 5610 NamespaceDecl *lookupStdExperimentalNamespace(); 5611 5612 CXXRecordDecl *getStdBadAlloc() const; 5613 EnumDecl *getStdAlignValT() const; 5614 5615 private: 5616 // A cache representing if we've fully checked the various comparison category 5617 // types stored in ASTContext. The bit-index corresponds to the integer value 5618 // of a ComparisonCategoryType enumerator. 5619 llvm::SmallBitVector FullyCheckedComparisonCategories; 5620 5621 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 5622 CXXScopeSpec &SS, 5623 ParsedType TemplateTypeTy, 5624 IdentifierInfo *MemberOrBase); 5625 5626 public: 5627 enum class ComparisonCategoryUsage { 5628 /// The '<=>' operator was used in an expression and a builtin operator 5629 /// was selected. 5630 OperatorInExpression, 5631 /// A defaulted 'operator<=>' needed the comparison category. This 5632 /// typically only applies to 'std::strong_ordering', due to the implicit 5633 /// fallback return value. 5634 DefaultedOperator, 5635 }; 5636 5637 /// Lookup the specified comparison category types in the standard 5638 /// library, an check the VarDecls possibly returned by the operator<=> 5639 /// builtins for that type. 5640 /// 5641 /// \return The type of the comparison category type corresponding to the 5642 /// specified Kind, or a null type if an error occurs 5643 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, 5644 SourceLocation Loc, 5645 ComparisonCategoryUsage Usage); 5646 5647 /// Tests whether Ty is an instance of std::initializer_list and, if 5648 /// it is and Element is not NULL, assigns the element type to Element. 5649 bool isStdInitializerList(QualType Ty, QualType *Element); 5650 5651 /// Looks for the std::initializer_list template and instantiates it 5652 /// with Element, or emits an error if it's not found. 5653 /// 5654 /// \returns The instantiated template, or null on error. 5655 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); 5656 5657 /// Determine whether Ctor is an initializer-list constructor, as 5658 /// defined in [dcl.init.list]p2. 5659 bool isInitListConstructor(const FunctionDecl *Ctor); 5660 5661 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, 5662 SourceLocation NamespcLoc, CXXScopeSpec &SS, 5663 SourceLocation IdentLoc, 5664 IdentifierInfo *NamespcName, 5665 const ParsedAttributesView &AttrList); 5666 5667 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); 5668 5669 Decl *ActOnNamespaceAliasDef(Scope *CurScope, 5670 SourceLocation NamespaceLoc, 5671 SourceLocation AliasLoc, 5672 IdentifierInfo *Alias, 5673 CXXScopeSpec &SS, 5674 SourceLocation IdentLoc, 5675 IdentifierInfo *Ident); 5676 5677 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); 5678 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, 5679 const LookupResult &PreviousDecls, 5680 UsingShadowDecl *&PrevShadow); 5681 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD, 5682 NamedDecl *Target, 5683 UsingShadowDecl *PrevDecl); 5684 5685 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 5686 bool HasTypenameKeyword, 5687 const CXXScopeSpec &SS, 5688 SourceLocation NameLoc, 5689 const LookupResult &Previous); 5690 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, 5691 bool HasTypename, 5692 const CXXScopeSpec &SS, 5693 const DeclarationNameInfo &NameInfo, 5694 SourceLocation NameLoc); 5695 5696 NamedDecl *BuildUsingDeclaration( 5697 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 5698 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 5699 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 5700 const ParsedAttributesView &AttrList, bool IsInstantiation); 5701 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 5702 ArrayRef<NamedDecl *> Expansions); 5703 5704 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); 5705 5706 /// Given a derived-class using shadow declaration for a constructor and the 5707 /// correspnding base class constructor, find or create the implicit 5708 /// synthesized derived class constructor to use for this initialization. 5709 CXXConstructorDecl * 5710 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, 5711 ConstructorUsingShadowDecl *DerivedShadow); 5712 5713 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, 5714 SourceLocation UsingLoc, 5715 SourceLocation TypenameLoc, CXXScopeSpec &SS, 5716 UnqualifiedId &Name, SourceLocation EllipsisLoc, 5717 const ParsedAttributesView &AttrList); 5718 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, 5719 MultiTemplateParamsArg TemplateParams, 5720 SourceLocation UsingLoc, UnqualifiedId &Name, 5721 const ParsedAttributesView &AttrList, 5722 TypeResult Type, Decl *DeclFromDeclSpec); 5723 5724 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 5725 /// including handling of its default argument expressions. 5726 /// 5727 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind 5728 ExprResult 5729 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 5730 NamedDecl *FoundDecl, 5731 CXXConstructorDecl *Constructor, MultiExprArg Exprs, 5732 bool HadMultipleCandidates, bool IsListInitialization, 5733 bool IsStdInitListInitialization, 5734 bool RequiresZeroInit, unsigned ConstructKind, 5735 SourceRange ParenRange); 5736 5737 /// Build a CXXConstructExpr whose constructor has already been resolved if 5738 /// it denotes an inherited constructor. 5739 ExprResult 5740 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 5741 CXXConstructorDecl *Constructor, bool Elidable, 5742 MultiExprArg Exprs, 5743 bool HadMultipleCandidates, bool IsListInitialization, 5744 bool IsStdInitListInitialization, 5745 bool RequiresZeroInit, unsigned ConstructKind, 5746 SourceRange ParenRange); 5747 5748 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if 5749 // the constructor can be elidable? 5750 ExprResult 5751 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 5752 NamedDecl *FoundDecl, 5753 CXXConstructorDecl *Constructor, bool Elidable, 5754 MultiExprArg Exprs, bool HadMultipleCandidates, 5755 bool IsListInitialization, 5756 bool IsStdInitListInitialization, bool RequiresZeroInit, 5757 unsigned ConstructKind, SourceRange ParenRange); 5758 5759 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field); 5760 5761 5762 /// Instantiate or parse a C++ default argument expression as necessary. 5763 /// Return true on error. 5764 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5765 ParmVarDecl *Param); 5766 5767 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating 5768 /// the default expr if needed. 5769 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5770 FunctionDecl *FD, 5771 ParmVarDecl *Param); 5772 5773 /// FinalizeVarWithDestructor - Prepare for calling destructor on the 5774 /// constructed variable. 5775 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); 5776 5777 /// Helper class that collects exception specifications for 5778 /// implicitly-declared special member functions. 5779 class ImplicitExceptionSpecification { 5780 // Pointer to allow copying 5781 Sema *Self; 5782 // We order exception specifications thus: 5783 // noexcept is the most restrictive, but is only used in C++11. 5784 // throw() comes next. 5785 // Then a throw(collected exceptions) 5786 // Finally no specification, which is expressed as noexcept(false). 5787 // throw(...) is used instead if any called function uses it. 5788 ExceptionSpecificationType ComputedEST; 5789 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; 5790 SmallVector<QualType, 4> Exceptions; 5791 ClearExceptions()5792 void ClearExceptions() { 5793 ExceptionsSeen.clear(); 5794 Exceptions.clear(); 5795 } 5796 5797 public: ImplicitExceptionSpecification(Sema & Self)5798 explicit ImplicitExceptionSpecification(Sema &Self) 5799 : Self(&Self), ComputedEST(EST_BasicNoexcept) { 5800 if (!Self.getLangOpts().CPlusPlus11) 5801 ComputedEST = EST_DynamicNone; 5802 } 5803 5804 /// Get the computed exception specification type. getExceptionSpecType()5805 ExceptionSpecificationType getExceptionSpecType() const { 5806 assert(!isComputedNoexcept(ComputedEST) && 5807 "noexcept(expr) should not be a possible result"); 5808 return ComputedEST; 5809 } 5810 5811 /// The number of exceptions in the exception specification. size()5812 unsigned size() const { return Exceptions.size(); } 5813 5814 /// The set of exceptions in the exception specification. data()5815 const QualType *data() const { return Exceptions.data(); } 5816 5817 /// Integrate another called method into the collected data. 5818 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); 5819 5820 /// Integrate an invoked expression into the collected data. CalledExpr(Expr * E)5821 void CalledExpr(Expr *E) { CalledStmt(E); } 5822 5823 /// Integrate an invoked statement into the collected data. 5824 void CalledStmt(Stmt *S); 5825 5826 /// Overwrite an EPI's exception specification with this 5827 /// computed exception specification. getExceptionSpec()5828 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const { 5829 FunctionProtoType::ExceptionSpecInfo ESI; 5830 ESI.Type = getExceptionSpecType(); 5831 if (ESI.Type == EST_Dynamic) { 5832 ESI.Exceptions = Exceptions; 5833 } else if (ESI.Type == EST_None) { 5834 /// C++11 [except.spec]p14: 5835 /// The exception-specification is noexcept(false) if the set of 5836 /// potential exceptions of the special member function contains "any" 5837 ESI.Type = EST_NoexceptFalse; 5838 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(), 5839 tok::kw_false).get(); 5840 } 5841 return ESI; 5842 } 5843 }; 5844 5845 /// Evaluate the implicit exception specification for a defaulted 5846 /// special member function. 5847 void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD); 5848 5849 /// Check the given noexcept-specifier, convert its expression, and compute 5850 /// the appropriate ExceptionSpecificationType. 5851 ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr, 5852 ExceptionSpecificationType &EST); 5853 5854 /// Check the given exception-specification and update the 5855 /// exception specification information with the results. 5856 void checkExceptionSpecification(bool IsTopLevel, 5857 ExceptionSpecificationType EST, 5858 ArrayRef<ParsedType> DynamicExceptions, 5859 ArrayRef<SourceRange> DynamicExceptionRanges, 5860 Expr *NoexceptExpr, 5861 SmallVectorImpl<QualType> &Exceptions, 5862 FunctionProtoType::ExceptionSpecInfo &ESI); 5863 5864 /// Determine if we're in a case where we need to (incorrectly) eagerly 5865 /// parse an exception specification to work around a libstdc++ bug. 5866 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D); 5867 5868 /// Add an exception-specification to the given member function 5869 /// (or member function template). The exception-specification was parsed 5870 /// after the method itself was declared. 5871 void actOnDelayedExceptionSpecification(Decl *Method, 5872 ExceptionSpecificationType EST, 5873 SourceRange SpecificationRange, 5874 ArrayRef<ParsedType> DynamicExceptions, 5875 ArrayRef<SourceRange> DynamicExceptionRanges, 5876 Expr *NoexceptExpr); 5877 5878 class InheritedConstructorInfo; 5879 5880 /// Determine if a special member function should have a deleted 5881 /// definition when it is defaulted. 5882 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5883 InheritedConstructorInfo *ICI = nullptr, 5884 bool Diagnose = false); 5885 5886 /// Produce notes explaining why a defaulted function was defined as deleted. 5887 void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD); 5888 5889 /// Declare the implicit default constructor for the given class. 5890 /// 5891 /// \param ClassDecl The class declaration into which the implicit 5892 /// default constructor will be added. 5893 /// 5894 /// \returns The implicitly-declared default constructor. 5895 CXXConstructorDecl *DeclareImplicitDefaultConstructor( 5896 CXXRecordDecl *ClassDecl); 5897 5898 /// DefineImplicitDefaultConstructor - Checks for feasibility of 5899 /// defining this constructor as the default constructor. 5900 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 5901 CXXConstructorDecl *Constructor); 5902 5903 /// Declare the implicit destructor for the given class. 5904 /// 5905 /// \param ClassDecl The class declaration into which the implicit 5906 /// destructor will be added. 5907 /// 5908 /// \returns The implicitly-declared destructor. 5909 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); 5910 5911 /// DefineImplicitDestructor - Checks for feasibility of 5912 /// defining this destructor as the default destructor. 5913 void DefineImplicitDestructor(SourceLocation CurrentLocation, 5914 CXXDestructorDecl *Destructor); 5915 5916 /// Build an exception spec for destructors that don't have one. 5917 /// 5918 /// C++11 says that user-defined destructors with no exception spec get one 5919 /// that looks as if the destructor was implicitly declared. 5920 void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor); 5921 5922 /// Define the specified inheriting constructor. 5923 void DefineInheritingConstructor(SourceLocation UseLoc, 5924 CXXConstructorDecl *Constructor); 5925 5926 /// Declare the implicit copy constructor for the given class. 5927 /// 5928 /// \param ClassDecl The class declaration into which the implicit 5929 /// copy constructor will be added. 5930 /// 5931 /// \returns The implicitly-declared copy constructor. 5932 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); 5933 5934 /// DefineImplicitCopyConstructor - Checks for feasibility of 5935 /// defining this constructor as the copy constructor. 5936 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 5937 CXXConstructorDecl *Constructor); 5938 5939 /// Declare the implicit move constructor for the given class. 5940 /// 5941 /// \param ClassDecl The Class declaration into which the implicit 5942 /// move constructor will be added. 5943 /// 5944 /// \returns The implicitly-declared move constructor, or NULL if it wasn't 5945 /// declared. 5946 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); 5947 5948 /// DefineImplicitMoveConstructor - Checks for feasibility of 5949 /// defining this constructor as the move constructor. 5950 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 5951 CXXConstructorDecl *Constructor); 5952 5953 /// Declare the implicit copy assignment operator for the given class. 5954 /// 5955 /// \param ClassDecl The class declaration into which the implicit 5956 /// copy assignment operator will be added. 5957 /// 5958 /// \returns The implicitly-declared copy assignment operator. 5959 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); 5960 5961 /// Defines an implicitly-declared copy assignment operator. 5962 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 5963 CXXMethodDecl *MethodDecl); 5964 5965 /// Declare the implicit move assignment operator for the given class. 5966 /// 5967 /// \param ClassDecl The Class declaration into which the implicit 5968 /// move assignment operator will be added. 5969 /// 5970 /// \returns The implicitly-declared move assignment operator, or NULL if it 5971 /// wasn't declared. 5972 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); 5973 5974 /// Defines an implicitly-declared move assignment operator. 5975 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 5976 CXXMethodDecl *MethodDecl); 5977 5978 /// Force the declaration of any implicitly-declared members of this 5979 /// class. 5980 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); 5981 5982 /// Check a completed declaration of an implicit special member. 5983 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD); 5984 5985 /// Determine whether the given function is an implicitly-deleted 5986 /// special member function. 5987 bool isImplicitlyDeleted(FunctionDecl *FD); 5988 5989 /// Check whether 'this' shows up in the type of a static member 5990 /// function after the (naturally empty) cv-qualifier-seq would be. 5991 /// 5992 /// \returns true if an error occurred. 5993 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); 5994 5995 /// Whether this' shows up in the exception specification of a static 5996 /// member function. 5997 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); 5998 5999 /// Check whether 'this' shows up in the attributes of the given 6000 /// static member function. 6001 /// 6002 /// \returns true if an error occurred. 6003 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); 6004 6005 /// MaybeBindToTemporary - If the passed in expression has a record type with 6006 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise 6007 /// it simply returns the passed in expression. 6008 ExprResult MaybeBindToTemporary(Expr *E); 6009 6010 /// Wrap the expression in a ConstantExpr if it is a potential immediate 6011 /// invocation. 6012 ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl); 6013 6014 bool CompleteConstructorCall(CXXConstructorDecl *Constructor, 6015 QualType DeclInitType, MultiExprArg ArgsPtr, 6016 SourceLocation Loc, 6017 SmallVectorImpl<Expr *> &ConvertedArgs, 6018 bool AllowExplicit = false, 6019 bool IsListInitialization = false); 6020 6021 ParsedType getInheritingConstructorName(CXXScopeSpec &SS, 6022 SourceLocation NameLoc, 6023 IdentifierInfo &Name); 6024 6025 ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc, 6026 Scope *S, CXXScopeSpec &SS, 6027 bool EnteringContext); 6028 ParsedType getDestructorName(SourceLocation TildeLoc, 6029 IdentifierInfo &II, SourceLocation NameLoc, 6030 Scope *S, CXXScopeSpec &SS, 6031 ParsedType ObjectType, 6032 bool EnteringContext); 6033 6034 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, 6035 ParsedType ObjectType); 6036 6037 // Checks that reinterpret casts don't have undefined behavior. 6038 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, 6039 bool IsDereference, SourceRange Range); 6040 6041 /// ActOnCXXNamedCast - Parse 6042 /// {dynamic,static,reinterpret,const,addrspace}_cast's. 6043 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, 6044 tok::TokenKind Kind, 6045 SourceLocation LAngleBracketLoc, 6046 Declarator &D, 6047 SourceLocation RAngleBracketLoc, 6048 SourceLocation LParenLoc, 6049 Expr *E, 6050 SourceLocation RParenLoc); 6051 6052 ExprResult BuildCXXNamedCast(SourceLocation OpLoc, 6053 tok::TokenKind Kind, 6054 TypeSourceInfo *Ty, 6055 Expr *E, 6056 SourceRange AngleBrackets, 6057 SourceRange Parens); 6058 6059 ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl, 6060 ExprResult Operand, 6061 SourceLocation RParenLoc); 6062 6063 ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI, 6064 Expr *Operand, SourceLocation RParenLoc); 6065 6066 ExprResult BuildCXXTypeId(QualType TypeInfoType, 6067 SourceLocation TypeidLoc, 6068 TypeSourceInfo *Operand, 6069 SourceLocation RParenLoc); 6070 ExprResult BuildCXXTypeId(QualType TypeInfoType, 6071 SourceLocation TypeidLoc, 6072 Expr *Operand, 6073 SourceLocation RParenLoc); 6074 6075 /// ActOnCXXTypeid - Parse typeid( something ). 6076 ExprResult ActOnCXXTypeid(SourceLocation OpLoc, 6077 SourceLocation LParenLoc, bool isType, 6078 void *TyOrExpr, 6079 SourceLocation RParenLoc); 6080 6081 ExprResult BuildCXXUuidof(QualType TypeInfoType, 6082 SourceLocation TypeidLoc, 6083 TypeSourceInfo *Operand, 6084 SourceLocation RParenLoc); 6085 ExprResult BuildCXXUuidof(QualType TypeInfoType, 6086 SourceLocation TypeidLoc, 6087 Expr *Operand, 6088 SourceLocation RParenLoc); 6089 6090 /// ActOnCXXUuidof - Parse __uuidof( something ). 6091 ExprResult ActOnCXXUuidof(SourceLocation OpLoc, 6092 SourceLocation LParenLoc, bool isType, 6093 void *TyOrExpr, 6094 SourceLocation RParenLoc); 6095 6096 /// Handle a C++1z fold-expression: ( expr op ... op expr ). 6097 ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS, 6098 tok::TokenKind Operator, 6099 SourceLocation EllipsisLoc, Expr *RHS, 6100 SourceLocation RParenLoc); 6101 ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, 6102 SourceLocation LParenLoc, Expr *LHS, 6103 BinaryOperatorKind Operator, 6104 SourceLocation EllipsisLoc, Expr *RHS, 6105 SourceLocation RParenLoc, 6106 Optional<unsigned> NumExpansions); 6107 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, 6108 BinaryOperatorKind Operator); 6109 6110 //// ActOnCXXThis - Parse 'this' pointer. 6111 ExprResult ActOnCXXThis(SourceLocation loc); 6112 6113 /// Build a CXXThisExpr and mark it referenced in the current context. 6114 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit); 6115 void MarkThisReferenced(CXXThisExpr *This); 6116 6117 /// Try to retrieve the type of the 'this' pointer. 6118 /// 6119 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. 6120 QualType getCurrentThisType(); 6121 6122 /// When non-NULL, the C++ 'this' expression is allowed despite the 6123 /// current context not being a non-static member function. In such cases, 6124 /// this provides the type used for 'this'. 6125 QualType CXXThisTypeOverride; 6126 6127 /// RAII object used to temporarily allow the C++ 'this' expression 6128 /// to be used, with the given qualifiers on the current class type. 6129 class CXXThisScopeRAII { 6130 Sema &S; 6131 QualType OldCXXThisTypeOverride; 6132 bool Enabled; 6133 6134 public: 6135 /// Introduce a new scope where 'this' may be allowed (when enabled), 6136 /// using the given declaration (which is either a class template or a 6137 /// class) along with the given qualifiers. 6138 /// along with the qualifiers placed on '*this'. 6139 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, 6140 bool Enabled = true); 6141 6142 ~CXXThisScopeRAII(); 6143 }; 6144 6145 /// Make sure the value of 'this' is actually available in the current 6146 /// context, if it is a potentially evaluated context. 6147 /// 6148 /// \param Loc The location at which the capture of 'this' occurs. 6149 /// 6150 /// \param Explicit Whether 'this' is explicitly captured in a lambda 6151 /// capture list. 6152 /// 6153 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index 6154 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. 6155 /// This is useful when enclosing lambdas must speculatively capture 6156 /// 'this' that may or may not be used in certain specializations of 6157 /// a nested generic lambda (depending on whether the name resolves to 6158 /// a non-static member function or a static function). 6159 /// \return returns 'true' if failed, 'false' if success. 6160 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false, 6161 bool BuildAndDiagnose = true, 6162 const unsigned *const FunctionScopeIndexToStopAt = nullptr, 6163 bool ByCopy = false); 6164 6165 /// Determine whether the given type is the type of *this that is used 6166 /// outside of the body of a member function for a type that is currently 6167 /// being defined. 6168 bool isThisOutsideMemberFunctionBody(QualType BaseType); 6169 6170 /// ActOnCXXBoolLiteral - Parse {true,false} literals. 6171 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 6172 6173 6174 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 6175 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 6176 6177 ExprResult 6178 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs, 6179 SourceLocation AtLoc, SourceLocation RParen); 6180 6181 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 6182 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); 6183 6184 //// ActOnCXXThrow - Parse throw expressions. 6185 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); 6186 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, 6187 bool IsThrownVarInScope); 6188 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E); 6189 6190 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 6191 /// Can be interpreted either as function-style casting ("int(x)") 6192 /// or class type construction ("ClassType(x,y,z)") 6193 /// or creation of a value-initialized type ("int()"). 6194 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, 6195 SourceLocation LParenOrBraceLoc, 6196 MultiExprArg Exprs, 6197 SourceLocation RParenOrBraceLoc, 6198 bool ListInitialization); 6199 6200 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, 6201 SourceLocation LParenLoc, 6202 MultiExprArg Exprs, 6203 SourceLocation RParenLoc, 6204 bool ListInitialization); 6205 6206 /// ActOnCXXNew - Parsed a C++ 'new' expression. 6207 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 6208 SourceLocation PlacementLParen, 6209 MultiExprArg PlacementArgs, 6210 SourceLocation PlacementRParen, 6211 SourceRange TypeIdParens, Declarator &D, 6212 Expr *Initializer); 6213 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, 6214 SourceLocation PlacementLParen, 6215 MultiExprArg PlacementArgs, 6216 SourceLocation PlacementRParen, 6217 SourceRange TypeIdParens, 6218 QualType AllocType, 6219 TypeSourceInfo *AllocTypeInfo, 6220 Optional<Expr *> ArraySize, 6221 SourceRange DirectInitRange, 6222 Expr *Initializer); 6223 6224 /// Determine whether \p FD is an aligned allocation or deallocation 6225 /// function that is unavailable. 6226 bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const; 6227 6228 /// Produce diagnostics if \p FD is an aligned allocation or deallocation 6229 /// function that is unavailable. 6230 void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, 6231 SourceLocation Loc); 6232 6233 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, 6234 SourceRange R); 6235 6236 /// The scope in which to find allocation functions. 6237 enum AllocationFunctionScope { 6238 /// Only look for allocation functions in the global scope. 6239 AFS_Global, 6240 /// Only look for allocation functions in the scope of the 6241 /// allocated class. 6242 AFS_Class, 6243 /// Look for allocation functions in both the global scope 6244 /// and in the scope of the allocated class. 6245 AFS_Both 6246 }; 6247 6248 /// Finds the overloads of operator new and delete that are appropriate 6249 /// for the allocation. 6250 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 6251 AllocationFunctionScope NewScope, 6252 AllocationFunctionScope DeleteScope, 6253 QualType AllocType, bool IsArray, 6254 bool &PassAlignment, MultiExprArg PlaceArgs, 6255 FunctionDecl *&OperatorNew, 6256 FunctionDecl *&OperatorDelete, 6257 bool Diagnose = true); 6258 void DeclareGlobalNewDelete(); 6259 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, 6260 ArrayRef<QualType> Params); 6261 6262 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 6263 DeclarationName Name, FunctionDecl* &Operator, 6264 bool Diagnose = true); 6265 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc, 6266 bool CanProvideSize, 6267 bool Overaligned, 6268 DeclarationName Name); 6269 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc, 6270 CXXRecordDecl *RD); 6271 6272 /// ActOnCXXDelete - Parsed a C++ 'delete' expression 6273 ExprResult ActOnCXXDelete(SourceLocation StartLoc, 6274 bool UseGlobal, bool ArrayForm, 6275 Expr *Operand); 6276 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, 6277 bool IsDelete, bool CallCanBeVirtual, 6278 bool WarnOnNonAbstractTypes, 6279 SourceLocation DtorLoc); 6280 6281 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, 6282 Expr *Operand, SourceLocation RParen); 6283 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 6284 SourceLocation RParen); 6285 6286 /// Parsed one of the type trait support pseudo-functions. 6287 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 6288 ArrayRef<ParsedType> Args, 6289 SourceLocation RParenLoc); 6290 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 6291 ArrayRef<TypeSourceInfo *> Args, 6292 SourceLocation RParenLoc); 6293 6294 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support 6295 /// pseudo-functions. 6296 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, 6297 SourceLocation KWLoc, 6298 ParsedType LhsTy, 6299 Expr *DimExpr, 6300 SourceLocation RParen); 6301 6302 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, 6303 SourceLocation KWLoc, 6304 TypeSourceInfo *TSInfo, 6305 Expr *DimExpr, 6306 SourceLocation RParen); 6307 6308 /// ActOnExpressionTrait - Parsed one of the unary type trait support 6309 /// pseudo-functions. 6310 ExprResult ActOnExpressionTrait(ExpressionTrait OET, 6311 SourceLocation KWLoc, 6312 Expr *Queried, 6313 SourceLocation RParen); 6314 6315 ExprResult BuildExpressionTrait(ExpressionTrait OET, 6316 SourceLocation KWLoc, 6317 Expr *Queried, 6318 SourceLocation RParen); 6319 6320 ExprResult ActOnStartCXXMemberReference(Scope *S, 6321 Expr *Base, 6322 SourceLocation OpLoc, 6323 tok::TokenKind OpKind, 6324 ParsedType &ObjectType, 6325 bool &MayBePseudoDestructor); 6326 6327 ExprResult BuildPseudoDestructorExpr(Expr *Base, 6328 SourceLocation OpLoc, 6329 tok::TokenKind OpKind, 6330 const CXXScopeSpec &SS, 6331 TypeSourceInfo *ScopeType, 6332 SourceLocation CCLoc, 6333 SourceLocation TildeLoc, 6334 PseudoDestructorTypeStorage DestroyedType); 6335 6336 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 6337 SourceLocation OpLoc, 6338 tok::TokenKind OpKind, 6339 CXXScopeSpec &SS, 6340 UnqualifiedId &FirstTypeName, 6341 SourceLocation CCLoc, 6342 SourceLocation TildeLoc, 6343 UnqualifiedId &SecondTypeName); 6344 6345 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 6346 SourceLocation OpLoc, 6347 tok::TokenKind OpKind, 6348 SourceLocation TildeLoc, 6349 const DeclSpec& DS); 6350 6351 /// MaybeCreateExprWithCleanups - If the current full-expression 6352 /// requires any cleanups, surround it with a ExprWithCleanups node. 6353 /// Otherwise, just returns the passed-in expression. 6354 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); 6355 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); 6356 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); 6357 6358 MaterializeTemporaryExpr * 6359 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, 6360 bool BoundToLvalueReference); 6361 ActOnFinishFullExpr(Expr * Expr,bool DiscardedValue)6362 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) { 6363 return ActOnFinishFullExpr( 6364 Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue); 6365 } 6366 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, 6367 bool DiscardedValue, bool IsConstexpr = false); 6368 StmtResult ActOnFinishFullStmt(Stmt *Stmt); 6369 6370 // Marks SS invalid if it represents an incomplete type. 6371 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); 6372 6373 DeclContext *computeDeclContext(QualType T); 6374 DeclContext *computeDeclContext(const CXXScopeSpec &SS, 6375 bool EnteringContext = false); 6376 bool isDependentScopeSpecifier(const CXXScopeSpec &SS); 6377 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); 6378 6379 /// The parser has parsed a global nested-name-specifier '::'. 6380 /// 6381 /// \param CCLoc The location of the '::'. 6382 /// 6383 /// \param SS The nested-name-specifier, which will be updated in-place 6384 /// to reflect the parsed nested-name-specifier. 6385 /// 6386 /// \returns true if an error occurred, false otherwise. 6387 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS); 6388 6389 /// The parser has parsed a '__super' nested-name-specifier. 6390 /// 6391 /// \param SuperLoc The location of the '__super' keyword. 6392 /// 6393 /// \param ColonColonLoc The location of the '::'. 6394 /// 6395 /// \param SS The nested-name-specifier, which will be updated in-place 6396 /// to reflect the parsed nested-name-specifier. 6397 /// 6398 /// \returns true if an error occurred, false otherwise. 6399 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, 6400 SourceLocation ColonColonLoc, CXXScopeSpec &SS); 6401 6402 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, 6403 bool *CanCorrect = nullptr); 6404 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); 6405 6406 /// Keeps information about an identifier in a nested-name-spec. 6407 /// 6408 struct NestedNameSpecInfo { 6409 /// The type of the object, if we're parsing nested-name-specifier in 6410 /// a member access expression. 6411 ParsedType ObjectType; 6412 6413 /// The identifier preceding the '::'. 6414 IdentifierInfo *Identifier; 6415 6416 /// The location of the identifier. 6417 SourceLocation IdentifierLoc; 6418 6419 /// The location of the '::'. 6420 SourceLocation CCLoc; 6421 6422 /// Creates info object for the most typical case. 6423 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, 6424 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType()) ObjectTypeNestedNameSpecInfo6425 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc), 6426 CCLoc(ColonColonLoc) { 6427 } 6428 NestedNameSpecInfoNestedNameSpecInfo6429 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, 6430 SourceLocation ColonColonLoc, QualType ObjectType) 6431 : ObjectType(ParsedType::make(ObjectType)), Identifier(II), 6432 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { 6433 } 6434 }; 6435 6436 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, 6437 NestedNameSpecInfo &IdInfo); 6438 6439 bool BuildCXXNestedNameSpecifier(Scope *S, 6440 NestedNameSpecInfo &IdInfo, 6441 bool EnteringContext, 6442 CXXScopeSpec &SS, 6443 NamedDecl *ScopeLookupResult, 6444 bool ErrorRecoveryLookup, 6445 bool *IsCorrectedToColon = nullptr, 6446 bool OnlyNamespace = false); 6447 6448 /// The parser has parsed a nested-name-specifier 'identifier::'. 6449 /// 6450 /// \param S The scope in which this nested-name-specifier occurs. 6451 /// 6452 /// \param IdInfo Parser information about an identifier in the 6453 /// nested-name-spec. 6454 /// 6455 /// \param EnteringContext Whether we're entering the context nominated by 6456 /// this nested-name-specifier. 6457 /// 6458 /// \param SS The nested-name-specifier, which is both an input 6459 /// parameter (the nested-name-specifier before this type) and an 6460 /// output parameter (containing the full nested-name-specifier, 6461 /// including this new type). 6462 /// 6463 /// \param ErrorRecoveryLookup If true, then this method is called to improve 6464 /// error recovery. In this case do not emit error message. 6465 /// 6466 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':' 6467 /// are allowed. The bool value pointed by this parameter is set to 'true' 6468 /// if the identifier is treated as if it was followed by ':', not '::'. 6469 /// 6470 /// \param OnlyNamespace If true, only considers namespaces in lookup. 6471 /// 6472 /// \returns true if an error occurred, false otherwise. 6473 bool ActOnCXXNestedNameSpecifier(Scope *S, 6474 NestedNameSpecInfo &IdInfo, 6475 bool EnteringContext, 6476 CXXScopeSpec &SS, 6477 bool ErrorRecoveryLookup = false, 6478 bool *IsCorrectedToColon = nullptr, 6479 bool OnlyNamespace = false); 6480 6481 ExprResult ActOnDecltypeExpression(Expr *E); 6482 6483 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, 6484 const DeclSpec &DS, 6485 SourceLocation ColonColonLoc); 6486 6487 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, 6488 NestedNameSpecInfo &IdInfo, 6489 bool EnteringContext); 6490 6491 /// The parser has parsed a nested-name-specifier 6492 /// 'template[opt] template-name < template-args >::'. 6493 /// 6494 /// \param S The scope in which this nested-name-specifier occurs. 6495 /// 6496 /// \param SS The nested-name-specifier, which is both an input 6497 /// parameter (the nested-name-specifier before this type) and an 6498 /// output parameter (containing the full nested-name-specifier, 6499 /// including this new type). 6500 /// 6501 /// \param TemplateKWLoc the location of the 'template' keyword, if any. 6502 /// \param TemplateName the template name. 6503 /// \param TemplateNameLoc The location of the template name. 6504 /// \param LAngleLoc The location of the opening angle bracket ('<'). 6505 /// \param TemplateArgs The template arguments. 6506 /// \param RAngleLoc The location of the closing angle bracket ('>'). 6507 /// \param CCLoc The location of the '::'. 6508 /// 6509 /// \param EnteringContext Whether we're entering the context of the 6510 /// nested-name-specifier. 6511 /// 6512 /// 6513 /// \returns true if an error occurred, false otherwise. 6514 bool ActOnCXXNestedNameSpecifier(Scope *S, 6515 CXXScopeSpec &SS, 6516 SourceLocation TemplateKWLoc, 6517 TemplateTy TemplateName, 6518 SourceLocation TemplateNameLoc, 6519 SourceLocation LAngleLoc, 6520 ASTTemplateArgsPtr TemplateArgs, 6521 SourceLocation RAngleLoc, 6522 SourceLocation CCLoc, 6523 bool EnteringContext); 6524 6525 /// Given a C++ nested-name-specifier, produce an annotation value 6526 /// that the parser can use later to reconstruct the given 6527 /// nested-name-specifier. 6528 /// 6529 /// \param SS A nested-name-specifier. 6530 /// 6531 /// \returns A pointer containing all of the information in the 6532 /// nested-name-specifier \p SS. 6533 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); 6534 6535 /// Given an annotation pointer for a nested-name-specifier, restore 6536 /// the nested-name-specifier structure. 6537 /// 6538 /// \param Annotation The annotation pointer, produced by 6539 /// \c SaveNestedNameSpecifierAnnotation(). 6540 /// 6541 /// \param AnnotationRange The source range corresponding to the annotation. 6542 /// 6543 /// \param SS The nested-name-specifier that will be updated with the contents 6544 /// of the annotation pointer. 6545 void RestoreNestedNameSpecifierAnnotation(void *Annotation, 6546 SourceRange AnnotationRange, 6547 CXXScopeSpec &SS); 6548 6549 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 6550 6551 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global 6552 /// scope or nested-name-specifier) is parsed, part of a declarator-id. 6553 /// After this method is called, according to [C++ 3.4.3p3], names should be 6554 /// looked up in the declarator-id's scope, until the declarator is parsed and 6555 /// ActOnCXXExitDeclaratorScope is called. 6556 /// The 'SS' should be a non-empty valid CXXScopeSpec. 6557 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); 6558 6559 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously 6560 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same 6561 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. 6562 /// Used to indicate that names should revert to being looked up in the 6563 /// defining scope. 6564 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 6565 6566 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an 6567 /// initializer for the declaration 'Dcl'. 6568 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 6569 /// static data member of class X, names should be looked up in the scope of 6570 /// class X. 6571 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); 6572 6573 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 6574 /// initializer for the declaration 'Dcl'. 6575 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); 6576 6577 /// Create a new lambda closure type. 6578 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, 6579 TypeSourceInfo *Info, 6580 bool KnownDependent, 6581 LambdaCaptureDefault CaptureDefault); 6582 6583 /// Start the definition of a lambda expression. 6584 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class, 6585 SourceRange IntroducerRange, 6586 TypeSourceInfo *MethodType, 6587 SourceLocation EndLoc, 6588 ArrayRef<ParmVarDecl *> Params, 6589 ConstexprSpecKind ConstexprKind, 6590 Expr *TrailingRequiresClause); 6591 6592 /// Number lambda for linkage purposes if necessary. 6593 void handleLambdaNumbering( 6594 CXXRecordDecl *Class, CXXMethodDecl *Method, 6595 Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling = None); 6596 6597 /// Endow the lambda scope info with the relevant properties. 6598 void buildLambdaScope(sema::LambdaScopeInfo *LSI, 6599 CXXMethodDecl *CallOperator, 6600 SourceRange IntroducerRange, 6601 LambdaCaptureDefault CaptureDefault, 6602 SourceLocation CaptureDefaultLoc, 6603 bool ExplicitParams, 6604 bool ExplicitResultType, 6605 bool Mutable); 6606 6607 /// Perform initialization analysis of the init-capture and perform 6608 /// any implicit conversions such as an lvalue-to-rvalue conversion if 6609 /// not being used to initialize a reference. actOnLambdaInitCaptureInitialization(SourceLocation Loc,bool ByRef,SourceLocation EllipsisLoc,IdentifierInfo * Id,LambdaCaptureInitKind InitKind,Expr * & Init)6610 ParsedType actOnLambdaInitCaptureInitialization( 6611 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, 6612 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) { 6613 return ParsedType::make(buildLambdaInitCaptureInitialization( 6614 Loc, ByRef, EllipsisLoc, None, Id, 6615 InitKind != LambdaCaptureInitKind::CopyInit, Init)); 6616 } 6617 QualType buildLambdaInitCaptureInitialization( 6618 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, 6619 Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit, 6620 Expr *&Init); 6621 6622 /// Create a dummy variable within the declcontext of the lambda's 6623 /// call operator, for name lookup purposes for a lambda init capture. 6624 /// 6625 /// CodeGen handles emission of lambda captures, ignoring these dummy 6626 /// variables appropriately. 6627 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc, 6628 QualType InitCaptureType, 6629 SourceLocation EllipsisLoc, 6630 IdentifierInfo *Id, 6631 unsigned InitStyle, Expr *Init); 6632 6633 /// Add an init-capture to a lambda scope. 6634 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var); 6635 6636 /// Note that we have finished the explicit captures for the 6637 /// given lambda. 6638 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); 6639 6640 /// \brief This is called after parsing the explicit template parameter list 6641 /// on a lambda (if it exists) in C++2a. 6642 void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc, 6643 ArrayRef<NamedDecl *> TParams, 6644 SourceLocation RAngleLoc, 6645 ExprResult RequiresClause); 6646 6647 /// Introduce the lambda parameters into scope. 6648 void addLambdaParameters( 6649 ArrayRef<LambdaIntroducer::LambdaCapture> Captures, 6650 CXXMethodDecl *CallOperator, Scope *CurScope); 6651 6652 /// Deduce a block or lambda's return type based on the return 6653 /// statements present in the body. 6654 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); 6655 6656 /// ActOnStartOfLambdaDefinition - This is called just before we start 6657 /// parsing the body of a lambda; it analyzes the explicit captures and 6658 /// arguments, and sets up various data-structures for the body of the 6659 /// lambda. 6660 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, 6661 Declarator &ParamInfo, Scope *CurScope); 6662 6663 /// ActOnLambdaError - If there is an error parsing a lambda, this callback 6664 /// is invoked to pop the information about the lambda. 6665 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, 6666 bool IsInstantiation = false); 6667 6668 /// ActOnLambdaExpr - This is called when the body of a lambda expression 6669 /// was successfully completed. 6670 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, 6671 Scope *CurScope); 6672 6673 /// Does copying/destroying the captured variable have side effects? 6674 bool CaptureHasSideEffects(const sema::Capture &From); 6675 6676 /// Diagnose if an explicit lambda capture is unused. Returns true if a 6677 /// diagnostic is emitted. 6678 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, 6679 const sema::Capture &From); 6680 6681 /// Build a FieldDecl suitable to hold the given capture. 6682 FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture); 6683 6684 /// Initialize the given capture with a suitable expression. 6685 ExprResult BuildCaptureInit(const sema::Capture &Capture, 6686 SourceLocation ImplicitCaptureLoc, 6687 bool IsOpenMPMapping = false); 6688 6689 /// Complete a lambda-expression having processed and attached the 6690 /// lambda body. 6691 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, 6692 sema::LambdaScopeInfo *LSI); 6693 6694 /// Get the return type to use for a lambda's conversion function(s) to 6695 /// function pointer type, given the type of the call operator. 6696 QualType 6697 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType, 6698 CallingConv CC); 6699 6700 /// Define the "body" of the conversion from a lambda object to a 6701 /// function pointer. 6702 /// 6703 /// This routine doesn't actually define a sensible body; rather, it fills 6704 /// in the initialization expression needed to copy the lambda object into 6705 /// the block, and IR generation actually generates the real body of the 6706 /// block pointer conversion. 6707 void DefineImplicitLambdaToFunctionPointerConversion( 6708 SourceLocation CurrentLoc, CXXConversionDecl *Conv); 6709 6710 /// Define the "body" of the conversion from a lambda object to a 6711 /// block pointer. 6712 /// 6713 /// This routine doesn't actually define a sensible body; rather, it fills 6714 /// in the initialization expression needed to copy the lambda object into 6715 /// the block, and IR generation actually generates the real body of the 6716 /// block pointer conversion. 6717 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, 6718 CXXConversionDecl *Conv); 6719 6720 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, 6721 SourceLocation ConvLocation, 6722 CXXConversionDecl *Conv, 6723 Expr *Src); 6724 6725 /// Check whether the given expression is a valid constraint expression. 6726 /// A diagnostic is emitted if it is not, false is returned, and 6727 /// PossibleNonPrimary will be set to true if the failure might be due to a 6728 /// non-primary expression being used as an atomic constraint. 6729 bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(), 6730 bool *PossibleNonPrimary = nullptr, 6731 bool IsTrailingRequiresClause = false); 6732 6733 private: 6734 /// Caches pairs of template-like decls whose associated constraints were 6735 /// checked for subsumption and whether or not the first's constraints did in 6736 /// fact subsume the second's. 6737 llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache; 6738 /// Caches the normalized associated constraints of declarations (concepts or 6739 /// constrained declarations). If an error occurred while normalizing the 6740 /// associated constraints of the template or concept, nullptr will be cached 6741 /// here. 6742 llvm::DenseMap<NamedDecl *, NormalizedConstraint *> 6743 NormalizationCache; 6744 6745 llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &> 6746 SatisfactionCache; 6747 6748 public: 6749 const NormalizedConstraint * 6750 getNormalizedAssociatedConstraints( 6751 NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints); 6752 6753 /// \brief Check whether the given declaration's associated constraints are 6754 /// at least as constrained than another declaration's according to the 6755 /// partial ordering of constraints. 6756 /// 6757 /// \param Result If no error occurred, receives the result of true if D1 is 6758 /// at least constrained than D2, and false otherwise. 6759 /// 6760 /// \returns true if an error occurred, false otherwise. 6761 bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1, 6762 NamedDecl *D2, ArrayRef<const Expr *> AC2, 6763 bool &Result); 6764 6765 /// If D1 was not at least as constrained as D2, but would've been if a pair 6766 /// of atomic constraints involved had been declared in a concept and not 6767 /// repeated in two separate places in code. 6768 /// \returns true if such a diagnostic was emitted, false otherwise. 6769 bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1, 6770 ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2); 6771 6772 /// \brief Check whether the given list of constraint expressions are 6773 /// satisfied (as if in a 'conjunction') given template arguments. 6774 /// \param Template the template-like entity that triggered the constraints 6775 /// check (either a concept or a constrained entity). 6776 /// \param ConstraintExprs a list of constraint expressions, treated as if 6777 /// they were 'AND'ed together. 6778 /// \param TemplateArgs the list of template arguments to substitute into the 6779 /// constraint expression. 6780 /// \param TemplateIDRange The source range of the template id that 6781 /// caused the constraints check. 6782 /// \param Satisfaction if true is returned, will contain details of the 6783 /// satisfaction, with enough information to diagnose an unsatisfied 6784 /// expression. 6785 /// \returns true if an error occurred and satisfaction could not be checked, 6786 /// false otherwise. 6787 bool CheckConstraintSatisfaction( 6788 const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs, 6789 ArrayRef<TemplateArgument> TemplateArgs, 6790 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction); 6791 6792 /// \brief Check whether the given non-dependent constraint expression is 6793 /// satisfied. Returns false and updates Satisfaction with the satisfaction 6794 /// verdict if successful, emits a diagnostic and returns true if an error 6795 /// occured and satisfaction could not be determined. 6796 /// 6797 /// \returns true if an error occurred, false otherwise. 6798 bool CheckConstraintSatisfaction(const Expr *ConstraintExpr, 6799 ConstraintSatisfaction &Satisfaction); 6800 6801 /// Check whether the given function decl's trailing requires clause is 6802 /// satisfied, if any. Returns false and updates Satisfaction with the 6803 /// satisfaction verdict if successful, emits a diagnostic and returns true if 6804 /// an error occured and satisfaction could not be determined. 6805 /// 6806 /// \returns true if an error occurred, false otherwise. 6807 bool CheckFunctionConstraints(const FunctionDecl *FD, 6808 ConstraintSatisfaction &Satisfaction, 6809 SourceLocation UsageLoc = SourceLocation()); 6810 6811 6812 /// \brief Ensure that the given template arguments satisfy the constraints 6813 /// associated with the given template, emitting a diagnostic if they do not. 6814 /// 6815 /// \param Template The template to which the template arguments are being 6816 /// provided. 6817 /// 6818 /// \param TemplateArgs The converted, canonicalized template arguments. 6819 /// 6820 /// \param TemplateIDRange The source range of the template id that 6821 /// caused the constraints check. 6822 /// 6823 /// \returns true if the constrains are not satisfied or could not be checked 6824 /// for satisfaction, false if the constraints are satisfied. 6825 bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, 6826 ArrayRef<TemplateArgument> TemplateArgs, 6827 SourceRange TemplateIDRange); 6828 6829 /// \brief Emit diagnostics explaining why a constraint expression was deemed 6830 /// unsatisfied. 6831 /// \param First whether this is the first time an unsatisfied constraint is 6832 /// diagnosed for this error. 6833 void 6834 DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, 6835 bool First = true); 6836 6837 /// \brief Emit diagnostics explaining why a constraint expression was deemed 6838 /// unsatisfied. 6839 void 6840 DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction, 6841 bool First = true); 6842 6843 // ParseObjCStringLiteral - Parse Objective-C string literals. 6844 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, 6845 ArrayRef<Expr *> Strings); 6846 6847 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); 6848 6849 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the 6850 /// numeric literal expression. Type of the expression will be "NSNumber *" 6851 /// or "id" if NSNumber is unavailable. 6852 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); 6853 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, 6854 bool Value); 6855 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); 6856 6857 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the 6858 /// '@' prefixed parenthesized expression. The type of the expression will 6859 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type 6860 /// of ValueType, which is allowed to be a built-in numeric type, "char *", 6861 /// "const char *" or C structure with attribute 'objc_boxable'. 6862 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); 6863 6864 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, 6865 Expr *IndexExpr, 6866 ObjCMethodDecl *getterMethod, 6867 ObjCMethodDecl *setterMethod); 6868 6869 ExprResult BuildObjCDictionaryLiteral(SourceRange SR, 6870 MutableArrayRef<ObjCDictionaryElement> Elements); 6871 6872 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, 6873 TypeSourceInfo *EncodedTypeInfo, 6874 SourceLocation RParenLoc); 6875 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, 6876 CXXConversionDecl *Method, 6877 bool HadMultipleCandidates); 6878 6879 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, 6880 SourceLocation EncodeLoc, 6881 SourceLocation LParenLoc, 6882 ParsedType Ty, 6883 SourceLocation RParenLoc); 6884 6885 /// ParseObjCSelectorExpression - Build selector expression for \@selector 6886 ExprResult ParseObjCSelectorExpression(Selector Sel, 6887 SourceLocation AtLoc, 6888 SourceLocation SelLoc, 6889 SourceLocation LParenLoc, 6890 SourceLocation RParenLoc, 6891 bool WarnMultipleSelectors); 6892 6893 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol 6894 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, 6895 SourceLocation AtLoc, 6896 SourceLocation ProtoLoc, 6897 SourceLocation LParenLoc, 6898 SourceLocation ProtoIdLoc, 6899 SourceLocation RParenLoc); 6900 6901 //===--------------------------------------------------------------------===// 6902 // C++ Declarations 6903 // 6904 Decl *ActOnStartLinkageSpecification(Scope *S, 6905 SourceLocation ExternLoc, 6906 Expr *LangStr, 6907 SourceLocation LBraceLoc); 6908 Decl *ActOnFinishLinkageSpecification(Scope *S, 6909 Decl *LinkageSpec, 6910 SourceLocation RBraceLoc); 6911 6912 6913 //===--------------------------------------------------------------------===// 6914 // C++ Classes 6915 // 6916 CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS); 6917 bool isCurrentClassName(const IdentifierInfo &II, Scope *S, 6918 const CXXScopeSpec *SS = nullptr); 6919 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS); 6920 6921 bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 6922 SourceLocation ColonLoc, 6923 const ParsedAttributesView &Attrs); 6924 6925 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, 6926 Declarator &D, 6927 MultiTemplateParamsArg TemplateParameterLists, 6928 Expr *BitfieldWidth, const VirtSpecifiers &VS, 6929 InClassInitStyle InitStyle); 6930 6931 void ActOnStartCXXInClassMemberInitializer(); 6932 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, 6933 SourceLocation EqualLoc, 6934 Expr *Init); 6935 6936 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 6937 Scope *S, 6938 CXXScopeSpec &SS, 6939 IdentifierInfo *MemberOrBase, 6940 ParsedType TemplateTypeTy, 6941 const DeclSpec &DS, 6942 SourceLocation IdLoc, 6943 SourceLocation LParenLoc, 6944 ArrayRef<Expr *> Args, 6945 SourceLocation RParenLoc, 6946 SourceLocation EllipsisLoc); 6947 6948 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 6949 Scope *S, 6950 CXXScopeSpec &SS, 6951 IdentifierInfo *MemberOrBase, 6952 ParsedType TemplateTypeTy, 6953 const DeclSpec &DS, 6954 SourceLocation IdLoc, 6955 Expr *InitList, 6956 SourceLocation EllipsisLoc); 6957 6958 MemInitResult BuildMemInitializer(Decl *ConstructorD, 6959 Scope *S, 6960 CXXScopeSpec &SS, 6961 IdentifierInfo *MemberOrBase, 6962 ParsedType TemplateTypeTy, 6963 const DeclSpec &DS, 6964 SourceLocation IdLoc, 6965 Expr *Init, 6966 SourceLocation EllipsisLoc); 6967 6968 MemInitResult BuildMemberInitializer(ValueDecl *Member, 6969 Expr *Init, 6970 SourceLocation IdLoc); 6971 6972 MemInitResult BuildBaseInitializer(QualType BaseType, 6973 TypeSourceInfo *BaseTInfo, 6974 Expr *Init, 6975 CXXRecordDecl *ClassDecl, 6976 SourceLocation EllipsisLoc); 6977 6978 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, 6979 Expr *Init, 6980 CXXRecordDecl *ClassDecl); 6981 6982 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, 6983 CXXCtorInitializer *Initializer); 6984 6985 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 6986 ArrayRef<CXXCtorInitializer *> Initializers = None); 6987 6988 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); 6989 6990 6991 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, 6992 /// mark all the non-trivial destructors of its members and bases as 6993 /// referenced. 6994 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, 6995 CXXRecordDecl *Record); 6996 6997 /// Mark destructors of virtual bases of this class referenced. In the Itanium 6998 /// C++ ABI, this is done when emitting a destructor for any non-abstract 6999 /// class. In the Microsoft C++ ABI, this is done any time a class's 7000 /// destructor is referenced. 7001 void MarkVirtualBaseDestructorsReferenced( 7002 SourceLocation Location, CXXRecordDecl *ClassDecl, 7003 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr); 7004 7005 /// Do semantic checks to allow the complete destructor variant to be emitted 7006 /// when the destructor is defined in another translation unit. In the Itanium 7007 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they 7008 /// can be emitted in separate TUs. To emit the complete variant, run a subset 7009 /// of the checks performed when emitting a regular destructor. 7010 void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, 7011 CXXDestructorDecl *Dtor); 7012 7013 /// The list of classes whose vtables have been used within 7014 /// this translation unit, and the source locations at which the 7015 /// first use occurred. 7016 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; 7017 7018 /// The list of vtables that are required but have not yet been 7019 /// materialized. 7020 SmallVector<VTableUse, 16> VTableUses; 7021 7022 /// The set of classes whose vtables have been used within 7023 /// this translation unit, and a bit that will be true if the vtable is 7024 /// required to be emitted (otherwise, it should be emitted only if needed 7025 /// by code generation). 7026 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; 7027 7028 /// Load any externally-stored vtable uses. 7029 void LoadExternalVTableUses(); 7030 7031 /// Note that the vtable for the given class was used at the 7032 /// given location. 7033 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 7034 bool DefinitionRequired = false); 7035 7036 /// Mark the exception specifications of all virtual member functions 7037 /// in the given class as needed. 7038 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 7039 const CXXRecordDecl *RD); 7040 7041 /// MarkVirtualMembersReferenced - Will mark all members of the given 7042 /// CXXRecordDecl referenced. 7043 void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, 7044 bool ConstexprOnly = false); 7045 7046 /// Define all of the vtables that have been used in this 7047 /// translation unit and reference any virtual members used by those 7048 /// vtables. 7049 /// 7050 /// \returns true if any work was done, false otherwise. 7051 bool DefineUsedVTables(); 7052 7053 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); 7054 7055 void ActOnMemInitializers(Decl *ConstructorDecl, 7056 SourceLocation ColonLoc, 7057 ArrayRef<CXXCtorInitializer*> MemInits, 7058 bool AnyErrors); 7059 7060 /// Check class-level dllimport/dllexport attribute. The caller must 7061 /// ensure that referenceDLLExportedClassMethods is called some point later 7062 /// when all outer classes of Class are complete. 7063 void checkClassLevelDLLAttribute(CXXRecordDecl *Class); 7064 void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class); 7065 7066 void referenceDLLExportedClassMethods(); 7067 7068 void propagateDLLAttrToBaseClassTemplate( 7069 CXXRecordDecl *Class, Attr *ClassAttr, 7070 ClassTemplateSpecializationDecl *BaseTemplateSpec, 7071 SourceLocation BaseLoc); 7072 7073 /// Add gsl::Pointer attribute to std::container::iterator 7074 /// \param ND The declaration that introduces the name 7075 /// std::container::iterator. \param UnderlyingRecord The record named by ND. 7076 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord); 7077 7078 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types. 7079 void inferGslOwnerPointerAttribute(CXXRecordDecl *Record); 7080 7081 /// Add [[gsl::Pointer]] attributes for std:: types. 7082 void inferGslPointerAttribute(TypedefNameDecl *TD); 7083 7084 void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record); 7085 7086 /// Check that the C++ class annoated with "trivial_abi" satisfies all the 7087 /// conditions that are needed for the attribute to have an effect. 7088 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD); 7089 7090 void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, 7091 Decl *TagDecl, SourceLocation LBrac, 7092 SourceLocation RBrac, 7093 const ParsedAttributesView &AttrList); 7094 void ActOnFinishCXXMemberDecls(); 7095 void ActOnFinishCXXNonNestedClass(); 7096 7097 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param); 7098 unsigned ActOnReenterTemplateScope(Decl *Template, 7099 llvm::function_ref<Scope *()> EnterScope); 7100 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); 7101 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 7102 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); 7103 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); 7104 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 7105 void ActOnFinishDelayedMemberInitializers(Decl *Record); 7106 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, 7107 CachedTokens &Toks); 7108 void UnmarkAsLateParsedTemplate(FunctionDecl *FD); 7109 bool IsInsideALocalClassWithinATemplateFunction(); 7110 7111 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 7112 Expr *AssertExpr, 7113 Expr *AssertMessageExpr, 7114 SourceLocation RParenLoc); 7115 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 7116 Expr *AssertExpr, 7117 StringLiteral *AssertMessageExpr, 7118 SourceLocation RParenLoc, 7119 bool Failed); 7120 7121 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, 7122 SourceLocation FriendLoc, 7123 TypeSourceInfo *TSInfo); 7124 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 7125 MultiTemplateParamsArg TemplateParams); 7126 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, 7127 MultiTemplateParamsArg TemplateParams); 7128 7129 QualType CheckConstructorDeclarator(Declarator &D, QualType R, 7130 StorageClass& SC); 7131 void CheckConstructor(CXXConstructorDecl *Constructor); 7132 QualType CheckDestructorDeclarator(Declarator &D, QualType R, 7133 StorageClass& SC); 7134 bool CheckDestructor(CXXDestructorDecl *Destructor); 7135 void CheckConversionDeclarator(Declarator &D, QualType &R, 7136 StorageClass& SC); 7137 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); 7138 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 7139 StorageClass &SC); 7140 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD); 7141 7142 void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD); 7143 7144 bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 7145 CXXSpecialMember CSM); 7146 void CheckDelayedMemberExceptionSpecs(); 7147 7148 bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, 7149 DefaultedComparisonKind DCK); 7150 void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 7151 FunctionDecl *Spaceship); 7152 void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, 7153 DefaultedComparisonKind DCK); 7154 7155 //===--------------------------------------------------------------------===// 7156 // C++ Derived Classes 7157 // 7158 7159 /// ActOnBaseSpecifier - Parsed a base specifier 7160 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, 7161 SourceRange SpecifierRange, 7162 bool Virtual, AccessSpecifier Access, 7163 TypeSourceInfo *TInfo, 7164 SourceLocation EllipsisLoc); 7165 7166 BaseResult ActOnBaseSpecifier(Decl *classdecl, 7167 SourceRange SpecifierRange, 7168 ParsedAttributes &Attrs, 7169 bool Virtual, AccessSpecifier Access, 7170 ParsedType basetype, 7171 SourceLocation BaseLoc, 7172 SourceLocation EllipsisLoc); 7173 7174 bool AttachBaseSpecifiers(CXXRecordDecl *Class, 7175 MutableArrayRef<CXXBaseSpecifier *> Bases); 7176 void ActOnBaseSpecifiers(Decl *ClassDecl, 7177 MutableArrayRef<CXXBaseSpecifier *> Bases); 7178 7179 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base); 7180 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 7181 CXXBasePaths &Paths); 7182 7183 // FIXME: I don't like this name. 7184 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); 7185 7186 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 7187 SourceLocation Loc, SourceRange Range, 7188 CXXCastPath *BasePath = nullptr, 7189 bool IgnoreAccess = false); 7190 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 7191 unsigned InaccessibleBaseID, 7192 unsigned AmbiguousBaseConvID, 7193 SourceLocation Loc, SourceRange Range, 7194 DeclarationName Name, 7195 CXXCastPath *BasePath, 7196 bool IgnoreAccess = false); 7197 7198 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); 7199 7200 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 7201 const CXXMethodDecl *Old); 7202 7203 /// CheckOverridingFunctionReturnType - Checks whether the return types are 7204 /// covariant, according to C++ [class.virtual]p5. 7205 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 7206 const CXXMethodDecl *Old); 7207 7208 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception 7209 /// spec is a subset of base spec. 7210 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, 7211 const CXXMethodDecl *Old); 7212 7213 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); 7214 7215 /// CheckOverrideControl - Check C++11 override control semantics. 7216 void CheckOverrideControl(NamedDecl *D); 7217 7218 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was 7219 /// not used in the declaration of an overriding method. 7220 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent); 7221 7222 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function 7223 /// overrides a virtual member function marked 'final', according to 7224 /// C++11 [class.virtual]p4. 7225 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 7226 const CXXMethodDecl *Old); 7227 7228 7229 //===--------------------------------------------------------------------===// 7230 // C++ Access Control 7231 // 7232 7233 enum AccessResult { 7234 AR_accessible, 7235 AR_inaccessible, 7236 AR_dependent, 7237 AR_delayed 7238 }; 7239 7240 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, 7241 NamedDecl *PrevMemberDecl, 7242 AccessSpecifier LexicalAS); 7243 7244 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, 7245 DeclAccessPair FoundDecl); 7246 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, 7247 DeclAccessPair FoundDecl); 7248 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, 7249 SourceRange PlacementRange, 7250 CXXRecordDecl *NamingClass, 7251 DeclAccessPair FoundDecl, 7252 bool Diagnose = true); 7253 AccessResult CheckConstructorAccess(SourceLocation Loc, 7254 CXXConstructorDecl *D, 7255 DeclAccessPair FoundDecl, 7256 const InitializedEntity &Entity, 7257 bool IsCopyBindingRefToTemp = false); 7258 AccessResult CheckConstructorAccess(SourceLocation Loc, 7259 CXXConstructorDecl *D, 7260 DeclAccessPair FoundDecl, 7261 const InitializedEntity &Entity, 7262 const PartialDiagnostic &PDiag); 7263 AccessResult CheckDestructorAccess(SourceLocation Loc, 7264 CXXDestructorDecl *Dtor, 7265 const PartialDiagnostic &PDiag, 7266 QualType objectType = QualType()); 7267 AccessResult CheckFriendAccess(NamedDecl *D); 7268 AccessResult CheckMemberAccess(SourceLocation UseLoc, 7269 CXXRecordDecl *NamingClass, 7270 DeclAccessPair Found); 7271 AccessResult 7272 CheckStructuredBindingMemberAccess(SourceLocation UseLoc, 7273 CXXRecordDecl *DecomposedClass, 7274 DeclAccessPair Field); 7275 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, 7276 Expr *ObjectExpr, 7277 Expr *ArgExpr, 7278 DeclAccessPair FoundDecl); 7279 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, 7280 DeclAccessPair FoundDecl); 7281 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, 7282 QualType Base, QualType Derived, 7283 const CXXBasePath &Path, 7284 unsigned DiagID, 7285 bool ForceCheck = false, 7286 bool ForceUnprivileged = false); 7287 void CheckLookupAccess(const LookupResult &R); 7288 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass, 7289 QualType BaseType); 7290 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, 7291 DeclAccessPair Found, QualType ObjectType, 7292 SourceLocation Loc, 7293 const PartialDiagnostic &Diag); isMemberAccessibleForDeletion(CXXRecordDecl * NamingClass,DeclAccessPair Found,QualType ObjectType)7294 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, 7295 DeclAccessPair Found, 7296 QualType ObjectType) { 7297 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType, 7298 SourceLocation(), PDiag()); 7299 } 7300 7301 void HandleDependentAccessCheck(const DependentDiagnostic &DD, 7302 const MultiLevelTemplateArgumentList &TemplateArgs); 7303 void PerformDependentDiagnostics(const DeclContext *Pattern, 7304 const MultiLevelTemplateArgumentList &TemplateArgs); 7305 7306 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 7307 7308 /// When true, access checking violations are treated as SFINAE 7309 /// failures rather than hard errors. 7310 bool AccessCheckingSFINAE; 7311 7312 enum AbstractDiagSelID { 7313 AbstractNone = -1, 7314 AbstractReturnType, 7315 AbstractParamType, 7316 AbstractVariableType, 7317 AbstractFieldType, 7318 AbstractIvarType, 7319 AbstractSynthesizedIvarType, 7320 AbstractArrayType 7321 }; 7322 7323 bool isAbstractType(SourceLocation Loc, QualType T); 7324 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 7325 TypeDiagnoser &Diagnoser); 7326 template <typename... Ts> RequireNonAbstractType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)7327 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, 7328 const Ts &...Args) { 7329 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 7330 return RequireNonAbstractType(Loc, T, Diagnoser); 7331 } 7332 7333 void DiagnoseAbstractType(const CXXRecordDecl *RD); 7334 7335 //===--------------------------------------------------------------------===// 7336 // C++ Overloaded Operators [C++ 13.5] 7337 // 7338 7339 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); 7340 7341 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); 7342 7343 //===--------------------------------------------------------------------===// 7344 // C++ Templates [C++ 14] 7345 // 7346 void FilterAcceptableTemplateNames(LookupResult &R, 7347 bool AllowFunctionTemplates = true, 7348 bool AllowDependent = true); 7349 bool hasAnyAcceptableTemplateNames(LookupResult &R, 7350 bool AllowFunctionTemplates = true, 7351 bool AllowDependent = true, 7352 bool AllowNonTemplateFunctions = false); 7353 /// Try to interpret the lookup result D as a template-name. 7354 /// 7355 /// \param D A declaration found by name lookup. 7356 /// \param AllowFunctionTemplates Whether function templates should be 7357 /// considered valid results. 7358 /// \param AllowDependent Whether unresolved using declarations (that might 7359 /// name templates) should be considered valid results. 7360 static NamedDecl *getAsTemplateNameDecl(NamedDecl *D, 7361 bool AllowFunctionTemplates = true, 7362 bool AllowDependent = true); 7363 7364 enum TemplateNameIsRequiredTag { TemplateNameIsRequired }; 7365 /// Whether and why a template name is required in this lookup. 7366 class RequiredTemplateKind { 7367 public: 7368 /// Template name is required if TemplateKWLoc is valid. 7369 RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation()) TemplateKW(TemplateKWLoc)7370 : TemplateKW(TemplateKWLoc) {} 7371 /// Template name is unconditionally required. RequiredTemplateKind(TemplateNameIsRequiredTag)7372 RequiredTemplateKind(TemplateNameIsRequiredTag) : TemplateKW() {} 7373 getTemplateKeywordLoc()7374 SourceLocation getTemplateKeywordLoc() const { 7375 return TemplateKW.getValueOr(SourceLocation()); 7376 } hasTemplateKeyword()7377 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } isRequired()7378 bool isRequired() const { return TemplateKW != SourceLocation(); } 7379 explicit operator bool() const { return isRequired(); } 7380 7381 private: 7382 llvm::Optional<SourceLocation> TemplateKW; 7383 }; 7384 7385 enum class AssumedTemplateKind { 7386 /// This is not assumed to be a template name. 7387 None, 7388 /// This is assumed to be a template name because lookup found nothing. 7389 FoundNothing, 7390 /// This is assumed to be a template name because lookup found one or more 7391 /// functions (but no function templates). 7392 FoundFunctions, 7393 }; 7394 bool LookupTemplateName( 7395 LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, 7396 bool EnteringContext, bool &MemberOfUnknownSpecialization, 7397 RequiredTemplateKind RequiredTemplate = SourceLocation(), 7398 AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true); 7399 7400 TemplateNameKind isTemplateName(Scope *S, 7401 CXXScopeSpec &SS, 7402 bool hasTemplateKeyword, 7403 const UnqualifiedId &Name, 7404 ParsedType ObjectType, 7405 bool EnteringContext, 7406 TemplateTy &Template, 7407 bool &MemberOfUnknownSpecialization, 7408 bool Disambiguation = false); 7409 7410 /// Try to resolve an undeclared template name as a type template. 7411 /// 7412 /// Sets II to the identifier corresponding to the template name, and updates 7413 /// Name to a corresponding (typo-corrected) type template name and TNK to 7414 /// the corresponding kind, if possible. 7415 void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, 7416 TemplateNameKind &TNK, 7417 SourceLocation NameLoc, 7418 IdentifierInfo *&II); 7419 7420 bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, 7421 SourceLocation NameLoc, 7422 bool Diagnose = true); 7423 7424 /// Determine whether a particular identifier might be the name in a C++1z 7425 /// deduction-guide declaration. 7426 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, 7427 SourceLocation NameLoc, 7428 ParsedTemplateTy *Template = nullptr); 7429 7430 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, 7431 SourceLocation IILoc, 7432 Scope *S, 7433 const CXXScopeSpec *SS, 7434 TemplateTy &SuggestedTemplate, 7435 TemplateNameKind &SuggestedKind); 7436 7437 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, 7438 NamedDecl *Instantiation, 7439 bool InstantiatedFromMember, 7440 const NamedDecl *Pattern, 7441 const NamedDecl *PatternDef, 7442 TemplateSpecializationKind TSK, 7443 bool Complain = true); 7444 7445 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); 7446 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); 7447 7448 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename, 7449 SourceLocation EllipsisLoc, 7450 SourceLocation KeyLoc, 7451 IdentifierInfo *ParamName, 7452 SourceLocation ParamNameLoc, 7453 unsigned Depth, unsigned Position, 7454 SourceLocation EqualLoc, 7455 ParsedType DefaultArg, bool HasTypeConstraint); 7456 7457 bool ActOnTypeConstraint(const CXXScopeSpec &SS, 7458 TemplateIdAnnotation *TypeConstraint, 7459 TemplateTypeParmDecl *ConstrainedParameter, 7460 SourceLocation EllipsisLoc); 7461 bool BuildTypeConstraint(const CXXScopeSpec &SS, 7462 TemplateIdAnnotation *TypeConstraint, 7463 TemplateTypeParmDecl *ConstrainedParameter, 7464 SourceLocation EllipsisLoc, 7465 bool AllowUnexpandedPack); 7466 7467 bool AttachTypeConstraint(NestedNameSpecifierLoc NS, 7468 DeclarationNameInfo NameInfo, 7469 ConceptDecl *NamedConcept, 7470 const TemplateArgumentListInfo *TemplateArgs, 7471 TemplateTypeParmDecl *ConstrainedParameter, 7472 SourceLocation EllipsisLoc); 7473 7474 bool AttachTypeConstraint(AutoTypeLoc TL, 7475 NonTypeTemplateParmDecl *ConstrainedParameter, 7476 SourceLocation EllipsisLoc); 7477 7478 bool RequireStructuralType(QualType T, SourceLocation Loc); 7479 7480 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, 7481 SourceLocation Loc); 7482 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); 7483 7484 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 7485 unsigned Depth, 7486 unsigned Position, 7487 SourceLocation EqualLoc, 7488 Expr *DefaultArg); 7489 NamedDecl *ActOnTemplateTemplateParameter(Scope *S, 7490 SourceLocation TmpLoc, 7491 TemplateParameterList *Params, 7492 SourceLocation EllipsisLoc, 7493 IdentifierInfo *ParamName, 7494 SourceLocation ParamNameLoc, 7495 unsigned Depth, 7496 unsigned Position, 7497 SourceLocation EqualLoc, 7498 ParsedTemplateArgument DefaultArg); 7499 7500 TemplateParameterList * 7501 ActOnTemplateParameterList(unsigned Depth, 7502 SourceLocation ExportLoc, 7503 SourceLocation TemplateLoc, 7504 SourceLocation LAngleLoc, 7505 ArrayRef<NamedDecl *> Params, 7506 SourceLocation RAngleLoc, 7507 Expr *RequiresClause); 7508 7509 /// The context in which we are checking a template parameter list. 7510 enum TemplateParamListContext { 7511 TPC_ClassTemplate, 7512 TPC_VarTemplate, 7513 TPC_FunctionTemplate, 7514 TPC_ClassTemplateMember, 7515 TPC_FriendClassTemplate, 7516 TPC_FriendFunctionTemplate, 7517 TPC_FriendFunctionTemplateDefinition, 7518 TPC_TypeAliasTemplate 7519 }; 7520 7521 bool CheckTemplateParameterList(TemplateParameterList *NewParams, 7522 TemplateParameterList *OldParams, 7523 TemplateParamListContext TPC, 7524 SkipBodyInfo *SkipBody = nullptr); 7525 TemplateParameterList *MatchTemplateParametersToScopeSpecifier( 7526 SourceLocation DeclStartLoc, SourceLocation DeclLoc, 7527 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, 7528 ArrayRef<TemplateParameterList *> ParamLists, 7529 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, 7530 bool SuppressDiagnostic = false); 7531 7532 DeclResult CheckClassTemplate( 7533 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, 7534 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, 7535 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, 7536 AccessSpecifier AS, SourceLocation ModulePrivateLoc, 7537 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, 7538 TemplateParameterList **OuterTemplateParamLists, 7539 SkipBodyInfo *SkipBody = nullptr); 7540 7541 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, 7542 QualType NTTPType, 7543 SourceLocation Loc); 7544 7545 /// Get a template argument mapping the given template parameter to itself, 7546 /// e.g. for X in \c template<int X>, this would return an expression template 7547 /// argument referencing X. 7548 TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param, 7549 SourceLocation Location); 7550 7551 void translateTemplateArguments(const ASTTemplateArgsPtr &In, 7552 TemplateArgumentListInfo &Out); 7553 7554 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType); 7555 7556 void NoteAllFoundTemplates(TemplateName Name); 7557 7558 QualType CheckTemplateIdType(TemplateName Template, 7559 SourceLocation TemplateLoc, 7560 TemplateArgumentListInfo &TemplateArgs); 7561 7562 TypeResult 7563 ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 7564 TemplateTy Template, IdentifierInfo *TemplateII, 7565 SourceLocation TemplateIILoc, SourceLocation LAngleLoc, 7566 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, 7567 bool IsCtorOrDtorName = false, bool IsClassName = false); 7568 7569 /// Parsed an elaborated-type-specifier that refers to a template-id, 7570 /// such as \c class T::template apply<U>. 7571 TypeResult ActOnTagTemplateIdType(TagUseKind TUK, 7572 TypeSpecifierType TagSpec, 7573 SourceLocation TagLoc, 7574 CXXScopeSpec &SS, 7575 SourceLocation TemplateKWLoc, 7576 TemplateTy TemplateD, 7577 SourceLocation TemplateLoc, 7578 SourceLocation LAngleLoc, 7579 ASTTemplateArgsPtr TemplateArgsIn, 7580 SourceLocation RAngleLoc); 7581 7582 DeclResult ActOnVarTemplateSpecialization( 7583 Scope *S, Declarator &D, TypeSourceInfo *DI, 7584 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, 7585 StorageClass SC, bool IsPartialSpecialization); 7586 7587 /// Get the specialization of the given variable template corresponding to 7588 /// the specified argument list, or a null-but-valid result if the arguments 7589 /// are dependent. 7590 DeclResult CheckVarTemplateId(VarTemplateDecl *Template, 7591 SourceLocation TemplateLoc, 7592 SourceLocation TemplateNameLoc, 7593 const TemplateArgumentListInfo &TemplateArgs); 7594 7595 /// Form a reference to the specialization of the given variable template 7596 /// corresponding to the specified argument list, or a null-but-valid result 7597 /// if the arguments are dependent. 7598 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, 7599 const DeclarationNameInfo &NameInfo, 7600 VarTemplateDecl *Template, 7601 SourceLocation TemplateLoc, 7602 const TemplateArgumentListInfo *TemplateArgs); 7603 7604 ExprResult 7605 CheckConceptTemplateId(const CXXScopeSpec &SS, 7606 SourceLocation TemplateKWLoc, 7607 const DeclarationNameInfo &ConceptNameInfo, 7608 NamedDecl *FoundDecl, ConceptDecl *NamedConcept, 7609 const TemplateArgumentListInfo *TemplateArgs); 7610 7611 void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc); 7612 7613 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, 7614 SourceLocation TemplateKWLoc, 7615 LookupResult &R, 7616 bool RequiresADL, 7617 const TemplateArgumentListInfo *TemplateArgs); 7618 7619 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, 7620 SourceLocation TemplateKWLoc, 7621 const DeclarationNameInfo &NameInfo, 7622 const TemplateArgumentListInfo *TemplateArgs); 7623 7624 TemplateNameKind ActOnTemplateName( 7625 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 7626 const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, 7627 TemplateTy &Template, bool AllowInjectedClassName = false); 7628 7629 DeclResult ActOnClassTemplateSpecialization( 7630 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, 7631 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, 7632 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, 7633 MultiTemplateParamsArg TemplateParameterLists, 7634 SkipBodyInfo *SkipBody = nullptr); 7635 7636 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, 7637 TemplateDecl *PrimaryTemplate, 7638 unsigned NumExplicitArgs, 7639 ArrayRef<TemplateArgument> Args); 7640 void CheckTemplatePartialSpecialization( 7641 ClassTemplatePartialSpecializationDecl *Partial); 7642 void CheckTemplatePartialSpecialization( 7643 VarTemplatePartialSpecializationDecl *Partial); 7644 7645 Decl *ActOnTemplateDeclarator(Scope *S, 7646 MultiTemplateParamsArg TemplateParameterLists, 7647 Declarator &D); 7648 7649 bool 7650 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, 7651 TemplateSpecializationKind NewTSK, 7652 NamedDecl *PrevDecl, 7653 TemplateSpecializationKind PrevTSK, 7654 SourceLocation PrevPtOfInstantiation, 7655 bool &SuppressNew); 7656 7657 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, 7658 const TemplateArgumentListInfo &ExplicitTemplateArgs, 7659 LookupResult &Previous); 7660 7661 bool CheckFunctionTemplateSpecialization( 7662 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, 7663 LookupResult &Previous, bool QualifiedFriend = false); 7664 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); 7665 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous); 7666 7667 DeclResult ActOnExplicitInstantiation( 7668 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, 7669 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, 7670 TemplateTy Template, SourceLocation TemplateNameLoc, 7671 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, 7672 SourceLocation RAngleLoc, const ParsedAttributesView &Attr); 7673 7674 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, 7675 SourceLocation TemplateLoc, 7676 unsigned TagSpec, SourceLocation KWLoc, 7677 CXXScopeSpec &SS, IdentifierInfo *Name, 7678 SourceLocation NameLoc, 7679 const ParsedAttributesView &Attr); 7680 7681 DeclResult ActOnExplicitInstantiation(Scope *S, 7682 SourceLocation ExternLoc, 7683 SourceLocation TemplateLoc, 7684 Declarator &D); 7685 7686 TemplateArgumentLoc 7687 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, 7688 SourceLocation TemplateLoc, 7689 SourceLocation RAngleLoc, 7690 Decl *Param, 7691 SmallVectorImpl<TemplateArgument> 7692 &Converted, 7693 bool &HasDefaultArg); 7694 7695 /// Specifies the context in which a particular template 7696 /// argument is being checked. 7697 enum CheckTemplateArgumentKind { 7698 /// The template argument was specified in the code or was 7699 /// instantiated with some deduced template arguments. 7700 CTAK_Specified, 7701 7702 /// The template argument was deduced via template argument 7703 /// deduction. 7704 CTAK_Deduced, 7705 7706 /// The template argument was deduced from an array bound 7707 /// via template argument deduction. 7708 CTAK_DeducedFromArrayBound 7709 }; 7710 7711 bool CheckTemplateArgument(NamedDecl *Param, 7712 TemplateArgumentLoc &Arg, 7713 NamedDecl *Template, 7714 SourceLocation TemplateLoc, 7715 SourceLocation RAngleLoc, 7716 unsigned ArgumentPackIndex, 7717 SmallVectorImpl<TemplateArgument> &Converted, 7718 CheckTemplateArgumentKind CTAK = CTAK_Specified); 7719 7720 /// Check that the given template arguments can be be provided to 7721 /// the given template, converting the arguments along the way. 7722 /// 7723 /// \param Template The template to which the template arguments are being 7724 /// provided. 7725 /// 7726 /// \param TemplateLoc The location of the template name in the source. 7727 /// 7728 /// \param TemplateArgs The list of template arguments. If the template is 7729 /// a template template parameter, this function may extend the set of 7730 /// template arguments to also include substituted, defaulted template 7731 /// arguments. 7732 /// 7733 /// \param PartialTemplateArgs True if the list of template arguments is 7734 /// intentionally partial, e.g., because we're checking just the initial 7735 /// set of template arguments. 7736 /// 7737 /// \param Converted Will receive the converted, canonicalized template 7738 /// arguments. 7739 /// 7740 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to 7741 /// contain the converted forms of the template arguments as written. 7742 /// Otherwise, \p TemplateArgs will not be modified. 7743 /// 7744 /// \param ConstraintsNotSatisfied If provided, and an error occured, will 7745 /// receive true if the cause for the error is the associated constraints of 7746 /// the template not being satisfied by the template arguments. 7747 /// 7748 /// \returns true if an error occurred, false otherwise. 7749 bool CheckTemplateArgumentList(TemplateDecl *Template, 7750 SourceLocation TemplateLoc, 7751 TemplateArgumentListInfo &TemplateArgs, 7752 bool PartialTemplateArgs, 7753 SmallVectorImpl<TemplateArgument> &Converted, 7754 bool UpdateArgsWithConversions = true, 7755 bool *ConstraintsNotSatisfied = nullptr); 7756 7757 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, 7758 TemplateArgumentLoc &Arg, 7759 SmallVectorImpl<TemplateArgument> &Converted); 7760 7761 bool CheckTemplateArgument(TemplateTypeParmDecl *Param, 7762 TypeSourceInfo *Arg); 7763 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 7764 QualType InstantiatedParamType, Expr *Arg, 7765 TemplateArgument &Converted, 7766 CheckTemplateArgumentKind CTAK = CTAK_Specified); 7767 bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, 7768 TemplateParameterList *Params, 7769 TemplateArgumentLoc &Arg); 7770 7771 ExprResult 7772 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, 7773 QualType ParamType, 7774 SourceLocation Loc); 7775 ExprResult 7776 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, 7777 SourceLocation Loc); 7778 7779 /// Enumeration describing how template parameter lists are compared 7780 /// for equality. 7781 enum TemplateParameterListEqualKind { 7782 /// We are matching the template parameter lists of two templates 7783 /// that might be redeclarations. 7784 /// 7785 /// \code 7786 /// template<typename T> struct X; 7787 /// template<typename T> struct X; 7788 /// \endcode 7789 TPL_TemplateMatch, 7790 7791 /// We are matching the template parameter lists of two template 7792 /// template parameters as part of matching the template parameter lists 7793 /// of two templates that might be redeclarations. 7794 /// 7795 /// \code 7796 /// template<template<int I> class TT> struct X; 7797 /// template<template<int Value> class Other> struct X; 7798 /// \endcode 7799 TPL_TemplateTemplateParmMatch, 7800 7801 /// We are matching the template parameter lists of a template 7802 /// template argument against the template parameter lists of a template 7803 /// template parameter. 7804 /// 7805 /// \code 7806 /// template<template<int Value> class Metafun> struct X; 7807 /// template<int Value> struct integer_c; 7808 /// X<integer_c> xic; 7809 /// \endcode 7810 TPL_TemplateTemplateArgumentMatch 7811 }; 7812 7813 bool TemplateParameterListsAreEqual(TemplateParameterList *New, 7814 TemplateParameterList *Old, 7815 bool Complain, 7816 TemplateParameterListEqualKind Kind, 7817 SourceLocation TemplateArgLoc 7818 = SourceLocation()); 7819 7820 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); 7821 7822 /// Called when the parser has parsed a C++ typename 7823 /// specifier, e.g., "typename T::type". 7824 /// 7825 /// \param S The scope in which this typename type occurs. 7826 /// \param TypenameLoc the location of the 'typename' keyword 7827 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 7828 /// \param II the identifier we're retrieving (e.g., 'type' in the example). 7829 /// \param IdLoc the location of the identifier. 7830 TypeResult 7831 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 7832 const CXXScopeSpec &SS, const IdentifierInfo &II, 7833 SourceLocation IdLoc); 7834 7835 /// Called when the parser has parsed a C++ typename 7836 /// specifier that ends in a template-id, e.g., 7837 /// "typename MetaFun::template apply<T1, T2>". 7838 /// 7839 /// \param S The scope in which this typename type occurs. 7840 /// \param TypenameLoc the location of the 'typename' keyword 7841 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 7842 /// \param TemplateLoc the location of the 'template' keyword, if any. 7843 /// \param TemplateName The template name. 7844 /// \param TemplateII The identifier used to name the template. 7845 /// \param TemplateIILoc The location of the template name. 7846 /// \param LAngleLoc The location of the opening angle bracket ('<'). 7847 /// \param TemplateArgs The template arguments. 7848 /// \param RAngleLoc The location of the closing angle bracket ('>'). 7849 TypeResult 7850 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 7851 const CXXScopeSpec &SS, 7852 SourceLocation TemplateLoc, 7853 TemplateTy TemplateName, 7854 IdentifierInfo *TemplateII, 7855 SourceLocation TemplateIILoc, 7856 SourceLocation LAngleLoc, 7857 ASTTemplateArgsPtr TemplateArgs, 7858 SourceLocation RAngleLoc); 7859 7860 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, 7861 SourceLocation KeywordLoc, 7862 NestedNameSpecifierLoc QualifierLoc, 7863 const IdentifierInfo &II, 7864 SourceLocation IILoc, 7865 TypeSourceInfo **TSI, 7866 bool DeducedTSTContext); 7867 7868 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, 7869 SourceLocation KeywordLoc, 7870 NestedNameSpecifierLoc QualifierLoc, 7871 const IdentifierInfo &II, 7872 SourceLocation IILoc, 7873 bool DeducedTSTContext = true); 7874 7875 7876 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, 7877 SourceLocation Loc, 7878 DeclarationName Name); 7879 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); 7880 7881 ExprResult RebuildExprInCurrentInstantiation(Expr *E); 7882 bool RebuildTemplateParamsInCurrentInstantiation( 7883 TemplateParameterList *Params); 7884 7885 std::string 7886 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 7887 const TemplateArgumentList &Args); 7888 7889 std::string 7890 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 7891 const TemplateArgument *Args, 7892 unsigned NumArgs); 7893 7894 //===--------------------------------------------------------------------===// 7895 // C++ Concepts 7896 //===--------------------------------------------------------------------===// 7897 Decl *ActOnConceptDefinition( 7898 Scope *S, MultiTemplateParamsArg TemplateParameterLists, 7899 IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr); 7900 7901 RequiresExprBodyDecl * 7902 ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, 7903 ArrayRef<ParmVarDecl *> LocalParameters, 7904 Scope *BodyScope); 7905 void ActOnFinishRequiresExpr(); 7906 concepts::Requirement *ActOnSimpleRequirement(Expr *E); 7907 concepts::Requirement *ActOnTypeRequirement( 7908 SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc, 7909 IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId); 7910 concepts::Requirement *ActOnCompoundRequirement(Expr *E, 7911 SourceLocation NoexceptLoc); 7912 concepts::Requirement * 7913 ActOnCompoundRequirement( 7914 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS, 7915 TemplateIdAnnotation *TypeConstraint, unsigned Depth); 7916 concepts::Requirement *ActOnNestedRequirement(Expr *Constraint); 7917 concepts::ExprRequirement * 7918 BuildExprRequirement( 7919 Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc, 7920 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); 7921 concepts::ExprRequirement * 7922 BuildExprRequirement( 7923 concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag, 7924 bool IsSatisfied, SourceLocation NoexceptLoc, 7925 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); 7926 concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type); 7927 concepts::TypeRequirement * 7928 BuildTypeRequirement( 7929 concepts::Requirement::SubstitutionDiagnostic *SubstDiag); 7930 concepts::NestedRequirement *BuildNestedRequirement(Expr *E); 7931 concepts::NestedRequirement * 7932 BuildNestedRequirement( 7933 concepts::Requirement::SubstitutionDiagnostic *SubstDiag); 7934 ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc, 7935 RequiresExprBodyDecl *Body, 7936 ArrayRef<ParmVarDecl *> LocalParameters, 7937 ArrayRef<concepts::Requirement *> Requirements, 7938 SourceLocation ClosingBraceLoc); 7939 7940 //===--------------------------------------------------------------------===// 7941 // C++ Variadic Templates (C++0x [temp.variadic]) 7942 //===--------------------------------------------------------------------===// 7943 7944 /// Determine whether an unexpanded parameter pack might be permitted in this 7945 /// location. Useful for error recovery. 7946 bool isUnexpandedParameterPackPermitted(); 7947 7948 /// The context in which an unexpanded parameter pack is 7949 /// being diagnosed. 7950 /// 7951 /// Note that the values of this enumeration line up with the first 7952 /// argument to the \c err_unexpanded_parameter_pack diagnostic. 7953 enum UnexpandedParameterPackContext { 7954 /// An arbitrary expression. 7955 UPPC_Expression = 0, 7956 7957 /// The base type of a class type. 7958 UPPC_BaseType, 7959 7960 /// The type of an arbitrary declaration. 7961 UPPC_DeclarationType, 7962 7963 /// The type of a data member. 7964 UPPC_DataMemberType, 7965 7966 /// The size of a bit-field. 7967 UPPC_BitFieldWidth, 7968 7969 /// The expression in a static assertion. 7970 UPPC_StaticAssertExpression, 7971 7972 /// The fixed underlying type of an enumeration. 7973 UPPC_FixedUnderlyingType, 7974 7975 /// The enumerator value. 7976 UPPC_EnumeratorValue, 7977 7978 /// A using declaration. 7979 UPPC_UsingDeclaration, 7980 7981 /// A friend declaration. 7982 UPPC_FriendDeclaration, 7983 7984 /// A declaration qualifier. 7985 UPPC_DeclarationQualifier, 7986 7987 /// An initializer. 7988 UPPC_Initializer, 7989 7990 /// A default argument. 7991 UPPC_DefaultArgument, 7992 7993 /// The type of a non-type template parameter. 7994 UPPC_NonTypeTemplateParameterType, 7995 7996 /// The type of an exception. 7997 UPPC_ExceptionType, 7998 7999 /// Partial specialization. 8000 UPPC_PartialSpecialization, 8001 8002 /// Microsoft __if_exists. 8003 UPPC_IfExists, 8004 8005 /// Microsoft __if_not_exists. 8006 UPPC_IfNotExists, 8007 8008 /// Lambda expression. 8009 UPPC_Lambda, 8010 8011 /// Block expression. 8012 UPPC_Block, 8013 8014 /// A type constraint. 8015 UPPC_TypeConstraint, 8016 8017 // A requirement in a requires-expression. 8018 UPPC_Requirement, 8019 8020 // A requires-clause. 8021 UPPC_RequiresClause, 8022 }; 8023 8024 /// Diagnose unexpanded parameter packs. 8025 /// 8026 /// \param Loc The location at which we should emit the diagnostic. 8027 /// 8028 /// \param UPPC The context in which we are diagnosing unexpanded 8029 /// parameter packs. 8030 /// 8031 /// \param Unexpanded the set of unexpanded parameter packs. 8032 /// 8033 /// \returns true if an error occurred, false otherwise. 8034 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, 8035 UnexpandedParameterPackContext UPPC, 8036 ArrayRef<UnexpandedParameterPack> Unexpanded); 8037 8038 /// If the given type contains an unexpanded parameter pack, 8039 /// diagnose the error. 8040 /// 8041 /// \param Loc The source location where a diagnostc should be emitted. 8042 /// 8043 /// \param T The type that is being checked for unexpanded parameter 8044 /// packs. 8045 /// 8046 /// \returns true if an error occurred, false otherwise. 8047 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, 8048 UnexpandedParameterPackContext UPPC); 8049 8050 /// If the given expression contains an unexpanded parameter 8051 /// pack, diagnose the error. 8052 /// 8053 /// \param E The expression that is being checked for unexpanded 8054 /// parameter packs. 8055 /// 8056 /// \returns true if an error occurred, false otherwise. 8057 bool DiagnoseUnexpandedParameterPack(Expr *E, 8058 UnexpandedParameterPackContext UPPC = UPPC_Expression); 8059 8060 /// If the given requirees-expression contains an unexpanded reference to one 8061 /// of its own parameter packs, diagnose the error. 8062 /// 8063 /// \param RE The requiress-expression that is being checked for unexpanded 8064 /// parameter packs. 8065 /// 8066 /// \returns true if an error occurred, false otherwise. 8067 bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE); 8068 8069 /// If the given nested-name-specifier contains an unexpanded 8070 /// parameter pack, diagnose the error. 8071 /// 8072 /// \param SS The nested-name-specifier that is being checked for 8073 /// unexpanded parameter packs. 8074 /// 8075 /// \returns true if an error occurred, false otherwise. 8076 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, 8077 UnexpandedParameterPackContext UPPC); 8078 8079 /// If the given name contains an unexpanded parameter pack, 8080 /// diagnose the error. 8081 /// 8082 /// \param NameInfo The name (with source location information) that 8083 /// is being checked for unexpanded parameter packs. 8084 /// 8085 /// \returns true if an error occurred, false otherwise. 8086 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, 8087 UnexpandedParameterPackContext UPPC); 8088 8089 /// If the given template name contains an unexpanded parameter pack, 8090 /// diagnose the error. 8091 /// 8092 /// \param Loc The location of the template name. 8093 /// 8094 /// \param Template The template name that is being checked for unexpanded 8095 /// parameter packs. 8096 /// 8097 /// \returns true if an error occurred, false otherwise. 8098 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, 8099 TemplateName Template, 8100 UnexpandedParameterPackContext UPPC); 8101 8102 /// If the given template argument contains an unexpanded parameter 8103 /// pack, diagnose the error. 8104 /// 8105 /// \param Arg The template argument that is being checked for unexpanded 8106 /// parameter packs. 8107 /// 8108 /// \returns true if an error occurred, false otherwise. 8109 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, 8110 UnexpandedParameterPackContext UPPC); 8111 8112 /// Collect the set of unexpanded parameter packs within the given 8113 /// template argument. 8114 /// 8115 /// \param Arg The template argument that will be traversed to find 8116 /// unexpanded parameter packs. 8117 void collectUnexpandedParameterPacks(TemplateArgument Arg, 8118 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 8119 8120 /// Collect the set of unexpanded parameter packs within the given 8121 /// template argument. 8122 /// 8123 /// \param Arg The template argument that will be traversed to find 8124 /// unexpanded parameter packs. 8125 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, 8126 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 8127 8128 /// Collect the set of unexpanded parameter packs within the given 8129 /// type. 8130 /// 8131 /// \param T The type that will be traversed to find 8132 /// unexpanded parameter packs. 8133 void collectUnexpandedParameterPacks(QualType T, 8134 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 8135 8136 /// Collect the set of unexpanded parameter packs within the given 8137 /// type. 8138 /// 8139 /// \param TL The type that will be traversed to find 8140 /// unexpanded parameter packs. 8141 void collectUnexpandedParameterPacks(TypeLoc TL, 8142 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 8143 8144 /// Collect the set of unexpanded parameter packs within the given 8145 /// nested-name-specifier. 8146 /// 8147 /// \param NNS The nested-name-specifier that will be traversed to find 8148 /// unexpanded parameter packs. 8149 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS, 8150 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 8151 8152 /// Collect the set of unexpanded parameter packs within the given 8153 /// name. 8154 /// 8155 /// \param NameInfo The name that will be traversed to find 8156 /// unexpanded parameter packs. 8157 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, 8158 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 8159 8160 /// Invoked when parsing a template argument followed by an 8161 /// ellipsis, which creates a pack expansion. 8162 /// 8163 /// \param Arg The template argument preceding the ellipsis, which 8164 /// may already be invalid. 8165 /// 8166 /// \param EllipsisLoc The location of the ellipsis. 8167 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, 8168 SourceLocation EllipsisLoc); 8169 8170 /// Invoked when parsing a type followed by an ellipsis, which 8171 /// creates a pack expansion. 8172 /// 8173 /// \param Type The type preceding the ellipsis, which will become 8174 /// the pattern of the pack expansion. 8175 /// 8176 /// \param EllipsisLoc The location of the ellipsis. 8177 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); 8178 8179 /// Construct a pack expansion type from the pattern of the pack 8180 /// expansion. 8181 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, 8182 SourceLocation EllipsisLoc, 8183 Optional<unsigned> NumExpansions); 8184 8185 /// Construct a pack expansion type from the pattern of the pack 8186 /// expansion. 8187 QualType CheckPackExpansion(QualType Pattern, 8188 SourceRange PatternRange, 8189 SourceLocation EllipsisLoc, 8190 Optional<unsigned> NumExpansions); 8191 8192 /// Invoked when parsing an expression followed by an ellipsis, which 8193 /// creates a pack expansion. 8194 /// 8195 /// \param Pattern The expression preceding the ellipsis, which will become 8196 /// the pattern of the pack expansion. 8197 /// 8198 /// \param EllipsisLoc The location of the ellipsis. 8199 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); 8200 8201 /// Invoked when parsing an expression followed by an ellipsis, which 8202 /// creates a pack expansion. 8203 /// 8204 /// \param Pattern The expression preceding the ellipsis, which will become 8205 /// the pattern of the pack expansion. 8206 /// 8207 /// \param EllipsisLoc The location of the ellipsis. 8208 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, 8209 Optional<unsigned> NumExpansions); 8210 8211 /// Determine whether we could expand a pack expansion with the 8212 /// given set of parameter packs into separate arguments by repeatedly 8213 /// transforming the pattern. 8214 /// 8215 /// \param EllipsisLoc The location of the ellipsis that identifies the 8216 /// pack expansion. 8217 /// 8218 /// \param PatternRange The source range that covers the entire pattern of 8219 /// the pack expansion. 8220 /// 8221 /// \param Unexpanded The set of unexpanded parameter packs within the 8222 /// pattern. 8223 /// 8224 /// \param ShouldExpand Will be set to \c true if the transformer should 8225 /// expand the corresponding pack expansions into separate arguments. When 8226 /// set, \c NumExpansions must also be set. 8227 /// 8228 /// \param RetainExpansion Whether the caller should add an unexpanded 8229 /// pack expansion after all of the expanded arguments. This is used 8230 /// when extending explicitly-specified template argument packs per 8231 /// C++0x [temp.arg.explicit]p9. 8232 /// 8233 /// \param NumExpansions The number of separate arguments that will be in 8234 /// the expanded form of the corresponding pack expansion. This is both an 8235 /// input and an output parameter, which can be set by the caller if the 8236 /// number of expansions is known a priori (e.g., due to a prior substitution) 8237 /// and will be set by the callee when the number of expansions is known. 8238 /// The callee must set this value when \c ShouldExpand is \c true; it may 8239 /// set this value in other cases. 8240 /// 8241 /// \returns true if an error occurred (e.g., because the parameter packs 8242 /// are to be instantiated with arguments of different lengths), false 8243 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) 8244 /// must be set. 8245 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, 8246 SourceRange PatternRange, 8247 ArrayRef<UnexpandedParameterPack> Unexpanded, 8248 const MultiLevelTemplateArgumentList &TemplateArgs, 8249 bool &ShouldExpand, 8250 bool &RetainExpansion, 8251 Optional<unsigned> &NumExpansions); 8252 8253 /// Determine the number of arguments in the given pack expansion 8254 /// type. 8255 /// 8256 /// This routine assumes that the number of arguments in the expansion is 8257 /// consistent across all of the unexpanded parameter packs in its pattern. 8258 /// 8259 /// Returns an empty Optional if the type can't be expanded. 8260 Optional<unsigned> getNumArgumentsInExpansion(QualType T, 8261 const MultiLevelTemplateArgumentList &TemplateArgs); 8262 8263 /// Determine whether the given declarator contains any unexpanded 8264 /// parameter packs. 8265 /// 8266 /// This routine is used by the parser to disambiguate function declarators 8267 /// with an ellipsis prior to the ')', e.g., 8268 /// 8269 /// \code 8270 /// void f(T...); 8271 /// \endcode 8272 /// 8273 /// To determine whether we have an (unnamed) function parameter pack or 8274 /// a variadic function. 8275 /// 8276 /// \returns true if the declarator contains any unexpanded parameter packs, 8277 /// false otherwise. 8278 bool containsUnexpandedParameterPacks(Declarator &D); 8279 8280 /// Returns the pattern of the pack expansion for a template argument. 8281 /// 8282 /// \param OrigLoc The template argument to expand. 8283 /// 8284 /// \param Ellipsis Will be set to the location of the ellipsis. 8285 /// 8286 /// \param NumExpansions Will be set to the number of expansions that will 8287 /// be generated from this pack expansion, if known a priori. 8288 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( 8289 TemplateArgumentLoc OrigLoc, 8290 SourceLocation &Ellipsis, 8291 Optional<unsigned> &NumExpansions) const; 8292 8293 /// Given a template argument that contains an unexpanded parameter pack, but 8294 /// which has already been substituted, attempt to determine the number of 8295 /// elements that will be produced once this argument is fully-expanded. 8296 /// 8297 /// This is intended for use when transforming 'sizeof...(Arg)' in order to 8298 /// avoid actually expanding the pack where possible. 8299 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg); 8300 8301 //===--------------------------------------------------------------------===// 8302 // C++ Template Argument Deduction (C++ [temp.deduct]) 8303 //===--------------------------------------------------------------------===// 8304 8305 /// Adjust the type \p ArgFunctionType to match the calling convention, 8306 /// noreturn, and optionally the exception specification of \p FunctionType. 8307 /// Deduction often wants to ignore these properties when matching function 8308 /// types. 8309 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, 8310 bool AdjustExceptionSpec = false); 8311 8312 /// Describes the result of template argument deduction. 8313 /// 8314 /// The TemplateDeductionResult enumeration describes the result of 8315 /// template argument deduction, as returned from 8316 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo 8317 /// structure provides additional information about the results of 8318 /// template argument deduction, e.g., the deduced template argument 8319 /// list (if successful) or the specific template parameters or 8320 /// deduced arguments that were involved in the failure. 8321 enum TemplateDeductionResult { 8322 /// Template argument deduction was successful. 8323 TDK_Success = 0, 8324 /// The declaration was invalid; do nothing. 8325 TDK_Invalid, 8326 /// Template argument deduction exceeded the maximum template 8327 /// instantiation depth (which has already been diagnosed). 8328 TDK_InstantiationDepth, 8329 /// Template argument deduction did not deduce a value 8330 /// for every template parameter. 8331 TDK_Incomplete, 8332 /// Template argument deduction did not deduce a value for every 8333 /// expansion of an expanded template parameter pack. 8334 TDK_IncompletePack, 8335 /// Template argument deduction produced inconsistent 8336 /// deduced values for the given template parameter. 8337 TDK_Inconsistent, 8338 /// Template argument deduction failed due to inconsistent 8339 /// cv-qualifiers on a template parameter type that would 8340 /// otherwise be deduced, e.g., we tried to deduce T in "const T" 8341 /// but were given a non-const "X". 8342 TDK_Underqualified, 8343 /// Substitution of the deduced template argument values 8344 /// resulted in an error. 8345 TDK_SubstitutionFailure, 8346 /// After substituting deduced template arguments, a dependent 8347 /// parameter type did not match the corresponding argument. 8348 TDK_DeducedMismatch, 8349 /// After substituting deduced template arguments, an element of 8350 /// a dependent parameter type did not match the corresponding element 8351 /// of the corresponding argument (when deducing from an initializer list). 8352 TDK_DeducedMismatchNested, 8353 /// A non-depnedent component of the parameter did not match the 8354 /// corresponding component of the argument. 8355 TDK_NonDeducedMismatch, 8356 /// When performing template argument deduction for a function 8357 /// template, there were too many call arguments. 8358 TDK_TooManyArguments, 8359 /// When performing template argument deduction for a function 8360 /// template, there were too few call arguments. 8361 TDK_TooFewArguments, 8362 /// The explicitly-specified template arguments were not valid 8363 /// template arguments for the given template. 8364 TDK_InvalidExplicitArguments, 8365 /// Checking non-dependent argument conversions failed. 8366 TDK_NonDependentConversionFailure, 8367 /// The deduced arguments did not satisfy the constraints associated 8368 /// with the template. 8369 TDK_ConstraintsNotSatisfied, 8370 /// Deduction failed; that's all we know. 8371 TDK_MiscellaneousDeductionFailure, 8372 /// CUDA Target attributes do not match. 8373 TDK_CUDATargetMismatch 8374 }; 8375 8376 TemplateDeductionResult 8377 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, 8378 const TemplateArgumentList &TemplateArgs, 8379 sema::TemplateDeductionInfo &Info); 8380 8381 TemplateDeductionResult 8382 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, 8383 const TemplateArgumentList &TemplateArgs, 8384 sema::TemplateDeductionInfo &Info); 8385 8386 TemplateDeductionResult SubstituteExplicitTemplateArguments( 8387 FunctionTemplateDecl *FunctionTemplate, 8388 TemplateArgumentListInfo &ExplicitTemplateArgs, 8389 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 8390 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, 8391 sema::TemplateDeductionInfo &Info); 8392 8393 /// brief A function argument from which we performed template argument 8394 // deduction for a call. 8395 struct OriginalCallArg { OriginalCallArgOriginalCallArg8396 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, 8397 unsigned ArgIdx, QualType OriginalArgType) 8398 : OriginalParamType(OriginalParamType), 8399 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx), 8400 OriginalArgType(OriginalArgType) {} 8401 8402 QualType OriginalParamType; 8403 bool DecomposedParam; 8404 unsigned ArgIdx; 8405 QualType OriginalArgType; 8406 }; 8407 8408 TemplateDeductionResult FinishTemplateArgumentDeduction( 8409 FunctionTemplateDecl *FunctionTemplate, 8410 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 8411 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, 8412 sema::TemplateDeductionInfo &Info, 8413 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr, 8414 bool PartialOverloading = false, 8415 llvm::function_ref<bool()> CheckNonDependent = []{ return false; }); 8416 8417 TemplateDeductionResult DeduceTemplateArguments( 8418 FunctionTemplateDecl *FunctionTemplate, 8419 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 8420 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, 8421 bool PartialOverloading, 8422 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent); 8423 8424 TemplateDeductionResult 8425 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 8426 TemplateArgumentListInfo *ExplicitTemplateArgs, 8427 QualType ArgFunctionType, 8428 FunctionDecl *&Specialization, 8429 sema::TemplateDeductionInfo &Info, 8430 bool IsAddressOfFunction = false); 8431 8432 TemplateDeductionResult 8433 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 8434 QualType ToType, 8435 CXXConversionDecl *&Specialization, 8436 sema::TemplateDeductionInfo &Info); 8437 8438 TemplateDeductionResult 8439 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 8440 TemplateArgumentListInfo *ExplicitTemplateArgs, 8441 FunctionDecl *&Specialization, 8442 sema::TemplateDeductionInfo &Info, 8443 bool IsAddressOfFunction = false); 8444 8445 /// Substitute Replacement for \p auto in \p TypeWithAuto 8446 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); 8447 /// Substitute Replacement for auto in TypeWithAuto 8448 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, 8449 QualType Replacement); 8450 /// Completely replace the \c auto in \p TypeWithAuto by 8451 /// \p Replacement. This does not retain any \c auto type sugar. 8452 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement); 8453 TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, 8454 QualType Replacement); 8455 8456 /// Result type of DeduceAutoType. 8457 enum DeduceAutoResult { 8458 DAR_Succeeded, 8459 DAR_Failed, 8460 DAR_FailedAlreadyDiagnosed 8461 }; 8462 8463 DeduceAutoResult 8464 DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result, 8465 Optional<unsigned> DependentDeductionDepth = None, 8466 bool IgnoreConstraints = false); 8467 DeduceAutoResult 8468 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result, 8469 Optional<unsigned> DependentDeductionDepth = None, 8470 bool IgnoreConstraints = false); 8471 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); 8472 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, 8473 bool Diagnose = true); 8474 8475 /// Declare implicit deduction guides for a class template if we've 8476 /// not already done so. 8477 void DeclareImplicitDeductionGuides(TemplateDecl *Template, 8478 SourceLocation Loc); 8479 8480 QualType DeduceTemplateSpecializationFromInitializer( 8481 TypeSourceInfo *TInfo, const InitializedEntity &Entity, 8482 const InitializationKind &Kind, MultiExprArg Init); 8483 8484 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, 8485 QualType Type, TypeSourceInfo *TSI, 8486 SourceRange Range, bool DirectInit, 8487 Expr *Init); 8488 8489 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const; 8490 8491 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, 8492 SourceLocation ReturnLoc, 8493 Expr *&RetExpr, AutoType *AT); 8494 8495 FunctionTemplateDecl *getMoreSpecializedTemplate( 8496 FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, 8497 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, 8498 unsigned NumCallArguments2, bool Reversed = false); 8499 UnresolvedSetIterator 8500 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, 8501 TemplateSpecCandidateSet &FailedCandidates, 8502 SourceLocation Loc, 8503 const PartialDiagnostic &NoneDiag, 8504 const PartialDiagnostic &AmbigDiag, 8505 const PartialDiagnostic &CandidateDiag, 8506 bool Complain = true, QualType TargetType = QualType()); 8507 8508 ClassTemplatePartialSpecializationDecl * 8509 getMoreSpecializedPartialSpecialization( 8510 ClassTemplatePartialSpecializationDecl *PS1, 8511 ClassTemplatePartialSpecializationDecl *PS2, 8512 SourceLocation Loc); 8513 8514 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, 8515 sema::TemplateDeductionInfo &Info); 8516 8517 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( 8518 VarTemplatePartialSpecializationDecl *PS1, 8519 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); 8520 8521 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T, 8522 sema::TemplateDeductionInfo &Info); 8523 8524 bool isTemplateTemplateParameterAtLeastAsSpecializedAs( 8525 TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc); 8526 8527 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, 8528 unsigned Depth, llvm::SmallBitVector &Used); 8529 8530 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, 8531 bool OnlyDeduced, 8532 unsigned Depth, 8533 llvm::SmallBitVector &Used); MarkDeducedTemplateParameters(const FunctionTemplateDecl * FunctionTemplate,llvm::SmallBitVector & Deduced)8534 void MarkDeducedTemplateParameters( 8535 const FunctionTemplateDecl *FunctionTemplate, 8536 llvm::SmallBitVector &Deduced) { 8537 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); 8538 } 8539 static void MarkDeducedTemplateParameters(ASTContext &Ctx, 8540 const FunctionTemplateDecl *FunctionTemplate, 8541 llvm::SmallBitVector &Deduced); 8542 8543 //===--------------------------------------------------------------------===// 8544 // C++ Template Instantiation 8545 // 8546 8547 MultiLevelTemplateArgumentList 8548 getTemplateInstantiationArgs(NamedDecl *D, 8549 const TemplateArgumentList *Innermost = nullptr, 8550 bool RelativeToPrimary = false, 8551 const FunctionDecl *Pattern = nullptr); 8552 8553 /// A context in which code is being synthesized (where a source location 8554 /// alone is not sufficient to identify the context). This covers template 8555 /// instantiation and various forms of implicitly-generated functions. 8556 struct CodeSynthesisContext { 8557 /// The kind of template instantiation we are performing 8558 enum SynthesisKind { 8559 /// We are instantiating a template declaration. The entity is 8560 /// the declaration we're instantiating (e.g., a CXXRecordDecl). 8561 TemplateInstantiation, 8562 8563 /// We are instantiating a default argument for a template 8564 /// parameter. The Entity is the template parameter whose argument is 8565 /// being instantiated, the Template is the template, and the 8566 /// TemplateArgs/NumTemplateArguments provide the template arguments as 8567 /// specified. 8568 DefaultTemplateArgumentInstantiation, 8569 8570 /// We are instantiating a default argument for a function. 8571 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs 8572 /// provides the template arguments as specified. 8573 DefaultFunctionArgumentInstantiation, 8574 8575 /// We are substituting explicit template arguments provided for 8576 /// a function template. The entity is a FunctionTemplateDecl. 8577 ExplicitTemplateArgumentSubstitution, 8578 8579 /// We are substituting template argument determined as part of 8580 /// template argument deduction for either a class template 8581 /// partial specialization or a function template. The 8582 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or 8583 /// a TemplateDecl. 8584 DeducedTemplateArgumentSubstitution, 8585 8586 /// We are substituting prior template arguments into a new 8587 /// template parameter. The template parameter itself is either a 8588 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. 8589 PriorTemplateArgumentSubstitution, 8590 8591 /// We are checking the validity of a default template argument that 8592 /// has been used when naming a template-id. 8593 DefaultTemplateArgumentChecking, 8594 8595 /// We are computing the exception specification for a defaulted special 8596 /// member function. 8597 ExceptionSpecEvaluation, 8598 8599 /// We are instantiating the exception specification for a function 8600 /// template which was deferred until it was needed. 8601 ExceptionSpecInstantiation, 8602 8603 /// We are instantiating a requirement of a requires expression. 8604 RequirementInstantiation, 8605 8606 /// We are checking the satisfaction of a nested requirement of a requires 8607 /// expression. 8608 NestedRequirementConstraintsCheck, 8609 8610 /// We are declaring an implicit special member function. 8611 DeclaringSpecialMember, 8612 8613 /// We are declaring an implicit 'operator==' for a defaulted 8614 /// 'operator<=>'. 8615 DeclaringImplicitEqualityComparison, 8616 8617 /// We are defining a synthesized function (such as a defaulted special 8618 /// member). 8619 DefiningSynthesizedFunction, 8620 8621 // We are checking the constraints associated with a constrained entity or 8622 // the constraint expression of a concept. This includes the checks that 8623 // atomic constraints have the type 'bool' and that they can be constant 8624 // evaluated. 8625 ConstraintsCheck, 8626 8627 // We are substituting template arguments into a constraint expression. 8628 ConstraintSubstitution, 8629 8630 // We are normalizing a constraint expression. 8631 ConstraintNormalization, 8632 8633 // We are substituting into the parameter mapping of an atomic constraint 8634 // during normalization. 8635 ParameterMappingSubstitution, 8636 8637 /// We are rewriting a comparison operator in terms of an operator<=>. 8638 RewritingOperatorAsSpaceship, 8639 8640 /// We are initializing a structured binding. 8641 InitializingStructuredBinding, 8642 8643 /// We are marking a class as __dllexport. 8644 MarkingClassDllexported, 8645 8646 /// Added for Template instantiation observation. 8647 /// Memoization means we are _not_ instantiating a template because 8648 /// it is already instantiated (but we entered a context where we 8649 /// would have had to if it was not already instantiated). 8650 Memoization 8651 } Kind; 8652 8653 /// Was the enclosing context a non-instantiation SFINAE context? 8654 bool SavedInNonInstantiationSFINAEContext; 8655 8656 /// The point of instantiation or synthesis within the source code. 8657 SourceLocation PointOfInstantiation; 8658 8659 /// The entity that is being synthesized. 8660 Decl *Entity; 8661 8662 /// The template (or partial specialization) in which we are 8663 /// performing the instantiation, for substitutions of prior template 8664 /// arguments. 8665 NamedDecl *Template; 8666 8667 /// The list of template arguments we are substituting, if they 8668 /// are not part of the entity. 8669 const TemplateArgument *TemplateArgs; 8670 8671 // FIXME: Wrap this union around more members, or perhaps store the 8672 // kind-specific members in the RAII object owning the context. 8673 union { 8674 /// The number of template arguments in TemplateArgs. 8675 unsigned NumTemplateArgs; 8676 8677 /// The special member being declared or defined. 8678 CXXSpecialMember SpecialMember; 8679 }; 8680 template_argumentsCodeSynthesisContext8681 ArrayRef<TemplateArgument> template_arguments() const { 8682 assert(Kind != DeclaringSpecialMember); 8683 return {TemplateArgs, NumTemplateArgs}; 8684 } 8685 8686 /// The template deduction info object associated with the 8687 /// substitution or checking of explicit or deduced template arguments. 8688 sema::TemplateDeductionInfo *DeductionInfo; 8689 8690 /// The source range that covers the construct that cause 8691 /// the instantiation, e.g., the template-id that causes a class 8692 /// template instantiation. 8693 SourceRange InstantiationRange; 8694 CodeSynthesisContextCodeSynthesisContext8695 CodeSynthesisContext() 8696 : Kind(TemplateInstantiation), 8697 SavedInNonInstantiationSFINAEContext(false), Entity(nullptr), 8698 Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0), 8699 DeductionInfo(nullptr) {} 8700 8701 /// Determines whether this template is an actual instantiation 8702 /// that should be counted toward the maximum instantiation depth. 8703 bool isInstantiationRecord() const; 8704 }; 8705 8706 /// List of active code synthesis contexts. 8707 /// 8708 /// This vector is treated as a stack. As synthesis of one entity requires 8709 /// synthesis of another, additional contexts are pushed onto the stack. 8710 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts; 8711 8712 /// Specializations whose definitions are currently being instantiated. 8713 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations; 8714 8715 /// Non-dependent types used in templates that have already been instantiated 8716 /// by some template instantiation. 8717 llvm::DenseSet<QualType> InstantiatedNonDependentTypes; 8718 8719 /// Extra modules inspected when performing a lookup during a template 8720 /// instantiation. Computed lazily. 8721 SmallVector<Module*, 16> CodeSynthesisContextLookupModules; 8722 8723 /// Cache of additional modules that should be used for name lookup 8724 /// within the current template instantiation. Computed lazily; use 8725 /// getLookupModules() to get a complete set. 8726 llvm::DenseSet<Module*> LookupModulesCache; 8727 8728 /// Get the set of additional modules that should be checked during 8729 /// name lookup. A module and its imports become visible when instanting a 8730 /// template defined within it. 8731 llvm::DenseSet<Module*> &getLookupModules(); 8732 8733 /// Map from the most recent declaration of a namespace to the most 8734 /// recent visible declaration of that namespace. 8735 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache; 8736 8737 /// Whether we are in a SFINAE context that is not associated with 8738 /// template instantiation. 8739 /// 8740 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside 8741 /// of a template instantiation or template argument deduction. 8742 bool InNonInstantiationSFINAEContext; 8743 8744 /// The number of \p CodeSynthesisContexts that are not template 8745 /// instantiations and, therefore, should not be counted as part of the 8746 /// instantiation depth. 8747 /// 8748 /// When the instantiation depth reaches the user-configurable limit 8749 /// \p LangOptions::InstantiationDepth we will abort instantiation. 8750 // FIXME: Should we have a similar limit for other forms of synthesis? 8751 unsigned NonInstantiationEntries; 8752 8753 /// The depth of the context stack at the point when the most recent 8754 /// error or warning was produced. 8755 /// 8756 /// This value is used to suppress printing of redundant context stacks 8757 /// when there are multiple errors or warnings in the same instantiation. 8758 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else. 8759 unsigned LastEmittedCodeSynthesisContextDepth = 0; 8760 8761 /// The template instantiation callbacks to trace or track 8762 /// instantiations (objects can be chained). 8763 /// 8764 /// This callbacks is used to print, trace or track template 8765 /// instantiations as they are being constructed. 8766 std::vector<std::unique_ptr<TemplateInstantiationCallback>> 8767 TemplateInstCallbacks; 8768 8769 /// The current index into pack expansion arguments that will be 8770 /// used for substitution of parameter packs. 8771 /// 8772 /// The pack expansion index will be -1 to indicate that parameter packs 8773 /// should be instantiated as themselves. Otherwise, the index specifies 8774 /// which argument within the parameter pack will be used for substitution. 8775 int ArgumentPackSubstitutionIndex; 8776 8777 /// RAII object used to change the argument pack substitution index 8778 /// within a \c Sema object. 8779 /// 8780 /// See \c ArgumentPackSubstitutionIndex for more information. 8781 class ArgumentPackSubstitutionIndexRAII { 8782 Sema &Self; 8783 int OldSubstitutionIndex; 8784 8785 public: ArgumentPackSubstitutionIndexRAII(Sema & Self,int NewSubstitutionIndex)8786 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) 8787 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { 8788 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; 8789 } 8790 ~ArgumentPackSubstitutionIndexRAII()8791 ~ArgumentPackSubstitutionIndexRAII() { 8792 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; 8793 } 8794 }; 8795 8796 friend class ArgumentPackSubstitutionRAII; 8797 8798 /// For each declaration that involved template argument deduction, the 8799 /// set of diagnostics that were suppressed during that template argument 8800 /// deduction. 8801 /// 8802 /// FIXME: Serialize this structure to the AST file. 8803 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > 8804 SuppressedDiagnosticsMap; 8805 SuppressedDiagnosticsMap SuppressedDiagnostics; 8806 8807 /// A stack object to be created when performing template 8808 /// instantiation. 8809 /// 8810 /// Construction of an object of type \c InstantiatingTemplate 8811 /// pushes the current instantiation onto the stack of active 8812 /// instantiations. If the size of this stack exceeds the maximum 8813 /// number of recursive template instantiations, construction 8814 /// produces an error and evaluates true. 8815 /// 8816 /// Destruction of this object will pop the named instantiation off 8817 /// the stack. 8818 struct InstantiatingTemplate { 8819 /// Note that we are instantiating a class template, 8820 /// function template, variable template, alias template, 8821 /// or a member thereof. 8822 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8823 Decl *Entity, 8824 SourceRange InstantiationRange = SourceRange()); 8825 8826 struct ExceptionSpecification {}; 8827 /// Note that we are instantiating an exception specification 8828 /// of a function template. 8829 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8830 FunctionDecl *Entity, ExceptionSpecification, 8831 SourceRange InstantiationRange = SourceRange()); 8832 8833 /// Note that we are instantiating a default argument in a 8834 /// template-id. 8835 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8836 TemplateParameter Param, TemplateDecl *Template, 8837 ArrayRef<TemplateArgument> TemplateArgs, 8838 SourceRange InstantiationRange = SourceRange()); 8839 8840 /// Note that we are substituting either explicitly-specified or 8841 /// deduced template arguments during function template argument deduction. 8842 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8843 FunctionTemplateDecl *FunctionTemplate, 8844 ArrayRef<TemplateArgument> TemplateArgs, 8845 CodeSynthesisContext::SynthesisKind Kind, 8846 sema::TemplateDeductionInfo &DeductionInfo, 8847 SourceRange InstantiationRange = SourceRange()); 8848 8849 /// Note that we are instantiating as part of template 8850 /// argument deduction for a class template declaration. 8851 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8852 TemplateDecl *Template, 8853 ArrayRef<TemplateArgument> TemplateArgs, 8854 sema::TemplateDeductionInfo &DeductionInfo, 8855 SourceRange InstantiationRange = SourceRange()); 8856 8857 /// Note that we are instantiating as part of template 8858 /// argument deduction for a class template partial 8859 /// specialization. 8860 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8861 ClassTemplatePartialSpecializationDecl *PartialSpec, 8862 ArrayRef<TemplateArgument> TemplateArgs, 8863 sema::TemplateDeductionInfo &DeductionInfo, 8864 SourceRange InstantiationRange = SourceRange()); 8865 8866 /// Note that we are instantiating as part of template 8867 /// argument deduction for a variable template partial 8868 /// specialization. 8869 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8870 VarTemplatePartialSpecializationDecl *PartialSpec, 8871 ArrayRef<TemplateArgument> TemplateArgs, 8872 sema::TemplateDeductionInfo &DeductionInfo, 8873 SourceRange InstantiationRange = SourceRange()); 8874 8875 /// Note that we are instantiating a default argument for a function 8876 /// parameter. 8877 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8878 ParmVarDecl *Param, 8879 ArrayRef<TemplateArgument> TemplateArgs, 8880 SourceRange InstantiationRange = SourceRange()); 8881 8882 /// Note that we are substituting prior template arguments into a 8883 /// non-type parameter. 8884 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8885 NamedDecl *Template, 8886 NonTypeTemplateParmDecl *Param, 8887 ArrayRef<TemplateArgument> TemplateArgs, 8888 SourceRange InstantiationRange); 8889 8890 /// Note that we are substituting prior template arguments into a 8891 /// template template parameter. 8892 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8893 NamedDecl *Template, 8894 TemplateTemplateParmDecl *Param, 8895 ArrayRef<TemplateArgument> TemplateArgs, 8896 SourceRange InstantiationRange); 8897 8898 /// Note that we are checking the default template argument 8899 /// against the template parameter for a given template-id. 8900 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8901 TemplateDecl *Template, 8902 NamedDecl *Param, 8903 ArrayRef<TemplateArgument> TemplateArgs, 8904 SourceRange InstantiationRange); 8905 8906 struct ConstraintsCheck {}; 8907 /// \brief Note that we are checking the constraints associated with some 8908 /// constrained entity (a concept declaration or a template with associated 8909 /// constraints). 8910 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8911 ConstraintsCheck, NamedDecl *Template, 8912 ArrayRef<TemplateArgument> TemplateArgs, 8913 SourceRange InstantiationRange); 8914 8915 struct ConstraintSubstitution {}; 8916 /// \brief Note that we are checking a constraint expression associated 8917 /// with a template declaration or as part of the satisfaction check of a 8918 /// concept. 8919 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8920 ConstraintSubstitution, NamedDecl *Template, 8921 sema::TemplateDeductionInfo &DeductionInfo, 8922 SourceRange InstantiationRange); 8923 8924 struct ConstraintNormalization {}; 8925 /// \brief Note that we are normalizing a constraint expression. 8926 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8927 ConstraintNormalization, NamedDecl *Template, 8928 SourceRange InstantiationRange); 8929 8930 struct ParameterMappingSubstitution {}; 8931 /// \brief Note that we are subtituting into the parameter mapping of an 8932 /// atomic constraint during constraint normalization. 8933 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8934 ParameterMappingSubstitution, NamedDecl *Template, 8935 SourceRange InstantiationRange); 8936 8937 /// \brief Note that we are substituting template arguments into a part of 8938 /// a requirement of a requires expression. 8939 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8940 concepts::Requirement *Req, 8941 sema::TemplateDeductionInfo &DeductionInfo, 8942 SourceRange InstantiationRange = SourceRange()); 8943 8944 /// \brief Note that we are checking the satisfaction of the constraint 8945 /// expression inside of a nested requirement. 8946 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8947 concepts::NestedRequirement *Req, ConstraintsCheck, 8948 SourceRange InstantiationRange = SourceRange()); 8949 8950 /// Note that we have finished instantiating this template. 8951 void Clear(); 8952 ~InstantiatingTemplateInstantiatingTemplate8953 ~InstantiatingTemplate() { Clear(); } 8954 8955 /// Determines whether we have exceeded the maximum 8956 /// recursive template instantiations. isInvalidInstantiatingTemplate8957 bool isInvalid() const { return Invalid; } 8958 8959 /// Determine whether we are already instantiating this 8960 /// specialization in some surrounding active instantiation. isAlreadyInstantiatingInstantiatingTemplate8961 bool isAlreadyInstantiating() const { return AlreadyInstantiating; } 8962 8963 private: 8964 Sema &SemaRef; 8965 bool Invalid; 8966 bool AlreadyInstantiating; 8967 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, 8968 SourceRange InstantiationRange); 8969 8970 InstantiatingTemplate( 8971 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, 8972 SourceLocation PointOfInstantiation, SourceRange InstantiationRange, 8973 Decl *Entity, NamedDecl *Template = nullptr, 8974 ArrayRef<TemplateArgument> TemplateArgs = None, 8975 sema::TemplateDeductionInfo *DeductionInfo = nullptr); 8976 8977 InstantiatingTemplate(const InstantiatingTemplate&) = delete; 8978 8979 InstantiatingTemplate& 8980 operator=(const InstantiatingTemplate&) = delete; 8981 }; 8982 8983 void pushCodeSynthesisContext(CodeSynthesisContext Ctx); 8984 void popCodeSynthesisContext(); 8985 8986 /// Determine whether we are currently performing template instantiation. inTemplateInstantiation()8987 bool inTemplateInstantiation() const { 8988 return CodeSynthesisContexts.size() > NonInstantiationEntries; 8989 } 8990 PrintContextStack()8991 void PrintContextStack() { 8992 if (!CodeSynthesisContexts.empty() && 8993 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) { 8994 PrintInstantiationStack(); 8995 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size(); 8996 } 8997 if (PragmaAttributeCurrentTargetDecl) 8998 PrintPragmaAttributeInstantiationPoint(); 8999 } 9000 void PrintInstantiationStack(); 9001 9002 void PrintPragmaAttributeInstantiationPoint(); 9003 9004 /// Determines whether we are currently in a context where 9005 /// template argument substitution failures are not considered 9006 /// errors. 9007 /// 9008 /// \returns An empty \c Optional if we're not in a SFINAE context. 9009 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest 9010 /// template-deduction context object, which can be used to capture 9011 /// diagnostics that will be suppressed. 9012 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; 9013 9014 /// Determines whether we are currently in a context that 9015 /// is not evaluated as per C++ [expr] p5. isUnevaluatedContext()9016 bool isUnevaluatedContext() const { 9017 assert(!ExprEvalContexts.empty() && 9018 "Must be in an expression evaluation context"); 9019 return ExprEvalContexts.back().isUnevaluated(); 9020 } 9021 9022 /// RAII class used to determine whether SFINAE has 9023 /// trapped any errors that occur during template argument 9024 /// deduction. 9025 class SFINAETrap { 9026 Sema &SemaRef; 9027 unsigned PrevSFINAEErrors; 9028 bool PrevInNonInstantiationSFINAEContext; 9029 bool PrevAccessCheckingSFINAE; 9030 bool PrevLastDiagnosticIgnored; 9031 9032 public: 9033 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) SemaRef(SemaRef)9034 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), 9035 PrevInNonInstantiationSFINAEContext( 9036 SemaRef.InNonInstantiationSFINAEContext), 9037 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE), 9038 PrevLastDiagnosticIgnored( 9039 SemaRef.getDiagnostics().isLastDiagnosticIgnored()) 9040 { 9041 if (!SemaRef.isSFINAEContext()) 9042 SemaRef.InNonInstantiationSFINAEContext = true; 9043 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; 9044 } 9045 ~SFINAETrap()9046 ~SFINAETrap() { 9047 SemaRef.NumSFINAEErrors = PrevSFINAEErrors; 9048 SemaRef.InNonInstantiationSFINAEContext 9049 = PrevInNonInstantiationSFINAEContext; 9050 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; 9051 SemaRef.getDiagnostics().setLastDiagnosticIgnored( 9052 PrevLastDiagnosticIgnored); 9053 } 9054 9055 /// Determine whether any SFINAE errors have been trapped. hasErrorOccurred()9056 bool hasErrorOccurred() const { 9057 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; 9058 } 9059 }; 9060 9061 /// RAII class used to indicate that we are performing provisional 9062 /// semantic analysis to determine the validity of a construct, so 9063 /// typo-correction and diagnostics in the immediate context (not within 9064 /// implicitly-instantiated templates) should be suppressed. 9065 class TentativeAnalysisScope { 9066 Sema &SemaRef; 9067 // FIXME: Using a SFINAETrap for this is a hack. 9068 SFINAETrap Trap; 9069 bool PrevDisableTypoCorrection; 9070 public: TentativeAnalysisScope(Sema & SemaRef)9071 explicit TentativeAnalysisScope(Sema &SemaRef) 9072 : SemaRef(SemaRef), Trap(SemaRef, true), 9073 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) { 9074 SemaRef.DisableTypoCorrection = true; 9075 } ~TentativeAnalysisScope()9076 ~TentativeAnalysisScope() { 9077 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection; 9078 } 9079 }; 9080 9081 /// The current instantiation scope used to store local 9082 /// variables. 9083 LocalInstantiationScope *CurrentInstantiationScope; 9084 9085 /// Tracks whether we are in a context where typo correction is 9086 /// disabled. 9087 bool DisableTypoCorrection; 9088 9089 /// The number of typos corrected by CorrectTypo. 9090 unsigned TyposCorrected; 9091 9092 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet; 9093 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations; 9094 9095 /// A cache containing identifiers for which typo correction failed and 9096 /// their locations, so that repeated attempts to correct an identifier in a 9097 /// given location are ignored if typo correction already failed for it. 9098 IdentifierSourceLocations TypoCorrectionFailures; 9099 9100 /// Worker object for performing CFG-based warnings. 9101 sema::AnalysisBasedWarnings AnalysisWarnings; 9102 threadSafety::BeforeSet *ThreadSafetyDeclCache; 9103 9104 /// An entity for which implicit template instantiation is required. 9105 /// 9106 /// The source location associated with the declaration is the first place in 9107 /// the source code where the declaration was "used". It is not necessarily 9108 /// the point of instantiation (which will be either before or after the 9109 /// namespace-scope declaration that triggered this implicit instantiation), 9110 /// However, it is the location that diagnostics should generally refer to, 9111 /// because users will need to know what code triggered the instantiation. 9112 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; 9113 9114 /// The queue of implicit template instantiations that are required 9115 /// but have not yet been performed. 9116 std::deque<PendingImplicitInstantiation> PendingInstantiations; 9117 9118 /// Queue of implicit template instantiations that cannot be performed 9119 /// eagerly. 9120 SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations; 9121 9122 class GlobalEagerInstantiationScope { 9123 public: GlobalEagerInstantiationScope(Sema & S,bool Enabled)9124 GlobalEagerInstantiationScope(Sema &S, bool Enabled) 9125 : S(S), Enabled(Enabled) { 9126 if (!Enabled) return; 9127 9128 SavedPendingInstantiations.swap(S.PendingInstantiations); 9129 SavedVTableUses.swap(S.VTableUses); 9130 } 9131 perform()9132 void perform() { 9133 if (Enabled) { 9134 S.DefineUsedVTables(); 9135 S.PerformPendingInstantiations(); 9136 } 9137 } 9138 ~GlobalEagerInstantiationScope()9139 ~GlobalEagerInstantiationScope() { 9140 if (!Enabled) return; 9141 9142 // Restore the set of pending vtables. 9143 assert(S.VTableUses.empty() && 9144 "VTableUses should be empty before it is discarded."); 9145 S.VTableUses.swap(SavedVTableUses); 9146 9147 // Restore the set of pending implicit instantiations. 9148 if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) { 9149 assert(S.PendingInstantiations.empty() && 9150 "PendingInstantiations should be empty before it is discarded."); 9151 S.PendingInstantiations.swap(SavedPendingInstantiations); 9152 } else { 9153 // Template instantiations in the PCH may be delayed until the TU. 9154 S.PendingInstantiations.swap(SavedPendingInstantiations); 9155 S.PendingInstantiations.insert(S.PendingInstantiations.end(), 9156 SavedPendingInstantiations.begin(), 9157 SavedPendingInstantiations.end()); 9158 } 9159 } 9160 9161 private: 9162 Sema &S; 9163 SmallVector<VTableUse, 16> SavedVTableUses; 9164 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; 9165 bool Enabled; 9166 }; 9167 9168 /// The queue of implicit template instantiations that are required 9169 /// and must be performed within the current local scope. 9170 /// 9171 /// This queue is only used for member functions of local classes in 9172 /// templates, which must be instantiated in the same scope as their 9173 /// enclosing function, so that they can reference function-local 9174 /// types, static variables, enumerators, etc. 9175 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; 9176 9177 class LocalEagerInstantiationScope { 9178 public: LocalEagerInstantiationScope(Sema & S)9179 LocalEagerInstantiationScope(Sema &S) : S(S) { 9180 SavedPendingLocalImplicitInstantiations.swap( 9181 S.PendingLocalImplicitInstantiations); 9182 } 9183 perform()9184 void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); } 9185 ~LocalEagerInstantiationScope()9186 ~LocalEagerInstantiationScope() { 9187 assert(S.PendingLocalImplicitInstantiations.empty() && 9188 "there shouldn't be any pending local implicit instantiations"); 9189 SavedPendingLocalImplicitInstantiations.swap( 9190 S.PendingLocalImplicitInstantiations); 9191 } 9192 9193 private: 9194 Sema &S; 9195 std::deque<PendingImplicitInstantiation> 9196 SavedPendingLocalImplicitInstantiations; 9197 }; 9198 9199 /// A helper class for building up ExtParameterInfos. 9200 class ExtParameterInfoBuilder { 9201 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos; 9202 bool HasInteresting = false; 9203 9204 public: 9205 /// Set the ExtParameterInfo for the parameter at the given index, 9206 /// set(unsigned index,FunctionProtoType::ExtParameterInfo info)9207 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) { 9208 assert(Infos.size() <= index); 9209 Infos.resize(index); 9210 Infos.push_back(info); 9211 9212 if (!HasInteresting) 9213 HasInteresting = (info != FunctionProtoType::ExtParameterInfo()); 9214 } 9215 9216 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the 9217 /// ExtParameterInfo array we've built up. 9218 const FunctionProtoType::ExtParameterInfo * getPointerOrNull(unsigned numParams)9219 getPointerOrNull(unsigned numParams) { 9220 if (!HasInteresting) return nullptr; 9221 Infos.resize(numParams); 9222 return Infos.data(); 9223 } 9224 }; 9225 9226 void PerformPendingInstantiations(bool LocalOnly = false); 9227 9228 TypeSourceInfo *SubstType(TypeSourceInfo *T, 9229 const MultiLevelTemplateArgumentList &TemplateArgs, 9230 SourceLocation Loc, DeclarationName Entity, 9231 bool AllowDeducedTST = false); 9232 9233 QualType SubstType(QualType T, 9234 const MultiLevelTemplateArgumentList &TemplateArgs, 9235 SourceLocation Loc, DeclarationName Entity); 9236 9237 TypeSourceInfo *SubstType(TypeLoc TL, 9238 const MultiLevelTemplateArgumentList &TemplateArgs, 9239 SourceLocation Loc, DeclarationName Entity); 9240 9241 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, 9242 const MultiLevelTemplateArgumentList &TemplateArgs, 9243 SourceLocation Loc, 9244 DeclarationName Entity, 9245 CXXRecordDecl *ThisContext, 9246 Qualifiers ThisTypeQuals); 9247 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, 9248 const MultiLevelTemplateArgumentList &Args); 9249 bool SubstExceptionSpec(SourceLocation Loc, 9250 FunctionProtoType::ExceptionSpecInfo &ESI, 9251 SmallVectorImpl<QualType> &ExceptionStorage, 9252 const MultiLevelTemplateArgumentList &Args); 9253 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, 9254 const MultiLevelTemplateArgumentList &TemplateArgs, 9255 int indexAdjustment, 9256 Optional<unsigned> NumExpansions, 9257 bool ExpectParameterPack); 9258 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, 9259 const FunctionProtoType::ExtParameterInfo *ExtParamInfos, 9260 const MultiLevelTemplateArgumentList &TemplateArgs, 9261 SmallVectorImpl<QualType> &ParamTypes, 9262 SmallVectorImpl<ParmVarDecl *> *OutParams, 9263 ExtParameterInfoBuilder &ParamInfos); 9264 ExprResult SubstExpr(Expr *E, 9265 const MultiLevelTemplateArgumentList &TemplateArgs); 9266 9267 /// Substitute the given template arguments into a list of 9268 /// expressions, expanding pack expansions if required. 9269 /// 9270 /// \param Exprs The list of expressions to substitute into. 9271 /// 9272 /// \param IsCall Whether this is some form of call, in which case 9273 /// default arguments will be dropped. 9274 /// 9275 /// \param TemplateArgs The set of template arguments to substitute. 9276 /// 9277 /// \param Outputs Will receive all of the substituted arguments. 9278 /// 9279 /// \returns true if an error occurred, false otherwise. 9280 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, 9281 const MultiLevelTemplateArgumentList &TemplateArgs, 9282 SmallVectorImpl<Expr *> &Outputs); 9283 9284 StmtResult SubstStmt(Stmt *S, 9285 const MultiLevelTemplateArgumentList &TemplateArgs); 9286 9287 TemplateParameterList * 9288 SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, 9289 const MultiLevelTemplateArgumentList &TemplateArgs); 9290 9291 bool 9292 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, 9293 const MultiLevelTemplateArgumentList &TemplateArgs, 9294 TemplateArgumentListInfo &Outputs); 9295 9296 9297 Decl *SubstDecl(Decl *D, DeclContext *Owner, 9298 const MultiLevelTemplateArgumentList &TemplateArgs); 9299 9300 /// Substitute the name and return type of a defaulted 'operator<=>' to form 9301 /// an implicit 'operator=='. 9302 FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, 9303 FunctionDecl *Spaceship); 9304 9305 ExprResult SubstInitializer(Expr *E, 9306 const MultiLevelTemplateArgumentList &TemplateArgs, 9307 bool CXXDirectInit); 9308 9309 bool 9310 SubstBaseSpecifiers(CXXRecordDecl *Instantiation, 9311 CXXRecordDecl *Pattern, 9312 const MultiLevelTemplateArgumentList &TemplateArgs); 9313 9314 bool 9315 InstantiateClass(SourceLocation PointOfInstantiation, 9316 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, 9317 const MultiLevelTemplateArgumentList &TemplateArgs, 9318 TemplateSpecializationKind TSK, 9319 bool Complain = true); 9320 9321 bool InstantiateEnum(SourceLocation PointOfInstantiation, 9322 EnumDecl *Instantiation, EnumDecl *Pattern, 9323 const MultiLevelTemplateArgumentList &TemplateArgs, 9324 TemplateSpecializationKind TSK); 9325 9326 bool InstantiateInClassInitializer( 9327 SourceLocation PointOfInstantiation, FieldDecl *Instantiation, 9328 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); 9329 9330 struct LateInstantiatedAttribute { 9331 const Attr *TmplAttr; 9332 LocalInstantiationScope *Scope; 9333 Decl *NewDecl; 9334 LateInstantiatedAttributeLateInstantiatedAttribute9335 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, 9336 Decl *D) 9337 : TmplAttr(A), Scope(S), NewDecl(D) 9338 { } 9339 }; 9340 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; 9341 9342 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, 9343 const Decl *Pattern, Decl *Inst, 9344 LateInstantiatedAttrVec *LateAttrs = nullptr, 9345 LocalInstantiationScope *OuterMostScope = nullptr); 9346 9347 void 9348 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, 9349 const Decl *Pattern, Decl *Inst, 9350 LateInstantiatedAttrVec *LateAttrs = nullptr, 9351 LocalInstantiationScope *OuterMostScope = nullptr); 9352 9353 void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor); 9354 9355 bool usesPartialOrExplicitSpecialization( 9356 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec); 9357 9358 bool 9359 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, 9360 ClassTemplateSpecializationDecl *ClassTemplateSpec, 9361 TemplateSpecializationKind TSK, 9362 bool Complain = true); 9363 9364 void InstantiateClassMembers(SourceLocation PointOfInstantiation, 9365 CXXRecordDecl *Instantiation, 9366 const MultiLevelTemplateArgumentList &TemplateArgs, 9367 TemplateSpecializationKind TSK); 9368 9369 void InstantiateClassTemplateSpecializationMembers( 9370 SourceLocation PointOfInstantiation, 9371 ClassTemplateSpecializationDecl *ClassTemplateSpec, 9372 TemplateSpecializationKind TSK); 9373 9374 NestedNameSpecifierLoc 9375 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 9376 const MultiLevelTemplateArgumentList &TemplateArgs); 9377 9378 DeclarationNameInfo 9379 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 9380 const MultiLevelTemplateArgumentList &TemplateArgs); 9381 TemplateName 9382 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, 9383 SourceLocation Loc, 9384 const MultiLevelTemplateArgumentList &TemplateArgs); 9385 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, 9386 TemplateArgumentListInfo &Result, 9387 const MultiLevelTemplateArgumentList &TemplateArgs); 9388 9389 bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, 9390 ParmVarDecl *Param); 9391 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, 9392 FunctionDecl *Function); 9393 bool CheckInstantiatedFunctionTemplateConstraints( 9394 SourceLocation PointOfInstantiation, FunctionDecl *Decl, 9395 ArrayRef<TemplateArgument> TemplateArgs, 9396 ConstraintSatisfaction &Satisfaction); 9397 FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, 9398 const TemplateArgumentList *Args, 9399 SourceLocation Loc); 9400 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 9401 FunctionDecl *Function, 9402 bool Recursive = false, 9403 bool DefinitionRequired = false, 9404 bool AtEndOfTU = false); 9405 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation( 9406 VarTemplateDecl *VarTemplate, VarDecl *FromVar, 9407 const TemplateArgumentList &TemplateArgList, 9408 const TemplateArgumentListInfo &TemplateArgsInfo, 9409 SmallVectorImpl<TemplateArgument> &Converted, 9410 SourceLocation PointOfInstantiation, 9411 LateInstantiatedAttrVec *LateAttrs = nullptr, 9412 LocalInstantiationScope *StartingScope = nullptr); 9413 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl( 9414 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, 9415 const MultiLevelTemplateArgumentList &TemplateArgs); 9416 void 9417 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, 9418 const MultiLevelTemplateArgumentList &TemplateArgs, 9419 LateInstantiatedAttrVec *LateAttrs, 9420 DeclContext *Owner, 9421 LocalInstantiationScope *StartingScope, 9422 bool InstantiatingVarTemplate = false, 9423 VarTemplateSpecializationDecl *PrevVTSD = nullptr); 9424 9425 void InstantiateVariableInitializer( 9426 VarDecl *Var, VarDecl *OldVar, 9427 const MultiLevelTemplateArgumentList &TemplateArgs); 9428 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, 9429 VarDecl *Var, bool Recursive = false, 9430 bool DefinitionRequired = false, 9431 bool AtEndOfTU = false); 9432 9433 void InstantiateMemInitializers(CXXConstructorDecl *New, 9434 const CXXConstructorDecl *Tmpl, 9435 const MultiLevelTemplateArgumentList &TemplateArgs); 9436 9437 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 9438 const MultiLevelTemplateArgumentList &TemplateArgs, 9439 bool FindingInstantiatedContext = false); 9440 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, 9441 const MultiLevelTemplateArgumentList &TemplateArgs); 9442 9443 // Objective-C declarations. 9444 enum ObjCContainerKind { 9445 OCK_None = -1, 9446 OCK_Interface = 0, 9447 OCK_Protocol, 9448 OCK_Category, 9449 OCK_ClassExtension, 9450 OCK_Implementation, 9451 OCK_CategoryImplementation 9452 }; 9453 ObjCContainerKind getObjCContainerKind() const; 9454 9455 DeclResult actOnObjCTypeParam(Scope *S, 9456 ObjCTypeParamVariance variance, 9457 SourceLocation varianceLoc, 9458 unsigned index, 9459 IdentifierInfo *paramName, 9460 SourceLocation paramLoc, 9461 SourceLocation colonLoc, 9462 ParsedType typeBound); 9463 9464 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc, 9465 ArrayRef<Decl *> typeParams, 9466 SourceLocation rAngleLoc); 9467 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList); 9468 9469 Decl *ActOnStartClassInterface( 9470 Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, 9471 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, 9472 IdentifierInfo *SuperName, SourceLocation SuperLoc, 9473 ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange, 9474 Decl *const *ProtoRefs, unsigned NumProtoRefs, 9475 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, 9476 const ParsedAttributesView &AttrList); 9477 9478 void ActOnSuperClassOfClassInterface(Scope *S, 9479 SourceLocation AtInterfaceLoc, 9480 ObjCInterfaceDecl *IDecl, 9481 IdentifierInfo *ClassName, 9482 SourceLocation ClassLoc, 9483 IdentifierInfo *SuperName, 9484 SourceLocation SuperLoc, 9485 ArrayRef<ParsedType> SuperTypeArgs, 9486 SourceRange SuperTypeArgsRange); 9487 9488 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, 9489 SmallVectorImpl<SourceLocation> &ProtocolLocs, 9490 IdentifierInfo *SuperName, 9491 SourceLocation SuperLoc); 9492 9493 Decl *ActOnCompatibilityAlias( 9494 SourceLocation AtCompatibilityAliasLoc, 9495 IdentifierInfo *AliasName, SourceLocation AliasLocation, 9496 IdentifierInfo *ClassName, SourceLocation ClassLocation); 9497 9498 bool CheckForwardProtocolDeclarationForCircularDependency( 9499 IdentifierInfo *PName, 9500 SourceLocation &PLoc, SourceLocation PrevLoc, 9501 const ObjCList<ObjCProtocolDecl> &PList); 9502 9503 Decl *ActOnStartProtocolInterface( 9504 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName, 9505 SourceLocation ProtocolLoc, Decl *const *ProtoRefNames, 9506 unsigned NumProtoRefs, const SourceLocation *ProtoLocs, 9507 SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); 9508 9509 Decl *ActOnStartCategoryInterface( 9510 SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, 9511 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, 9512 IdentifierInfo *CategoryName, SourceLocation CategoryLoc, 9513 Decl *const *ProtoRefs, unsigned NumProtoRefs, 9514 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, 9515 const ParsedAttributesView &AttrList); 9516 9517 Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc, 9518 IdentifierInfo *ClassName, 9519 SourceLocation ClassLoc, 9520 IdentifierInfo *SuperClassname, 9521 SourceLocation SuperClassLoc, 9522 const ParsedAttributesView &AttrList); 9523 9524 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, 9525 IdentifierInfo *ClassName, 9526 SourceLocation ClassLoc, 9527 IdentifierInfo *CatName, 9528 SourceLocation CatLoc, 9529 const ParsedAttributesView &AttrList); 9530 9531 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, 9532 ArrayRef<Decl *> Decls); 9533 9534 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, 9535 IdentifierInfo **IdentList, 9536 SourceLocation *IdentLocs, 9537 ArrayRef<ObjCTypeParamList *> TypeParamLists, 9538 unsigned NumElts); 9539 9540 DeclGroupPtrTy 9541 ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, 9542 ArrayRef<IdentifierLocPair> IdentList, 9543 const ParsedAttributesView &attrList); 9544 9545 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer, 9546 ArrayRef<IdentifierLocPair> ProtocolId, 9547 SmallVectorImpl<Decl *> &Protocols); 9548 9549 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId, 9550 SourceLocation ProtocolLoc, 9551 IdentifierInfo *TypeArgId, 9552 SourceLocation TypeArgLoc, 9553 bool SelectProtocolFirst = false); 9554 9555 /// Given a list of identifiers (and their locations), resolve the 9556 /// names to either Objective-C protocol qualifiers or type 9557 /// arguments, as appropriate. 9558 void actOnObjCTypeArgsOrProtocolQualifiers( 9559 Scope *S, 9560 ParsedType baseType, 9561 SourceLocation lAngleLoc, 9562 ArrayRef<IdentifierInfo *> identifiers, 9563 ArrayRef<SourceLocation> identifierLocs, 9564 SourceLocation rAngleLoc, 9565 SourceLocation &typeArgsLAngleLoc, 9566 SmallVectorImpl<ParsedType> &typeArgs, 9567 SourceLocation &typeArgsRAngleLoc, 9568 SourceLocation &protocolLAngleLoc, 9569 SmallVectorImpl<Decl *> &protocols, 9570 SourceLocation &protocolRAngleLoc, 9571 bool warnOnIncompleteProtocols); 9572 9573 /// Build a an Objective-C protocol-qualified 'id' type where no 9574 /// base type was specified. 9575 TypeResult actOnObjCProtocolQualifierType( 9576 SourceLocation lAngleLoc, 9577 ArrayRef<Decl *> protocols, 9578 ArrayRef<SourceLocation> protocolLocs, 9579 SourceLocation rAngleLoc); 9580 9581 /// Build a specialized and/or protocol-qualified Objective-C type. 9582 TypeResult actOnObjCTypeArgsAndProtocolQualifiers( 9583 Scope *S, 9584 SourceLocation Loc, 9585 ParsedType BaseType, 9586 SourceLocation TypeArgsLAngleLoc, 9587 ArrayRef<ParsedType> TypeArgs, 9588 SourceLocation TypeArgsRAngleLoc, 9589 SourceLocation ProtocolLAngleLoc, 9590 ArrayRef<Decl *> Protocols, 9591 ArrayRef<SourceLocation> ProtocolLocs, 9592 SourceLocation ProtocolRAngleLoc); 9593 9594 /// Build an Objective-C type parameter type. 9595 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, 9596 SourceLocation ProtocolLAngleLoc, 9597 ArrayRef<ObjCProtocolDecl *> Protocols, 9598 ArrayRef<SourceLocation> ProtocolLocs, 9599 SourceLocation ProtocolRAngleLoc, 9600 bool FailOnError = false); 9601 9602 /// Build an Objective-C object pointer type. 9603 QualType BuildObjCObjectType(QualType BaseType, 9604 SourceLocation Loc, 9605 SourceLocation TypeArgsLAngleLoc, 9606 ArrayRef<TypeSourceInfo *> TypeArgs, 9607 SourceLocation TypeArgsRAngleLoc, 9608 SourceLocation ProtocolLAngleLoc, 9609 ArrayRef<ObjCProtocolDecl *> Protocols, 9610 ArrayRef<SourceLocation> ProtocolLocs, 9611 SourceLocation ProtocolRAngleLoc, 9612 bool FailOnError = false); 9613 9614 /// Ensure attributes are consistent with type. 9615 /// \param [in, out] Attributes The attributes to check; they will 9616 /// be modified to be consistent with \p PropertyTy. 9617 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, 9618 SourceLocation Loc, 9619 unsigned &Attributes, 9620 bool propertyInPrimaryClass); 9621 9622 /// Process the specified property declaration and create decls for the 9623 /// setters and getters as needed. 9624 /// \param property The property declaration being processed 9625 void ProcessPropertyDecl(ObjCPropertyDecl *property); 9626 9627 9628 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, 9629 ObjCPropertyDecl *SuperProperty, 9630 const IdentifierInfo *Name, 9631 bool OverridingProtocolProperty); 9632 9633 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, 9634 ObjCInterfaceDecl *ID); 9635 9636 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, 9637 ArrayRef<Decl *> allMethods = None, 9638 ArrayRef<DeclGroupPtrTy> allTUVars = None); 9639 9640 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, 9641 SourceLocation LParenLoc, 9642 FieldDeclarator &FD, ObjCDeclSpec &ODS, 9643 Selector GetterSel, Selector SetterSel, 9644 tok::ObjCKeywordKind MethodImplKind, 9645 DeclContext *lexicalDC = nullptr); 9646 9647 Decl *ActOnPropertyImplDecl(Scope *S, 9648 SourceLocation AtLoc, 9649 SourceLocation PropertyLoc, 9650 bool ImplKind, 9651 IdentifierInfo *PropertyId, 9652 IdentifierInfo *PropertyIvar, 9653 SourceLocation PropertyIvarLoc, 9654 ObjCPropertyQueryKind QueryKind); 9655 9656 enum ObjCSpecialMethodKind { 9657 OSMK_None, 9658 OSMK_Alloc, 9659 OSMK_New, 9660 OSMK_Copy, 9661 OSMK_RetainingInit, 9662 OSMK_NonRetainingInit 9663 }; 9664 9665 struct ObjCArgInfo { 9666 IdentifierInfo *Name; 9667 SourceLocation NameLoc; 9668 // The Type is null if no type was specified, and the DeclSpec is invalid 9669 // in this case. 9670 ParsedType Type; 9671 ObjCDeclSpec DeclSpec; 9672 9673 /// ArgAttrs - Attribute list for this argument. 9674 ParsedAttributesView ArgAttrs; 9675 }; 9676 9677 Decl *ActOnMethodDeclaration( 9678 Scope *S, 9679 SourceLocation BeginLoc, // location of the + or -. 9680 SourceLocation EndLoc, // location of the ; or {. 9681 tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType, 9682 ArrayRef<SourceLocation> SelectorLocs, Selector Sel, 9683 // optional arguments. The number of types/arguments is obtained 9684 // from the Sel.getNumArgs(). 9685 ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo, 9686 unsigned CNumArgs, // c-style args 9687 const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind, 9688 bool isVariadic, bool MethodDefinition); 9689 9690 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, 9691 const ObjCObjectPointerType *OPT, 9692 bool IsInstance); 9693 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, 9694 bool IsInstance); 9695 9696 bool CheckARCMethodDecl(ObjCMethodDecl *method); 9697 bool inferObjCARCLifetime(ValueDecl *decl); 9698 9699 void deduceOpenCLAddressSpace(ValueDecl *decl); 9700 9701 ExprResult 9702 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, 9703 Expr *BaseExpr, 9704 SourceLocation OpLoc, 9705 DeclarationName MemberName, 9706 SourceLocation MemberLoc, 9707 SourceLocation SuperLoc, QualType SuperType, 9708 bool Super); 9709 9710 ExprResult 9711 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, 9712 IdentifierInfo &propertyName, 9713 SourceLocation receiverNameLoc, 9714 SourceLocation propertyNameLoc); 9715 9716 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); 9717 9718 /// Describes the kind of message expression indicated by a message 9719 /// send that starts with an identifier. 9720 enum ObjCMessageKind { 9721 /// The message is sent to 'super'. 9722 ObjCSuperMessage, 9723 /// The message is an instance message. 9724 ObjCInstanceMessage, 9725 /// The message is a class message, and the identifier is a type 9726 /// name. 9727 ObjCClassMessage 9728 }; 9729 9730 ObjCMessageKind getObjCMessageKind(Scope *S, 9731 IdentifierInfo *Name, 9732 SourceLocation NameLoc, 9733 bool IsSuper, 9734 bool HasTrailingDot, 9735 ParsedType &ReceiverType); 9736 9737 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, 9738 Selector Sel, 9739 SourceLocation LBracLoc, 9740 ArrayRef<SourceLocation> SelectorLocs, 9741 SourceLocation RBracLoc, 9742 MultiExprArg Args); 9743 9744 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, 9745 QualType ReceiverType, 9746 SourceLocation SuperLoc, 9747 Selector Sel, 9748 ObjCMethodDecl *Method, 9749 SourceLocation LBracLoc, 9750 ArrayRef<SourceLocation> SelectorLocs, 9751 SourceLocation RBracLoc, 9752 MultiExprArg Args, 9753 bool isImplicit = false); 9754 9755 ExprResult BuildClassMessageImplicit(QualType ReceiverType, 9756 bool isSuperReceiver, 9757 SourceLocation Loc, 9758 Selector Sel, 9759 ObjCMethodDecl *Method, 9760 MultiExprArg Args); 9761 9762 ExprResult ActOnClassMessage(Scope *S, 9763 ParsedType Receiver, 9764 Selector Sel, 9765 SourceLocation LBracLoc, 9766 ArrayRef<SourceLocation> SelectorLocs, 9767 SourceLocation RBracLoc, 9768 MultiExprArg Args); 9769 9770 ExprResult BuildInstanceMessage(Expr *Receiver, 9771 QualType ReceiverType, 9772 SourceLocation SuperLoc, 9773 Selector Sel, 9774 ObjCMethodDecl *Method, 9775 SourceLocation LBracLoc, 9776 ArrayRef<SourceLocation> SelectorLocs, 9777 SourceLocation RBracLoc, 9778 MultiExprArg Args, 9779 bool isImplicit = false); 9780 9781 ExprResult BuildInstanceMessageImplicit(Expr *Receiver, 9782 QualType ReceiverType, 9783 SourceLocation Loc, 9784 Selector Sel, 9785 ObjCMethodDecl *Method, 9786 MultiExprArg Args); 9787 9788 ExprResult ActOnInstanceMessage(Scope *S, 9789 Expr *Receiver, 9790 Selector Sel, 9791 SourceLocation LBracLoc, 9792 ArrayRef<SourceLocation> SelectorLocs, 9793 SourceLocation RBracLoc, 9794 MultiExprArg Args); 9795 9796 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, 9797 ObjCBridgeCastKind Kind, 9798 SourceLocation BridgeKeywordLoc, 9799 TypeSourceInfo *TSInfo, 9800 Expr *SubExpr); 9801 9802 ExprResult ActOnObjCBridgedCast(Scope *S, 9803 SourceLocation LParenLoc, 9804 ObjCBridgeCastKind Kind, 9805 SourceLocation BridgeKeywordLoc, 9806 ParsedType Type, 9807 SourceLocation RParenLoc, 9808 Expr *SubExpr); 9809 9810 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr); 9811 9812 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr); 9813 9814 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, 9815 CastKind &Kind); 9816 9817 bool checkObjCBridgeRelatedComponents(SourceLocation Loc, 9818 QualType DestType, QualType SrcType, 9819 ObjCInterfaceDecl *&RelatedClass, 9820 ObjCMethodDecl *&ClassMethod, 9821 ObjCMethodDecl *&InstanceMethod, 9822 TypedefNameDecl *&TDNDecl, 9823 bool CfToNs, bool Diagnose = true); 9824 9825 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, 9826 QualType DestType, QualType SrcType, 9827 Expr *&SrcExpr, bool Diagnose = true); 9828 9829 bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr, 9830 bool Diagnose = true); 9831 9832 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); 9833 9834 /// Check whether the given new method is a valid override of the 9835 /// given overridden method, and set any properties that should be inherited. 9836 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, 9837 const ObjCMethodDecl *Overridden); 9838 9839 /// Describes the compatibility of a result type with its method. 9840 enum ResultTypeCompatibilityKind { 9841 RTC_Compatible, 9842 RTC_Incompatible, 9843 RTC_Unknown 9844 }; 9845 9846 void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method, 9847 ObjCMethodDecl *overridden); 9848 9849 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, 9850 ObjCInterfaceDecl *CurrentClass, 9851 ResultTypeCompatibilityKind RTC); 9852 9853 enum PragmaOptionsAlignKind { 9854 POAK_Native, // #pragma options align=native 9855 POAK_Natural, // #pragma options align=natural 9856 POAK_Packed, // #pragma options align=packed 9857 POAK_Power, // #pragma options align=power 9858 POAK_Mac68k, // #pragma options align=mac68k 9859 POAK_Reset // #pragma options align=reset 9860 }; 9861 9862 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section 9863 void ActOnPragmaClangSection(SourceLocation PragmaLoc, 9864 PragmaClangSectionAction Action, 9865 PragmaClangSectionKind SecKind, StringRef SecName); 9866 9867 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. 9868 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, 9869 SourceLocation PragmaLoc); 9870 9871 /// ActOnPragmaPack - Called on well formed \#pragma pack(...). 9872 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, 9873 StringRef SlotLabel, Expr *Alignment); 9874 9875 enum class PragmaAlignPackDiagnoseKind { 9876 NonDefaultStateAtInclude, 9877 ChangedStateAtExit 9878 }; 9879 9880 void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind, 9881 SourceLocation IncludeLoc); 9882 void DiagnoseUnterminatedPragmaAlignPack(); 9883 9884 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. 9885 void ActOnPragmaMSStruct(PragmaMSStructKind Kind); 9886 9887 /// ActOnPragmaMSComment - Called on well formed 9888 /// \#pragma comment(kind, "arg"). 9889 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind, 9890 StringRef Arg); 9891 9892 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma 9893 /// pointers_to_members(representation method[, general purpose 9894 /// representation]). 9895 void ActOnPragmaMSPointersToMembers( 9896 LangOptions::PragmaMSPointersToMembersKind Kind, 9897 SourceLocation PragmaLoc); 9898 9899 /// Called on well formed \#pragma vtordisp(). 9900 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, 9901 SourceLocation PragmaLoc, 9902 MSVtorDispMode Value); 9903 9904 enum PragmaSectionKind { 9905 PSK_DataSeg, 9906 PSK_BSSSeg, 9907 PSK_ConstSeg, 9908 PSK_CodeSeg, 9909 }; 9910 9911 bool UnifySection(StringRef SectionName, int SectionFlags, 9912 NamedDecl *TheDecl); 9913 bool UnifySection(StringRef SectionName, 9914 int SectionFlags, 9915 SourceLocation PragmaSectionLocation); 9916 9917 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg. 9918 void ActOnPragmaMSSeg(SourceLocation PragmaLocation, 9919 PragmaMsStackAction Action, 9920 llvm::StringRef StackSlotLabel, 9921 StringLiteral *SegmentName, 9922 llvm::StringRef PragmaName); 9923 9924 /// Called on well formed \#pragma section(). 9925 void ActOnPragmaMSSection(SourceLocation PragmaLocation, 9926 int SectionFlags, StringLiteral *SegmentName); 9927 9928 /// Called on well-formed \#pragma init_seg(). 9929 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, 9930 StringLiteral *SegmentName); 9931 9932 /// Called on #pragma clang __debug dump II 9933 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II); 9934 9935 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch 9936 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, 9937 StringRef Value); 9938 9939 /// Are precise floating point semantics currently enabled? isPreciseFPEnabled()9940 bool isPreciseFPEnabled() { 9941 return !CurFPFeatures.getAllowFPReassociate() && 9942 !CurFPFeatures.getNoSignedZero() && 9943 !CurFPFeatures.getAllowReciprocal() && 9944 !CurFPFeatures.getAllowApproxFunc(); 9945 } 9946 9947 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control 9948 void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action, 9949 PragmaFloatControlKind Value); 9950 9951 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. 9952 void ActOnPragmaUnused(const Token &Identifier, 9953 Scope *curScope, 9954 SourceLocation PragmaLoc); 9955 9956 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . 9957 void ActOnPragmaVisibility(const IdentifierInfo* VisType, 9958 SourceLocation PragmaLoc); 9959 9960 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, 9961 SourceLocation Loc); 9962 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); 9963 9964 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. 9965 void ActOnPragmaWeakID(IdentifierInfo* WeakName, 9966 SourceLocation PragmaLoc, 9967 SourceLocation WeakNameLoc); 9968 9969 /// ActOnPragmaRedefineExtname - Called on well formed 9970 /// \#pragma redefine_extname oldname newname. 9971 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, 9972 IdentifierInfo* AliasName, 9973 SourceLocation PragmaLoc, 9974 SourceLocation WeakNameLoc, 9975 SourceLocation AliasNameLoc); 9976 9977 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. 9978 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, 9979 IdentifierInfo* AliasName, 9980 SourceLocation PragmaLoc, 9981 SourceLocation WeakNameLoc, 9982 SourceLocation AliasNameLoc); 9983 9984 /// ActOnPragmaFPContract - Called on well formed 9985 /// \#pragma {STDC,OPENCL} FP_CONTRACT and 9986 /// \#pragma clang fp contract 9987 void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC); 9988 9989 /// Called on well formed 9990 /// \#pragma clang fp reassociate 9991 void ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled); 9992 9993 /// ActOnPragmaFenvAccess - Called on well formed 9994 /// \#pragma STDC FENV_ACCESS 9995 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled); 9996 9997 /// Called on well formed '\#pragma clang fp' that has option 'exceptions'. 9998 void ActOnPragmaFPExceptions(SourceLocation Loc, 9999 LangOptions::FPExceptionModeKind); 10000 10001 /// Called to set constant rounding mode for floating point operations. 10002 void setRoundingMode(SourceLocation Loc, llvm::RoundingMode); 10003 10004 /// Called to set exception behavior for floating point operations. 10005 void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind); 10006 10007 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to 10008 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. 10009 void AddAlignmentAttributesForRecord(RecordDecl *RD); 10010 10011 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. 10012 void AddMsStructLayoutForRecord(RecordDecl *RD); 10013 10014 /// PushNamespaceVisibilityAttr - Note that we've entered a 10015 /// namespace with a visibility attribute. 10016 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, 10017 SourceLocation Loc); 10018 10019 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, 10020 /// add an appropriate visibility attribute. 10021 void AddPushedVisibilityAttribute(Decl *RD); 10022 10023 /// PopPragmaVisibility - Pop the top element of the visibility stack; used 10024 /// for '\#pragma GCC visibility' and visibility attributes on namespaces. 10025 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); 10026 10027 /// FreeVisContext - Deallocate and null out VisContext. 10028 void FreeVisContext(); 10029 10030 /// AddCFAuditedAttribute - Check whether we're currently within 10031 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding 10032 /// the appropriate attribute. 10033 void AddCFAuditedAttribute(Decl *D); 10034 10035 void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, 10036 SourceLocation PragmaLoc, 10037 attr::ParsedSubjectMatchRuleSet Rules); 10038 void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc, 10039 const IdentifierInfo *Namespace); 10040 10041 /// Called on well-formed '\#pragma clang attribute pop'. 10042 void ActOnPragmaAttributePop(SourceLocation PragmaLoc, 10043 const IdentifierInfo *Namespace); 10044 10045 /// Adds the attributes that have been specified using the 10046 /// '\#pragma clang attribute push' directives to the given declaration. 10047 void AddPragmaAttributes(Scope *S, Decl *D); 10048 10049 void DiagnoseUnterminatedPragmaAttribute(); 10050 10051 /// Called on well formed \#pragma clang optimize. 10052 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); 10053 10054 /// Get the location for the currently active "\#pragma clang optimize 10055 /// off". If this location is invalid, then the state of the pragma is "on". getOptimizeOffPragmaLocation()10056 SourceLocation getOptimizeOffPragmaLocation() const { 10057 return OptimizeOffPragmaLocation; 10058 } 10059 10060 /// Only called on function definitions; if there is a pragma in scope 10061 /// with the effect of a range-based optnone, consider marking the function 10062 /// with attribute optnone. 10063 void AddRangeBasedOptnone(FunctionDecl *FD); 10064 10065 /// Adds the 'optnone' attribute to the function declaration if there 10066 /// are no conflicts; Loc represents the location causing the 'optnone' 10067 /// attribute to be added (usually because of a pragma). 10068 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc); 10069 10070 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. 10071 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, 10072 bool IsPackExpansion); 10073 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T, 10074 bool IsPackExpansion); 10075 10076 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular 10077 /// declaration. 10078 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, 10079 Expr *OE); 10080 10081 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular 10082 /// declaration. 10083 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, 10084 Expr *ParamExpr); 10085 10086 /// AddAlignValueAttr - Adds an align_value attribute to a particular 10087 /// declaration. 10088 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); 10089 10090 /// AddAnnotationAttr - Adds an annotation Annot with Args arguments to D. 10091 void AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI, 10092 StringRef Annot, MutableArrayRef<Expr *> Args); 10093 10094 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular 10095 /// declaration. 10096 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, 10097 Expr *MaxThreads, Expr *MinBlocks); 10098 10099 /// AddModeAttr - Adds a mode attribute to a particular declaration. 10100 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name, 10101 bool InInstantiation = false); 10102 10103 void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI, 10104 ParameterABI ABI); 10105 10106 enum class RetainOwnershipKind {NS, CF, OS}; 10107 void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI, 10108 RetainOwnershipKind K, bool IsTemplateInstantiation); 10109 10110 /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size 10111 /// attribute to a particular declaration. 10112 void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, 10113 Expr *Min, Expr *Max); 10114 10115 /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a 10116 /// particular declaration. 10117 void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, 10118 Expr *Min, Expr *Max); 10119 10120 bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type); 10121 10122 //===--------------------------------------------------------------------===// 10123 // C++ Coroutines TS 10124 // 10125 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, 10126 StringRef Keyword); 10127 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E); 10128 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E); 10129 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E); 10130 10131 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, 10132 bool IsImplicit = false); 10133 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, 10134 UnresolvedLookupExpr* Lookup); 10135 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E); 10136 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, 10137 bool IsImplicit = false); 10138 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs); 10139 bool buildCoroutineParameterMoves(SourceLocation Loc); 10140 VarDecl *buildCoroutinePromise(SourceLocation Loc); 10141 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body); 10142 ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc, 10143 SourceLocation FuncLoc); 10144 /// Check that the expression co_await promise.final_suspend() shall not be 10145 /// potentially-throwing. 10146 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend); 10147 10148 //===--------------------------------------------------------------------===// 10149 // OpenMP directives and clauses. 10150 // 10151 private: 10152 void *VarDataSharingAttributesStack; 10153 10154 struct DeclareTargetContextInfo { 10155 struct MapInfo { 10156 OMPDeclareTargetDeclAttr::MapTypeTy MT; 10157 SourceLocation Loc; 10158 }; 10159 /// Explicitly listed variables and functions in a 'to' or 'link' clause. 10160 llvm::DenseMap<NamedDecl *, MapInfo> ExplicitlyMapped; 10161 10162 /// The 'device_type' as parsed from the clause. 10163 OMPDeclareTargetDeclAttr::DevTypeTy DT = OMPDeclareTargetDeclAttr::DT_Any; 10164 10165 /// The directive kind, `begin declare target` or `declare target`. 10166 OpenMPDirectiveKind Kind; 10167 10168 /// The directive location. 10169 SourceLocation Loc; 10170 DeclareTargetContextInfoDeclareTargetContextInfo10171 DeclareTargetContextInfo(OpenMPDirectiveKind Kind, SourceLocation Loc) 10172 : Kind(Kind), Loc(Loc) {} 10173 }; 10174 10175 /// Number of nested '#pragma omp declare target' directives. 10176 SmallVector<DeclareTargetContextInfo, 4> DeclareTargetNesting; 10177 10178 /// Initialization of data-sharing attributes stack. 10179 void InitDataSharingAttributesStack(); 10180 void DestroyDataSharingAttributesStack(); 10181 ExprResult 10182 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind, 10183 bool StrictlyPositive = true); 10184 /// Returns OpenMP nesting level for current directive. 10185 unsigned getOpenMPNestingLevel() const; 10186 10187 /// Adjusts the function scopes index for the target-based regions. 10188 void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, 10189 unsigned Level) const; 10190 10191 /// Returns the number of scopes associated with the construct on the given 10192 /// OpenMP level. 10193 int getNumberOfConstructScopes(unsigned Level) const; 10194 10195 /// Push new OpenMP function region for non-capturing function. 10196 void pushOpenMPFunctionRegion(); 10197 10198 /// Pop OpenMP function region for non-capturing function. 10199 void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI); 10200 10201 /// Helper to keep information about the current `omp begin/end declare 10202 /// variant` nesting. 10203 struct OMPDeclareVariantScope { 10204 /// The associated OpenMP context selector. 10205 OMPTraitInfo *TI; 10206 10207 /// The associated OpenMP context selector mangling. 10208 std::string NameSuffix; 10209 10210 OMPDeclareVariantScope(OMPTraitInfo &TI); 10211 }; 10212 10213 /// Return the OMPTraitInfo for the surrounding scope, if any. getOMPTraitInfoForSurroundingScope()10214 OMPTraitInfo *getOMPTraitInfoForSurroundingScope() { 10215 return OMPDeclareVariantScopes.empty() ? nullptr 10216 : OMPDeclareVariantScopes.back().TI; 10217 } 10218 10219 /// The current `omp begin/end declare variant` scopes. 10220 SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes; 10221 10222 /// The current `omp begin/end assumes` scopes. 10223 SmallVector<AssumptionAttr *, 4> OMPAssumeScoped; 10224 10225 /// All `omp assumes` we encountered so far. 10226 SmallVector<AssumptionAttr *, 4> OMPAssumeGlobal; 10227 10228 public: 10229 /// The declarator \p D defines a function in the scope \p S which is nested 10230 /// in an `omp begin/end declare variant` scope. In this method we create a 10231 /// declaration for \p D and rename \p D according to the OpenMP context 10232 /// selector of the surrounding scope. Return all base functions in \p Bases. 10233 void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 10234 Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, 10235 SmallVectorImpl<FunctionDecl *> &Bases); 10236 10237 /// Register \p D as specialization of all base functions in \p Bases in the 10238 /// current `omp begin/end declare variant` scope. 10239 void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( 10240 Decl *D, SmallVectorImpl<FunctionDecl *> &Bases); 10241 10242 /// Act on \p D, a function definition inside of an `omp [begin/end] assumes`. 10243 void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D); 10244 10245 /// Can we exit an OpenMP declare variant scope at the moment. isInOpenMPDeclareVariantScope()10246 bool isInOpenMPDeclareVariantScope() const { 10247 return !OMPDeclareVariantScopes.empty(); 10248 } 10249 10250 /// Given the potential call expression \p Call, determine if there is a 10251 /// specialization via the OpenMP declare variant mechanism available. If 10252 /// there is, return the specialized call expression, otherwise return the 10253 /// original \p Call. 10254 ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope, 10255 SourceLocation LParenLoc, MultiExprArg ArgExprs, 10256 SourceLocation RParenLoc, Expr *ExecConfig); 10257 10258 /// Handle a `omp begin declare variant`. 10259 void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI); 10260 10261 /// Handle a `omp end declare variant`. 10262 void ActOnOpenMPEndDeclareVariant(); 10263 10264 /// Checks if the variant/multiversion functions are compatible. 10265 bool areMultiversionVariantFunctionsCompatible( 10266 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10267 const PartialDiagnostic &NoProtoDiagID, 10268 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10269 const PartialDiagnosticAt &NoSupportDiagIDAt, 10270 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10271 bool ConstexprSupported, bool CLinkageMayDiffer); 10272 10273 /// Function tries to capture lambda's captured variables in the OpenMP region 10274 /// before the original lambda is captured. 10275 void tryCaptureOpenMPLambdas(ValueDecl *V); 10276 10277 /// Return true if the provided declaration \a VD should be captured by 10278 /// reference. 10279 /// \param Level Relative level of nested OpenMP construct for that the check 10280 /// is performed. 10281 /// \param OpenMPCaptureLevel Capture level within an OpenMP construct. 10282 bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, 10283 unsigned OpenMPCaptureLevel) const; 10284 10285 /// Check if the specified variable is used in one of the private 10286 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP 10287 /// constructs. 10288 VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false, 10289 unsigned StopAt = 0); 10290 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 10291 ExprObjectKind OK, SourceLocation Loc); 10292 10293 /// If the current region is a loop-based region, mark the start of the loop 10294 /// construct. 10295 void startOpenMPLoop(); 10296 10297 /// If the current region is a range loop-based region, mark the start of the 10298 /// loop construct. 10299 void startOpenMPCXXRangeFor(); 10300 10301 /// Check if the specified variable is used in 'private' clause. 10302 /// \param Level Relative level of nested OpenMP construct for that the check 10303 /// is performed. 10304 OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, 10305 unsigned CapLevel) const; 10306 10307 /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.) 10308 /// for \p FD based on DSA for the provided corresponding captured declaration 10309 /// \p D. 10310 void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level); 10311 10312 /// Check if the specified variable is captured by 'target' directive. 10313 /// \param Level Relative level of nested OpenMP construct for that the check 10314 /// is performed. 10315 bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, 10316 unsigned CaptureLevel) const; 10317 10318 /// Check if the specified global variable must be captured by outer capture 10319 /// regions. 10320 /// \param Level Relative level of nested OpenMP construct for that 10321 /// the check is performed. 10322 bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, 10323 unsigned CaptureLevel) const; 10324 10325 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc, 10326 Expr *Op); 10327 /// Called on start of new data sharing attribute block. 10328 void StartOpenMPDSABlock(OpenMPDirectiveKind K, 10329 const DeclarationNameInfo &DirName, Scope *CurScope, 10330 SourceLocation Loc); 10331 /// Start analysis of clauses. 10332 void StartOpenMPClause(OpenMPClauseKind K); 10333 /// End analysis of clauses. 10334 void EndOpenMPClause(); 10335 /// Called on end of data sharing attribute block. 10336 void EndOpenMPDSABlock(Stmt *CurDirective); 10337 10338 /// Check if the current region is an OpenMP loop region and if it is, 10339 /// mark loop control variable, used in \p Init for loop initialization, as 10340 /// private by default. 10341 /// \param Init First part of the for loop. 10342 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init); 10343 10344 // OpenMP directives and clauses. 10345 /// Called on correct id-expression from the '#pragma omp 10346 /// threadprivate'. 10347 ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec, 10348 const DeclarationNameInfo &Id, 10349 OpenMPDirectiveKind Kind); 10350 /// Called on well-formed '#pragma omp threadprivate'. 10351 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective( 10352 SourceLocation Loc, 10353 ArrayRef<Expr *> VarList); 10354 /// Builds a new OpenMPThreadPrivateDecl and checks its correctness. 10355 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc, 10356 ArrayRef<Expr *> VarList); 10357 /// Called on well-formed '#pragma omp allocate'. 10358 DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc, 10359 ArrayRef<Expr *> VarList, 10360 ArrayRef<OMPClause *> Clauses, 10361 DeclContext *Owner = nullptr); 10362 10363 /// Called on well-formed '#pragma omp [begin] assume[s]'. 10364 void ActOnOpenMPAssumesDirective(SourceLocation Loc, 10365 OpenMPDirectiveKind DKind, 10366 ArrayRef<StringRef> Assumptions, 10367 bool SkippedClauses); 10368 10369 /// Check if there is an active global `omp begin assumes` directive. isInOpenMPAssumeScope()10370 bool isInOpenMPAssumeScope() const { return !OMPAssumeScoped.empty(); } 10371 10372 /// Check if there is an active global `omp assumes` directive. hasGlobalOpenMPAssumes()10373 bool hasGlobalOpenMPAssumes() const { return !OMPAssumeGlobal.empty(); } 10374 10375 /// Called on well-formed '#pragma omp end assumes'. 10376 void ActOnOpenMPEndAssumesDirective(); 10377 10378 /// Called on well-formed '#pragma omp requires'. 10379 DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc, 10380 ArrayRef<OMPClause *> ClauseList); 10381 /// Check restrictions on Requires directive 10382 OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc, 10383 ArrayRef<OMPClause *> Clauses); 10384 /// Check if the specified type is allowed to be used in 'omp declare 10385 /// reduction' construct. 10386 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 10387 TypeResult ParsedType); 10388 /// Called on start of '#pragma omp declare reduction'. 10389 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart( 10390 Scope *S, DeclContext *DC, DeclarationName Name, 10391 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 10392 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); 10393 /// Initialize declare reduction construct initializer. 10394 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D); 10395 /// Finish current declare reduction construct initializer. 10396 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner); 10397 /// Initialize declare reduction construct initializer. 10398 /// \return omp_priv variable. 10399 VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D); 10400 /// Finish current declare reduction construct initializer. 10401 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, 10402 VarDecl *OmpPrivParm); 10403 /// Called at the end of '#pragma omp declare reduction'. 10404 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd( 10405 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid); 10406 10407 /// Check variable declaration in 'omp declare mapper' construct. 10408 TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D); 10409 /// Check if the specified type is allowed to be used in 'omp declare 10410 /// mapper' construct. 10411 QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, 10412 TypeResult ParsedType); 10413 /// Called on start of '#pragma omp declare mapper'. 10414 DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective( 10415 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, 10416 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, 10417 Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, 10418 Decl *PrevDeclInScope = nullptr); 10419 /// Build the mapper variable of '#pragma omp declare mapper'. 10420 ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, 10421 QualType MapperType, 10422 SourceLocation StartLoc, 10423 DeclarationName VN); 10424 bool isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const; 10425 const ValueDecl *getOpenMPDeclareMapperVarName() const; 10426 10427 /// Called on the start of target region i.e. '#pragma omp declare target'. 10428 bool ActOnStartOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI); 10429 10430 /// Called at the end of target region i.e. '#pragma omp end declare target'. 10431 const DeclareTargetContextInfo ActOnOpenMPEndDeclareTargetDirective(); 10432 10433 /// Called once a target context is completed, that can be when a 10434 /// '#pragma omp end declare target' was encountered or when a 10435 /// '#pragma omp declare target' without declaration-definition-seq was 10436 /// encountered. 10437 void ActOnFinishedOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI); 10438 10439 /// Searches for the provided declaration name for OpenMP declare target 10440 /// directive. 10441 NamedDecl *lookupOpenMPDeclareTargetName(Scope *CurScope, 10442 CXXScopeSpec &ScopeSpec, 10443 const DeclarationNameInfo &Id); 10444 10445 /// Called on correct id-expression from the '#pragma omp declare target'. 10446 void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc, 10447 OMPDeclareTargetDeclAttr::MapTypeTy MT, 10448 OMPDeclareTargetDeclAttr::DevTypeTy DT); 10449 10450 /// Check declaration inside target region. 10451 void 10452 checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, 10453 SourceLocation IdLoc = SourceLocation()); 10454 /// Finishes analysis of the deferred functions calls that may be declared as 10455 /// host/nohost during device/host compilation. 10456 void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller, 10457 const FunctionDecl *Callee, 10458 SourceLocation Loc); 10459 /// Return true inside OpenMP declare target region. isInOpenMPDeclareTargetContext()10460 bool isInOpenMPDeclareTargetContext() const { 10461 return !DeclareTargetNesting.empty(); 10462 } 10463 /// Return true inside OpenMP target region. 10464 bool isInOpenMPTargetExecutionDirective() const; 10465 10466 /// Return the number of captured regions created for an OpenMP directive. 10467 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind); 10468 10469 /// Initialization of captured region for OpenMP region. 10470 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope); 10471 10472 /// Called for syntactical loops (ForStmt or CXXForRangeStmt) associated to 10473 /// an OpenMP loop directive. 10474 StmtResult ActOnOpenMPCanonicalLoop(Stmt *AStmt); 10475 10476 /// End of OpenMP region. 10477 /// 10478 /// \param S Statement associated with the current OpenMP region. 10479 /// \param Clauses List of clauses for the current OpenMP region. 10480 /// 10481 /// \returns Statement for finished OpenMP region. 10482 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses); 10483 StmtResult ActOnOpenMPExecutableDirective( 10484 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 10485 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 10486 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); 10487 /// Called on well-formed '\#pragma omp parallel' after parsing 10488 /// of the associated statement. 10489 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 10490 Stmt *AStmt, 10491 SourceLocation StartLoc, 10492 SourceLocation EndLoc); 10493 using VarsWithInheritedDSAType = 10494 llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>; 10495 /// Called on well-formed '\#pragma omp simd' after parsing 10496 /// of the associated statement. 10497 StmtResult 10498 ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 10499 SourceLocation StartLoc, SourceLocation EndLoc, 10500 VarsWithInheritedDSAType &VarsWithImplicitDSA); 10501 /// Called on well-formed '#pragma omp tile' after parsing of its clauses and 10502 /// the associated statement. 10503 StmtResult ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses, 10504 Stmt *AStmt, SourceLocation StartLoc, 10505 SourceLocation EndLoc); 10506 /// Called on well-formed '\#pragma omp for' after parsing 10507 /// of the associated statement. 10508 StmtResult 10509 ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 10510 SourceLocation StartLoc, SourceLocation EndLoc, 10511 VarsWithInheritedDSAType &VarsWithImplicitDSA); 10512 /// Called on well-formed '\#pragma omp for simd' after parsing 10513 /// of the associated statement. 10514 StmtResult 10515 ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 10516 SourceLocation StartLoc, SourceLocation EndLoc, 10517 VarsWithInheritedDSAType &VarsWithImplicitDSA); 10518 /// Called on well-formed '\#pragma omp sections' after parsing 10519 /// of the associated statement. 10520 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 10521 Stmt *AStmt, SourceLocation StartLoc, 10522 SourceLocation EndLoc); 10523 /// Called on well-formed '\#pragma omp section' after parsing of the 10524 /// associated statement. 10525 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc, 10526 SourceLocation EndLoc); 10527 /// Called on well-formed '\#pragma omp single' after parsing of the 10528 /// associated statement. 10529 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 10530 Stmt *AStmt, SourceLocation StartLoc, 10531 SourceLocation EndLoc); 10532 /// Called on well-formed '\#pragma omp master' after parsing of the 10533 /// associated statement. 10534 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc, 10535 SourceLocation EndLoc); 10536 /// Called on well-formed '\#pragma omp critical' after parsing of the 10537 /// associated statement. 10538 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, 10539 ArrayRef<OMPClause *> Clauses, 10540 Stmt *AStmt, SourceLocation StartLoc, 10541 SourceLocation EndLoc); 10542 /// Called on well-formed '\#pragma omp parallel for' after parsing 10543 /// of the associated statement. 10544 StmtResult ActOnOpenMPParallelForDirective( 10545 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10546 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10547 /// Called on well-formed '\#pragma omp parallel for simd' after 10548 /// parsing of the associated statement. 10549 StmtResult ActOnOpenMPParallelForSimdDirective( 10550 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10551 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10552 /// Called on well-formed '\#pragma omp parallel master' after 10553 /// parsing of the associated statement. 10554 StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses, 10555 Stmt *AStmt, 10556 SourceLocation StartLoc, 10557 SourceLocation EndLoc); 10558 /// Called on well-formed '\#pragma omp parallel sections' after 10559 /// parsing of the associated statement. 10560 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 10561 Stmt *AStmt, 10562 SourceLocation StartLoc, 10563 SourceLocation EndLoc); 10564 /// Called on well-formed '\#pragma omp task' after parsing of the 10565 /// associated statement. 10566 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 10567 Stmt *AStmt, SourceLocation StartLoc, 10568 SourceLocation EndLoc); 10569 /// Called on well-formed '\#pragma omp taskyield'. 10570 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 10571 SourceLocation EndLoc); 10572 /// Called on well-formed '\#pragma omp barrier'. 10573 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 10574 SourceLocation EndLoc); 10575 /// Called on well-formed '\#pragma omp taskwait'. 10576 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 10577 SourceLocation EndLoc); 10578 /// Called on well-formed '\#pragma omp taskgroup'. 10579 StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, 10580 Stmt *AStmt, SourceLocation StartLoc, 10581 SourceLocation EndLoc); 10582 /// Called on well-formed '\#pragma omp flush'. 10583 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 10584 SourceLocation StartLoc, 10585 SourceLocation EndLoc); 10586 /// Called on well-formed '\#pragma omp depobj'. 10587 StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses, 10588 SourceLocation StartLoc, 10589 SourceLocation EndLoc); 10590 /// Called on well-formed '\#pragma omp scan'. 10591 StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses, 10592 SourceLocation StartLoc, 10593 SourceLocation EndLoc); 10594 /// Called on well-formed '\#pragma omp ordered' after parsing of the 10595 /// associated statement. 10596 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 10597 Stmt *AStmt, SourceLocation StartLoc, 10598 SourceLocation EndLoc); 10599 /// Called on well-formed '\#pragma omp atomic' after parsing of the 10600 /// associated statement. 10601 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 10602 Stmt *AStmt, SourceLocation StartLoc, 10603 SourceLocation EndLoc); 10604 /// Called on well-formed '\#pragma omp target' after parsing of the 10605 /// associated statement. 10606 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 10607 Stmt *AStmt, SourceLocation StartLoc, 10608 SourceLocation EndLoc); 10609 /// Called on well-formed '\#pragma omp target data' after parsing of 10610 /// the associated statement. 10611 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 10612 Stmt *AStmt, SourceLocation StartLoc, 10613 SourceLocation EndLoc); 10614 /// Called on well-formed '\#pragma omp target enter data' after 10615 /// parsing of the associated statement. 10616 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 10617 SourceLocation StartLoc, 10618 SourceLocation EndLoc, 10619 Stmt *AStmt); 10620 /// Called on well-formed '\#pragma omp target exit data' after 10621 /// parsing of the associated statement. 10622 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 10623 SourceLocation StartLoc, 10624 SourceLocation EndLoc, 10625 Stmt *AStmt); 10626 /// Called on well-formed '\#pragma omp target parallel' after 10627 /// parsing of the associated statement. 10628 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 10629 Stmt *AStmt, 10630 SourceLocation StartLoc, 10631 SourceLocation EndLoc); 10632 /// Called on well-formed '\#pragma omp target parallel for' after 10633 /// parsing of the associated statement. 10634 StmtResult ActOnOpenMPTargetParallelForDirective( 10635 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10636 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10637 /// Called on well-formed '\#pragma omp teams' after parsing of the 10638 /// associated statement. 10639 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 10640 Stmt *AStmt, SourceLocation StartLoc, 10641 SourceLocation EndLoc); 10642 /// Called on well-formed '\#pragma omp cancellation point'. 10643 StmtResult 10644 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 10645 SourceLocation EndLoc, 10646 OpenMPDirectiveKind CancelRegion); 10647 /// Called on well-formed '\#pragma omp cancel'. 10648 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 10649 SourceLocation StartLoc, 10650 SourceLocation EndLoc, 10651 OpenMPDirectiveKind CancelRegion); 10652 /// Called on well-formed '\#pragma omp taskloop' after parsing of the 10653 /// associated statement. 10654 StmtResult 10655 ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 10656 SourceLocation StartLoc, SourceLocation EndLoc, 10657 VarsWithInheritedDSAType &VarsWithImplicitDSA); 10658 /// Called on well-formed '\#pragma omp taskloop simd' after parsing of 10659 /// the associated statement. 10660 StmtResult ActOnOpenMPTaskLoopSimdDirective( 10661 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10662 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10663 /// Called on well-formed '\#pragma omp master taskloop' after parsing of the 10664 /// associated statement. 10665 StmtResult ActOnOpenMPMasterTaskLoopDirective( 10666 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10667 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10668 /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of 10669 /// the associated statement. 10670 StmtResult ActOnOpenMPMasterTaskLoopSimdDirective( 10671 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10672 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10673 /// Called on well-formed '\#pragma omp parallel master taskloop' after 10674 /// parsing of the associated statement. 10675 StmtResult ActOnOpenMPParallelMasterTaskLoopDirective( 10676 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10677 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10678 /// Called on well-formed '\#pragma omp parallel master taskloop simd' after 10679 /// parsing of the associated statement. 10680 StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective( 10681 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10682 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10683 /// Called on well-formed '\#pragma omp distribute' after parsing 10684 /// of the associated statement. 10685 StmtResult 10686 ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 10687 SourceLocation StartLoc, SourceLocation EndLoc, 10688 VarsWithInheritedDSAType &VarsWithImplicitDSA); 10689 /// Called on well-formed '\#pragma omp target update'. 10690 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 10691 SourceLocation StartLoc, 10692 SourceLocation EndLoc, 10693 Stmt *AStmt); 10694 /// Called on well-formed '\#pragma omp distribute parallel for' after 10695 /// parsing of the associated statement. 10696 StmtResult ActOnOpenMPDistributeParallelForDirective( 10697 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10698 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10699 /// Called on well-formed '\#pragma omp distribute parallel for simd' 10700 /// after parsing of the associated statement. 10701 StmtResult ActOnOpenMPDistributeParallelForSimdDirective( 10702 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10703 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10704 /// Called on well-formed '\#pragma omp distribute simd' after 10705 /// parsing of the associated statement. 10706 StmtResult ActOnOpenMPDistributeSimdDirective( 10707 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10708 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10709 /// Called on well-formed '\#pragma omp target parallel for simd' after 10710 /// parsing of the associated statement. 10711 StmtResult ActOnOpenMPTargetParallelForSimdDirective( 10712 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10713 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10714 /// Called on well-formed '\#pragma omp target simd' after parsing of 10715 /// the associated statement. 10716 StmtResult 10717 ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 10718 SourceLocation StartLoc, SourceLocation EndLoc, 10719 VarsWithInheritedDSAType &VarsWithImplicitDSA); 10720 /// Called on well-formed '\#pragma omp teams distribute' after parsing of 10721 /// the associated statement. 10722 StmtResult ActOnOpenMPTeamsDistributeDirective( 10723 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10724 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10725 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing 10726 /// of the associated statement. 10727 StmtResult ActOnOpenMPTeamsDistributeSimdDirective( 10728 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10729 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10730 /// Called on well-formed '\#pragma omp teams distribute parallel for simd' 10731 /// after parsing of the associated statement. 10732 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective( 10733 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10734 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10735 /// Called on well-formed '\#pragma omp teams distribute parallel for' 10736 /// after parsing of the associated statement. 10737 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective( 10738 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10739 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10740 /// Called on well-formed '\#pragma omp target teams' after parsing of the 10741 /// associated statement. 10742 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 10743 Stmt *AStmt, 10744 SourceLocation StartLoc, 10745 SourceLocation EndLoc); 10746 /// Called on well-formed '\#pragma omp target teams distribute' after parsing 10747 /// of the associated statement. 10748 StmtResult ActOnOpenMPTargetTeamsDistributeDirective( 10749 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10750 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10751 /// Called on well-formed '\#pragma omp target teams distribute parallel for' 10752 /// after parsing of the associated statement. 10753 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective( 10754 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10755 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10756 /// Called on well-formed '\#pragma omp target teams distribute parallel for 10757 /// simd' after parsing of the associated statement. 10758 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 10759 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10760 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10761 /// Called on well-formed '\#pragma omp target teams distribute simd' after 10762 /// parsing of the associated statement. 10763 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective( 10764 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10765 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10766 /// Called on well-formed '\#pragma omp interop'. 10767 StmtResult ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses, 10768 SourceLocation StartLoc, 10769 SourceLocation EndLoc); 10770 /// Called on well-formed '\#pragma omp dispatch' after parsing of the 10771 // /associated statement. 10772 StmtResult ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses, 10773 Stmt *AStmt, SourceLocation StartLoc, 10774 SourceLocation EndLoc); 10775 /// Called on well-formed '\#pragma omp masked' after parsing of the 10776 // /associated statement. 10777 StmtResult ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses, 10778 Stmt *AStmt, SourceLocation StartLoc, 10779 SourceLocation EndLoc); 10780 10781 /// Checks correctness of linear modifiers. 10782 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 10783 SourceLocation LinLoc); 10784 /// Checks that the specified declaration matches requirements for the linear 10785 /// decls. 10786 bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, 10787 OpenMPLinearClauseKind LinKind, QualType Type, 10788 bool IsDeclareSimd = false); 10789 10790 /// Called on well-formed '\#pragma omp declare simd' after parsing of 10791 /// the associated method/function. 10792 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective( 10793 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, 10794 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 10795 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 10796 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR); 10797 10798 /// Checks '\#pragma omp declare variant' variant function and original 10799 /// functions after parsing of the associated method/function. 10800 /// \param DG Function declaration to which declare variant directive is 10801 /// applied to. 10802 /// \param VariantRef Expression that references the variant function, which 10803 /// must be used instead of the original one, specified in \p DG. 10804 /// \param TI The trait info object representing the match clause. 10805 /// \returns None, if the function/variant function are not compatible with 10806 /// the pragma, pair of original function/variant ref expression otherwise. 10807 Optional<std::pair<FunctionDecl *, Expr *>> 10808 checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef, 10809 OMPTraitInfo &TI, SourceRange SR); 10810 10811 /// Called on well-formed '\#pragma omp declare variant' after parsing of 10812 /// the associated method/function. 10813 /// \param FD Function declaration to which declare variant directive is 10814 /// applied to. 10815 /// \param VariantRef Expression that references the variant function, which 10816 /// must be used instead of the original one, specified in \p DG. 10817 /// \param TI The context traits associated with the function variant. 10818 void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef, 10819 OMPTraitInfo &TI, SourceRange SR); 10820 10821 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, 10822 Expr *Expr, 10823 SourceLocation StartLoc, 10824 SourceLocation LParenLoc, 10825 SourceLocation EndLoc); 10826 /// Called on well-formed 'allocator' clause. 10827 OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator, 10828 SourceLocation StartLoc, 10829 SourceLocation LParenLoc, 10830 SourceLocation EndLoc); 10831 /// Called on well-formed 'if' clause. 10832 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 10833 Expr *Condition, SourceLocation StartLoc, 10834 SourceLocation LParenLoc, 10835 SourceLocation NameModifierLoc, 10836 SourceLocation ColonLoc, 10837 SourceLocation EndLoc); 10838 /// Called on well-formed 'final' clause. 10839 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc, 10840 SourceLocation LParenLoc, 10841 SourceLocation EndLoc); 10842 /// Called on well-formed 'num_threads' clause. 10843 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads, 10844 SourceLocation StartLoc, 10845 SourceLocation LParenLoc, 10846 SourceLocation EndLoc); 10847 /// Called on well-formed 'safelen' clause. 10848 OMPClause *ActOnOpenMPSafelenClause(Expr *Length, 10849 SourceLocation StartLoc, 10850 SourceLocation LParenLoc, 10851 SourceLocation EndLoc); 10852 /// Called on well-formed 'simdlen' clause. 10853 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc, 10854 SourceLocation LParenLoc, 10855 SourceLocation EndLoc); 10856 /// Called on well-form 'sizes' clause. 10857 OMPClause *ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs, 10858 SourceLocation StartLoc, 10859 SourceLocation LParenLoc, 10860 SourceLocation EndLoc); 10861 /// Called on well-formed 'collapse' clause. 10862 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops, 10863 SourceLocation StartLoc, 10864 SourceLocation LParenLoc, 10865 SourceLocation EndLoc); 10866 /// Called on well-formed 'ordered' clause. 10867 OMPClause * 10868 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc, 10869 SourceLocation LParenLoc = SourceLocation(), 10870 Expr *NumForLoops = nullptr); 10871 /// Called on well-formed 'grainsize' clause. 10872 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc, 10873 SourceLocation LParenLoc, 10874 SourceLocation EndLoc); 10875 /// Called on well-formed 'num_tasks' clause. 10876 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc, 10877 SourceLocation LParenLoc, 10878 SourceLocation EndLoc); 10879 /// Called on well-formed 'hint' clause. 10880 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 10881 SourceLocation LParenLoc, 10882 SourceLocation EndLoc); 10883 /// Called on well-formed 'detach' clause. 10884 OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc, 10885 SourceLocation LParenLoc, 10886 SourceLocation EndLoc); 10887 10888 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind, 10889 unsigned Argument, 10890 SourceLocation ArgumentLoc, 10891 SourceLocation StartLoc, 10892 SourceLocation LParenLoc, 10893 SourceLocation EndLoc); 10894 /// Called on well-formed 'default' clause. 10895 OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind, 10896 SourceLocation KindLoc, 10897 SourceLocation StartLoc, 10898 SourceLocation LParenLoc, 10899 SourceLocation EndLoc); 10900 /// Called on well-formed 'proc_bind' clause. 10901 OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind, 10902 SourceLocation KindLoc, 10903 SourceLocation StartLoc, 10904 SourceLocation LParenLoc, 10905 SourceLocation EndLoc); 10906 /// Called on well-formed 'order' clause. 10907 OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind, 10908 SourceLocation KindLoc, 10909 SourceLocation StartLoc, 10910 SourceLocation LParenLoc, 10911 SourceLocation EndLoc); 10912 /// Called on well-formed 'update' clause. 10913 OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind, 10914 SourceLocation KindLoc, 10915 SourceLocation StartLoc, 10916 SourceLocation LParenLoc, 10917 SourceLocation EndLoc); 10918 10919 OMPClause *ActOnOpenMPSingleExprWithArgClause( 10920 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr, 10921 SourceLocation StartLoc, SourceLocation LParenLoc, 10922 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc, 10923 SourceLocation EndLoc); 10924 /// Called on well-formed 'schedule' clause. 10925 OMPClause *ActOnOpenMPScheduleClause( 10926 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 10927 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 10928 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 10929 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); 10930 10931 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc, 10932 SourceLocation EndLoc); 10933 /// Called on well-formed 'nowait' clause. 10934 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc, 10935 SourceLocation EndLoc); 10936 /// Called on well-formed 'untied' clause. 10937 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc, 10938 SourceLocation EndLoc); 10939 /// Called on well-formed 'mergeable' clause. 10940 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc, 10941 SourceLocation EndLoc); 10942 /// Called on well-formed 'read' clause. 10943 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc, 10944 SourceLocation EndLoc); 10945 /// Called on well-formed 'write' clause. 10946 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc, 10947 SourceLocation EndLoc); 10948 /// Called on well-formed 'update' clause. 10949 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc, 10950 SourceLocation EndLoc); 10951 /// Called on well-formed 'capture' clause. 10952 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc, 10953 SourceLocation EndLoc); 10954 /// Called on well-formed 'seq_cst' clause. 10955 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 10956 SourceLocation EndLoc); 10957 /// Called on well-formed 'acq_rel' clause. 10958 OMPClause *ActOnOpenMPAcqRelClause(SourceLocation StartLoc, 10959 SourceLocation EndLoc); 10960 /// Called on well-formed 'acquire' clause. 10961 OMPClause *ActOnOpenMPAcquireClause(SourceLocation StartLoc, 10962 SourceLocation EndLoc); 10963 /// Called on well-formed 'release' clause. 10964 OMPClause *ActOnOpenMPReleaseClause(SourceLocation StartLoc, 10965 SourceLocation EndLoc); 10966 /// Called on well-formed 'relaxed' clause. 10967 OMPClause *ActOnOpenMPRelaxedClause(SourceLocation StartLoc, 10968 SourceLocation EndLoc); 10969 10970 /// Called on well-formed 'init' clause. 10971 OMPClause *ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs, 10972 bool IsTarget, bool IsTargetSync, 10973 SourceLocation StartLoc, 10974 SourceLocation LParenLoc, 10975 SourceLocation VarLoc, 10976 SourceLocation EndLoc); 10977 10978 /// Called on well-formed 'use' clause. 10979 OMPClause *ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc, 10980 SourceLocation LParenLoc, 10981 SourceLocation VarLoc, SourceLocation EndLoc); 10982 10983 /// Called on well-formed 'destroy' clause. 10984 OMPClause *ActOnOpenMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc, 10985 SourceLocation LParenLoc, 10986 SourceLocation VarLoc, 10987 SourceLocation EndLoc); 10988 /// Called on well-formed 'novariants' clause. 10989 OMPClause *ActOnOpenMPNovariantsClause(Expr *Condition, 10990 SourceLocation StartLoc, 10991 SourceLocation LParenLoc, 10992 SourceLocation EndLoc); 10993 /// Called on well-formed 'nocontext' clause. 10994 OMPClause *ActOnOpenMPNocontextClause(Expr *Condition, 10995 SourceLocation StartLoc, 10996 SourceLocation LParenLoc, 10997 SourceLocation EndLoc); 10998 /// Called on well-formed 'filter' clause. 10999 OMPClause *ActOnOpenMPFilterClause(Expr *ThreadID, SourceLocation StartLoc, 11000 SourceLocation LParenLoc, 11001 SourceLocation EndLoc); 11002 /// Called on well-formed 'threads' clause. 11003 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc, 11004 SourceLocation EndLoc); 11005 /// Called on well-formed 'simd' clause. 11006 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc, 11007 SourceLocation EndLoc); 11008 /// Called on well-formed 'nogroup' clause. 11009 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc, 11010 SourceLocation EndLoc); 11011 /// Called on well-formed 'unified_address' clause. 11012 OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, 11013 SourceLocation EndLoc); 11014 11015 /// Called on well-formed 'unified_address' clause. 11016 OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, 11017 SourceLocation EndLoc); 11018 11019 /// Called on well-formed 'reverse_offload' clause. 11020 OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, 11021 SourceLocation EndLoc); 11022 11023 /// Called on well-formed 'dynamic_allocators' clause. 11024 OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, 11025 SourceLocation EndLoc); 11026 11027 /// Called on well-formed 'atomic_default_mem_order' clause. 11028 OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause( 11029 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc, 11030 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); 11031 11032 OMPClause *ActOnOpenMPVarListClause( 11033 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *DepModOrTailExpr, 11034 const OMPVarListLocTy &Locs, SourceLocation ColonLoc, 11035 CXXScopeSpec &ReductionOrMapperIdScopeSpec, 11036 DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier, 11037 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 11038 ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit, 11039 SourceLocation ExtraModifierLoc, 11040 ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 11041 ArrayRef<SourceLocation> MotionModifiersLoc); 11042 /// Called on well-formed 'inclusive' clause. 11043 OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList, 11044 SourceLocation StartLoc, 11045 SourceLocation LParenLoc, 11046 SourceLocation EndLoc); 11047 /// Called on well-formed 'exclusive' clause. 11048 OMPClause *ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList, 11049 SourceLocation StartLoc, 11050 SourceLocation LParenLoc, 11051 SourceLocation EndLoc); 11052 /// Called on well-formed 'allocate' clause. 11053 OMPClause * 11054 ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList, 11055 SourceLocation StartLoc, SourceLocation ColonLoc, 11056 SourceLocation LParenLoc, SourceLocation EndLoc); 11057 /// Called on well-formed 'private' clause. 11058 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 11059 SourceLocation StartLoc, 11060 SourceLocation LParenLoc, 11061 SourceLocation EndLoc); 11062 /// Called on well-formed 'firstprivate' clause. 11063 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 11064 SourceLocation StartLoc, 11065 SourceLocation LParenLoc, 11066 SourceLocation EndLoc); 11067 /// Called on well-formed 'lastprivate' clause. 11068 OMPClause *ActOnOpenMPLastprivateClause( 11069 ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind, 11070 SourceLocation LPKindLoc, SourceLocation ColonLoc, 11071 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); 11072 /// Called on well-formed 'shared' clause. 11073 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 11074 SourceLocation StartLoc, 11075 SourceLocation LParenLoc, 11076 SourceLocation EndLoc); 11077 /// Called on well-formed 'reduction' clause. 11078 OMPClause *ActOnOpenMPReductionClause( 11079 ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier, 11080 SourceLocation StartLoc, SourceLocation LParenLoc, 11081 SourceLocation ModifierLoc, SourceLocation ColonLoc, 11082 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, 11083 const DeclarationNameInfo &ReductionId, 11084 ArrayRef<Expr *> UnresolvedReductions = llvm::None); 11085 /// Called on well-formed 'task_reduction' clause. 11086 OMPClause *ActOnOpenMPTaskReductionClause( 11087 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 11088 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, 11089 CXXScopeSpec &ReductionIdScopeSpec, 11090 const DeclarationNameInfo &ReductionId, 11091 ArrayRef<Expr *> UnresolvedReductions = llvm::None); 11092 /// Called on well-formed 'in_reduction' clause. 11093 OMPClause *ActOnOpenMPInReductionClause( 11094 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 11095 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, 11096 CXXScopeSpec &ReductionIdScopeSpec, 11097 const DeclarationNameInfo &ReductionId, 11098 ArrayRef<Expr *> UnresolvedReductions = llvm::None); 11099 /// Called on well-formed 'linear' clause. 11100 OMPClause * 11101 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step, 11102 SourceLocation StartLoc, SourceLocation LParenLoc, 11103 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc, 11104 SourceLocation ColonLoc, SourceLocation EndLoc); 11105 /// Called on well-formed 'aligned' clause. 11106 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList, 11107 Expr *Alignment, 11108 SourceLocation StartLoc, 11109 SourceLocation LParenLoc, 11110 SourceLocation ColonLoc, 11111 SourceLocation EndLoc); 11112 /// Called on well-formed 'copyin' clause. 11113 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 11114 SourceLocation StartLoc, 11115 SourceLocation LParenLoc, 11116 SourceLocation EndLoc); 11117 /// Called on well-formed 'copyprivate' clause. 11118 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 11119 SourceLocation StartLoc, 11120 SourceLocation LParenLoc, 11121 SourceLocation EndLoc); 11122 /// Called on well-formed 'flush' pseudo clause. 11123 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 11124 SourceLocation StartLoc, 11125 SourceLocation LParenLoc, 11126 SourceLocation EndLoc); 11127 /// Called on well-formed 'depobj' pseudo clause. 11128 OMPClause *ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc, 11129 SourceLocation LParenLoc, 11130 SourceLocation EndLoc); 11131 /// Called on well-formed 'depend' clause. 11132 OMPClause * 11133 ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind, 11134 SourceLocation DepLoc, SourceLocation ColonLoc, 11135 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 11136 SourceLocation LParenLoc, SourceLocation EndLoc); 11137 /// Called on well-formed 'device' clause. 11138 OMPClause *ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier, 11139 Expr *Device, SourceLocation StartLoc, 11140 SourceLocation LParenLoc, 11141 SourceLocation ModifierLoc, 11142 SourceLocation EndLoc); 11143 /// Called on well-formed 'map' clause. 11144 OMPClause * 11145 ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 11146 ArrayRef<SourceLocation> MapTypeModifiersLoc, 11147 CXXScopeSpec &MapperIdScopeSpec, 11148 DeclarationNameInfo &MapperId, 11149 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 11150 SourceLocation MapLoc, SourceLocation ColonLoc, 11151 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, 11152 ArrayRef<Expr *> UnresolvedMappers = llvm::None); 11153 /// Called on well-formed 'num_teams' clause. 11154 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc, 11155 SourceLocation LParenLoc, 11156 SourceLocation EndLoc); 11157 /// Called on well-formed 'thread_limit' clause. 11158 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 11159 SourceLocation StartLoc, 11160 SourceLocation LParenLoc, 11161 SourceLocation EndLoc); 11162 /// Called on well-formed 'priority' clause. 11163 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc, 11164 SourceLocation LParenLoc, 11165 SourceLocation EndLoc); 11166 /// Called on well-formed 'dist_schedule' clause. 11167 OMPClause *ActOnOpenMPDistScheduleClause( 11168 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, 11169 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc, 11170 SourceLocation CommaLoc, SourceLocation EndLoc); 11171 /// Called on well-formed 'defaultmap' clause. 11172 OMPClause *ActOnOpenMPDefaultmapClause( 11173 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 11174 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 11175 SourceLocation KindLoc, SourceLocation EndLoc); 11176 /// Called on well-formed 'to' clause. 11177 OMPClause * 11178 ActOnOpenMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 11179 ArrayRef<SourceLocation> MotionModifiersLoc, 11180 CXXScopeSpec &MapperIdScopeSpec, 11181 DeclarationNameInfo &MapperId, SourceLocation ColonLoc, 11182 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, 11183 ArrayRef<Expr *> UnresolvedMappers = llvm::None); 11184 /// Called on well-formed 'from' clause. 11185 OMPClause * 11186 ActOnOpenMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 11187 ArrayRef<SourceLocation> MotionModifiersLoc, 11188 CXXScopeSpec &MapperIdScopeSpec, 11189 DeclarationNameInfo &MapperId, SourceLocation ColonLoc, 11190 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, 11191 ArrayRef<Expr *> UnresolvedMappers = llvm::None); 11192 /// Called on well-formed 'use_device_ptr' clause. 11193 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 11194 const OMPVarListLocTy &Locs); 11195 /// Called on well-formed 'use_device_addr' clause. 11196 OMPClause *ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList, 11197 const OMPVarListLocTy &Locs); 11198 /// Called on well-formed 'is_device_ptr' clause. 11199 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 11200 const OMPVarListLocTy &Locs); 11201 /// Called on well-formed 'nontemporal' clause. 11202 OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList, 11203 SourceLocation StartLoc, 11204 SourceLocation LParenLoc, 11205 SourceLocation EndLoc); 11206 11207 /// Data for list of allocators. 11208 struct UsesAllocatorsData { 11209 /// Allocator. 11210 Expr *Allocator = nullptr; 11211 /// Allocator traits. 11212 Expr *AllocatorTraits = nullptr; 11213 /// Locations of '(' and ')' symbols. 11214 SourceLocation LParenLoc, RParenLoc; 11215 }; 11216 /// Called on well-formed 'uses_allocators' clause. 11217 OMPClause *ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc, 11218 SourceLocation LParenLoc, 11219 SourceLocation EndLoc, 11220 ArrayRef<UsesAllocatorsData> Data); 11221 /// Called on well-formed 'affinity' clause. 11222 OMPClause *ActOnOpenMPAffinityClause(SourceLocation StartLoc, 11223 SourceLocation LParenLoc, 11224 SourceLocation ColonLoc, 11225 SourceLocation EndLoc, Expr *Modifier, 11226 ArrayRef<Expr *> Locators); 11227 11228 /// The kind of conversion being performed. 11229 enum CheckedConversionKind { 11230 /// An implicit conversion. 11231 CCK_ImplicitConversion, 11232 /// A C-style cast. 11233 CCK_CStyleCast, 11234 /// A functional-style cast. 11235 CCK_FunctionalCast, 11236 /// A cast other than a C-style cast. 11237 CCK_OtherCast, 11238 /// A conversion for an operand of a builtin overloaded operator. 11239 CCK_ForBuiltinOverloadedOp 11240 }; 11241 isCast(CheckedConversionKind CCK)11242 static bool isCast(CheckedConversionKind CCK) { 11243 return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast || 11244 CCK == CCK_OtherCast; 11245 } 11246 11247 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit 11248 /// cast. If there is already an implicit cast, merge into the existing one. 11249 /// If isLvalue, the result of the cast is an lvalue. 11250 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, 11251 ExprValueKind VK = VK_RValue, 11252 const CXXCastPath *BasePath = nullptr, 11253 CheckedConversionKind CCK 11254 = CCK_ImplicitConversion); 11255 11256 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding 11257 /// to the conversion from scalar type ScalarTy to the Boolean type. 11258 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); 11259 11260 /// IgnoredValueConversions - Given that an expression's result is 11261 /// syntactically ignored, perform any conversions that are 11262 /// required. 11263 ExprResult IgnoredValueConversions(Expr *E); 11264 11265 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts 11266 // functions and arrays to their respective pointers (C99 6.3.2.1). 11267 ExprResult UsualUnaryConversions(Expr *E); 11268 11269 /// CallExprUnaryConversions - a special case of an unary conversion 11270 /// performed on a function designator of a call expression. 11271 ExprResult CallExprUnaryConversions(Expr *E); 11272 11273 // DefaultFunctionArrayConversion - converts functions and arrays 11274 // to their respective pointers (C99 6.3.2.1). 11275 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true); 11276 11277 // DefaultFunctionArrayLvalueConversion - converts functions and 11278 // arrays to their respective pointers and performs the 11279 // lvalue-to-rvalue conversion. 11280 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, 11281 bool Diagnose = true); 11282 11283 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on 11284 // the operand. This function is a no-op if the operand has a function type 11285 // or an array type. 11286 ExprResult DefaultLvalueConversion(Expr *E); 11287 11288 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 11289 // do not have a prototype. Integer promotions are performed on each 11290 // argument, and arguments that have type float are promoted to double. 11291 ExprResult DefaultArgumentPromotion(Expr *E); 11292 11293 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize 11294 /// it as an xvalue. In C++98, the result will still be a prvalue, because 11295 /// we don't have xvalues there. 11296 ExprResult TemporaryMaterializationConversion(Expr *E); 11297 11298 // Used for emitting the right warning by DefaultVariadicArgumentPromotion 11299 enum VariadicCallType { 11300 VariadicFunction, 11301 VariadicBlock, 11302 VariadicMethod, 11303 VariadicConstructor, 11304 VariadicDoesNotApply 11305 }; 11306 11307 VariadicCallType getVariadicCallType(FunctionDecl *FDecl, 11308 const FunctionProtoType *Proto, 11309 Expr *Fn); 11310 11311 // Used for determining in which context a type is allowed to be passed to a 11312 // vararg function. 11313 enum VarArgKind { 11314 VAK_Valid, 11315 VAK_ValidInCXX11, 11316 VAK_Undefined, 11317 VAK_MSVCUndefined, 11318 VAK_Invalid 11319 }; 11320 11321 // Determines which VarArgKind fits an expression. 11322 VarArgKind isValidVarArgType(const QualType &Ty); 11323 11324 /// Check to see if the given expression is a valid argument to a variadic 11325 /// function, issuing a diagnostic if not. 11326 void checkVariadicArgument(const Expr *E, VariadicCallType CT); 11327 11328 /// Check whether the given statement can have musttail applied to it, 11329 /// issuing a diagnostic and returning false if not. In the success case, 11330 /// the statement is rewritten to remove implicit nodes from the return 11331 /// value. 11332 bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA); 11333 11334 private: 11335 /// Check whether the given statement can have musttail applied to it, 11336 /// issuing a diagnostic and returning false if not. 11337 bool checkMustTailAttr(const Stmt *St, const Attr &MTA); 11338 11339 public: 11340 /// Check to see if a given expression could have '.c_str()' called on it. 11341 bool hasCStrMethod(const Expr *E); 11342 11343 /// GatherArgumentsForCall - Collector argument expressions for various 11344 /// form of call prototypes. 11345 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 11346 const FunctionProtoType *Proto, 11347 unsigned FirstParam, ArrayRef<Expr *> Args, 11348 SmallVectorImpl<Expr *> &AllArgs, 11349 VariadicCallType CallType = VariadicDoesNotApply, 11350 bool AllowExplicit = false, 11351 bool IsListInitialization = false); 11352 11353 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 11354 // will create a runtime trap if the resulting type is not a POD type. 11355 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 11356 FunctionDecl *FDecl); 11357 11358 /// Context in which we're performing a usual arithmetic conversion. 11359 enum ArithConvKind { 11360 /// An arithmetic operation. 11361 ACK_Arithmetic, 11362 /// A bitwise operation. 11363 ACK_BitwiseOp, 11364 /// A comparison. 11365 ACK_Comparison, 11366 /// A conditional (?:) operator. 11367 ACK_Conditional, 11368 /// A compound assignment expression. 11369 ACK_CompAssign, 11370 }; 11371 11372 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's 11373 // operands and then handles various conversions that are common to binary 11374 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this 11375 // routine returns the first non-arithmetic type found. The client is 11376 // responsible for emitting appropriate error diagnostics. 11377 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 11378 SourceLocation Loc, ArithConvKind ACK); 11379 11380 /// AssignConvertType - All of the 'assignment' semantic checks return this 11381 /// enum to indicate whether the assignment was allowed. These checks are 11382 /// done for simple assignments, as well as initialization, return from 11383 /// function, argument passing, etc. The query is phrased in terms of a 11384 /// source and destination type. 11385 enum AssignConvertType { 11386 /// Compatible - the types are compatible according to the standard. 11387 Compatible, 11388 11389 /// PointerToInt - The assignment converts a pointer to an int, which we 11390 /// accept as an extension. 11391 PointerToInt, 11392 11393 /// IntToPointer - The assignment converts an int to a pointer, which we 11394 /// accept as an extension. 11395 IntToPointer, 11396 11397 /// FunctionVoidPointer - The assignment is between a function pointer and 11398 /// void*, which the standard doesn't allow, but we accept as an extension. 11399 FunctionVoidPointer, 11400 11401 /// IncompatiblePointer - The assignment is between two pointers types that 11402 /// are not compatible, but we accept them as an extension. 11403 IncompatiblePointer, 11404 11405 /// IncompatibleFunctionPointer - The assignment is between two function 11406 /// pointers types that are not compatible, but we accept them as an 11407 /// extension. 11408 IncompatibleFunctionPointer, 11409 11410 /// IncompatiblePointerSign - The assignment is between two pointers types 11411 /// which point to integers which have a different sign, but are otherwise 11412 /// identical. This is a subset of the above, but broken out because it's by 11413 /// far the most common case of incompatible pointers. 11414 IncompatiblePointerSign, 11415 11416 /// CompatiblePointerDiscardsQualifiers - The assignment discards 11417 /// c/v/r qualifiers, which we accept as an extension. 11418 CompatiblePointerDiscardsQualifiers, 11419 11420 /// IncompatiblePointerDiscardsQualifiers - The assignment 11421 /// discards qualifiers that we don't permit to be discarded, 11422 /// like address spaces. 11423 IncompatiblePointerDiscardsQualifiers, 11424 11425 /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment 11426 /// changes address spaces in nested pointer types which is not allowed. 11427 /// For instance, converting __private int ** to __generic int ** is 11428 /// illegal even though __private could be converted to __generic. 11429 IncompatibleNestedPointerAddressSpaceMismatch, 11430 11431 /// IncompatibleNestedPointerQualifiers - The assignment is between two 11432 /// nested pointer types, and the qualifiers other than the first two 11433 /// levels differ e.g. char ** -> const char **, but we accept them as an 11434 /// extension. 11435 IncompatibleNestedPointerQualifiers, 11436 11437 /// IncompatibleVectors - The assignment is between two vector types that 11438 /// have the same size, which we accept as an extension. 11439 IncompatibleVectors, 11440 11441 /// IntToBlockPointer - The assignment converts an int to a block 11442 /// pointer. We disallow this. 11443 IntToBlockPointer, 11444 11445 /// IncompatibleBlockPointer - The assignment is between two block 11446 /// pointers types that are not compatible. 11447 IncompatibleBlockPointer, 11448 11449 /// IncompatibleObjCQualifiedId - The assignment is between a qualified 11450 /// id type and something else (that is incompatible with it). For example, 11451 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. 11452 IncompatibleObjCQualifiedId, 11453 11454 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an 11455 /// object with __weak qualifier. 11456 IncompatibleObjCWeakRef, 11457 11458 /// Incompatible - We reject this conversion outright, it is invalid to 11459 /// represent it in the AST. 11460 Incompatible 11461 }; 11462 11463 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the 11464 /// assignment conversion type specified by ConvTy. This returns true if the 11465 /// conversion was invalid or false if the conversion was accepted. 11466 bool DiagnoseAssignmentResult(AssignConvertType ConvTy, 11467 SourceLocation Loc, 11468 QualType DstType, QualType SrcType, 11469 Expr *SrcExpr, AssignmentAction Action, 11470 bool *Complained = nullptr); 11471 11472 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag 11473 /// enum. If AllowMask is true, then we also allow the complement of a valid 11474 /// value, to be used as a mask. 11475 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 11476 bool AllowMask) const; 11477 11478 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant 11479 /// integer not in the range of enum values. 11480 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, 11481 Expr *SrcExpr); 11482 11483 /// CheckAssignmentConstraints - Perform type checking for assignment, 11484 /// argument passing, variable initialization, and function return values. 11485 /// C99 6.5.16. 11486 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, 11487 QualType LHSType, 11488 QualType RHSType); 11489 11490 /// Check assignment constraints and optionally prepare for a conversion of 11491 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS 11492 /// is true. 11493 AssignConvertType CheckAssignmentConstraints(QualType LHSType, 11494 ExprResult &RHS, 11495 CastKind &Kind, 11496 bool ConvertRHS = true); 11497 11498 /// Check assignment constraints for an assignment of RHS to LHSType. 11499 /// 11500 /// \param LHSType The destination type for the assignment. 11501 /// \param RHS The source expression for the assignment. 11502 /// \param Diagnose If \c true, diagnostics may be produced when checking 11503 /// for assignability. If a diagnostic is produced, \p RHS will be 11504 /// set to ExprError(). Note that this function may still return 11505 /// without producing a diagnostic, even for an invalid assignment. 11506 /// \param DiagnoseCFAudited If \c true, the target is a function parameter 11507 /// in an audited Core Foundation API and does not need to be checked 11508 /// for ARC retain issues. 11509 /// \param ConvertRHS If \c true, \p RHS will be updated to model the 11510 /// conversions necessary to perform the assignment. If \c false, 11511 /// \p Diagnose must also be \c false. 11512 AssignConvertType CheckSingleAssignmentConstraints( 11513 QualType LHSType, ExprResult &RHS, bool Diagnose = true, 11514 bool DiagnoseCFAudited = false, bool ConvertRHS = true); 11515 11516 // If the lhs type is a transparent union, check whether we 11517 // can initialize the transparent union with the given expression. 11518 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, 11519 ExprResult &RHS); 11520 11521 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); 11522 11523 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); 11524 11525 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 11526 AssignmentAction Action, 11527 bool AllowExplicit = false); 11528 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 11529 const ImplicitConversionSequence& ICS, 11530 AssignmentAction Action, 11531 CheckedConversionKind CCK 11532 = CCK_ImplicitConversion); 11533 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 11534 const StandardConversionSequence& SCS, 11535 AssignmentAction Action, 11536 CheckedConversionKind CCK); 11537 11538 ExprResult PerformQualificationConversion( 11539 Expr *E, QualType Ty, ExprValueKind VK = VK_RValue, 11540 CheckedConversionKind CCK = CCK_ImplicitConversion); 11541 11542 /// the following "Check" methods will return a valid/converted QualType 11543 /// or a null QualType (indicating an error diagnostic was issued). 11544 11545 /// type checking binary operators (subroutines of CreateBuiltinBinOp). 11546 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, 11547 ExprResult &RHS); 11548 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 11549 ExprResult &RHS); 11550 QualType CheckPointerToMemberOperands( // C++ 5.5 11551 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, 11552 SourceLocation OpLoc, bool isIndirect); 11553 QualType CheckMultiplyDivideOperands( // C99 6.5.5 11554 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, 11555 bool IsDivide); 11556 QualType CheckRemainderOperands( // C99 6.5.5 11557 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11558 bool IsCompAssign = false); 11559 QualType CheckAdditionOperands( // C99 6.5.6 11560 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11561 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr); 11562 QualType CheckSubtractionOperands( // C99 6.5.6 11563 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11564 QualType* CompLHSTy = nullptr); 11565 QualType CheckShiftOperands( // C99 6.5.7 11566 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11567 BinaryOperatorKind Opc, bool IsCompAssign = false); 11568 void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE); 11569 QualType CheckCompareOperands( // C99 6.5.8/9 11570 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11571 BinaryOperatorKind Opc); 11572 QualType CheckBitwiseOperands( // C99 6.5.[10...12] 11573 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11574 BinaryOperatorKind Opc); 11575 QualType CheckLogicalOperands( // C99 6.5.[13,14] 11576 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11577 BinaryOperatorKind Opc); 11578 // CheckAssignmentOperands is used for both simple and compound assignment. 11579 // For simple assignment, pass both expressions and a null converted type. 11580 // For compound assignment, pass both expressions and the converted type. 11581 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] 11582 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); 11583 11584 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, 11585 UnaryOperatorKind Opcode, Expr *Op); 11586 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, 11587 BinaryOperatorKind Opcode, 11588 Expr *LHS, Expr *RHS); 11589 ExprResult checkPseudoObjectRValue(Expr *E); 11590 Expr *recreateSyntacticForm(PseudoObjectExpr *E); 11591 11592 QualType CheckConditionalOperands( // C99 6.5.15 11593 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, 11594 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); 11595 QualType CXXCheckConditionalOperands( // C++ 5.16 11596 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, 11597 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); 11598 QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, 11599 ExprResult &RHS, 11600 SourceLocation QuestionLoc); 11601 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, 11602 bool ConvertArgs = true); 11603 QualType FindCompositePointerType(SourceLocation Loc, 11604 ExprResult &E1, ExprResult &E2, 11605 bool ConvertArgs = true) { 11606 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get(); 11607 QualType Composite = 11608 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs); 11609 E1 = E1Tmp; 11610 E2 = E2Tmp; 11611 return Composite; 11612 } 11613 11614 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 11615 SourceLocation QuestionLoc); 11616 11617 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 11618 SourceLocation QuestionLoc); 11619 11620 void DiagnoseAlwaysNonNullPointer(Expr *E, 11621 Expr::NullPointerConstantKind NullType, 11622 bool IsEqual, SourceRange Range); 11623 11624 /// type checking for vector binary operators. 11625 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 11626 SourceLocation Loc, bool IsCompAssign, 11627 bool AllowBothBool, bool AllowBoolConversion); 11628 QualType GetSignedVectorType(QualType V); 11629 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11630 SourceLocation Loc, 11631 BinaryOperatorKind Opc); 11632 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11633 SourceLocation Loc); 11634 11635 /// Type checking for matrix binary operators. 11636 QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 11637 SourceLocation Loc, 11638 bool IsCompAssign); 11639 QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 11640 SourceLocation Loc, bool IsCompAssign); 11641 11642 bool isValidSveBitcast(QualType srcType, QualType destType); 11643 11644 bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy); 11645 11646 bool areVectorTypesSameSize(QualType srcType, QualType destType); 11647 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType); 11648 bool isLaxVectorConversion(QualType srcType, QualType destType); 11649 11650 /// type checking declaration initializers (C99 6.7.8) 11651 bool CheckForConstantInitializer(Expr *e, QualType t); 11652 11653 // type checking C++ declaration initializers (C++ [dcl.init]). 11654 11655 /// ReferenceCompareResult - Expresses the result of comparing two 11656 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the 11657 /// purposes of initialization by reference (C++ [dcl.init.ref]p4). 11658 enum ReferenceCompareResult { 11659 /// Ref_Incompatible - The two types are incompatible, so direct 11660 /// reference binding is not possible. 11661 Ref_Incompatible = 0, 11662 /// Ref_Related - The two types are reference-related, which means 11663 /// that their unqualified forms (T1 and T2) are either the same 11664 /// or T1 is a base class of T2. 11665 Ref_Related, 11666 /// Ref_Compatible - The two types are reference-compatible. 11667 Ref_Compatible 11668 }; 11669 11670 // Fake up a scoped enumeration that still contextually converts to bool. 11671 struct ReferenceConversionsScope { 11672 /// The conversions that would be performed on an lvalue of type T2 when 11673 /// binding a reference of type T1 to it, as determined when evaluating 11674 /// whether T1 is reference-compatible with T2. 11675 enum ReferenceConversions { 11676 Qualification = 0x1, 11677 NestedQualification = 0x2, 11678 Function = 0x4, 11679 DerivedToBase = 0x8, 11680 ObjC = 0x10, 11681 ObjCLifetime = 0x20, 11682 11683 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime) 11684 }; 11685 }; 11686 using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions; 11687 11688 ReferenceCompareResult 11689 CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, 11690 ReferenceConversions *Conv = nullptr); 11691 11692 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 11693 Expr *CastExpr, CastKind &CastKind, 11694 ExprValueKind &VK, CXXCastPath &Path); 11695 11696 /// Force an expression with unknown-type to an expression of the 11697 /// given type. 11698 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); 11699 11700 /// Type-check an expression that's being passed to an 11701 /// __unknown_anytype parameter. 11702 ExprResult checkUnknownAnyArg(SourceLocation callLoc, 11703 Expr *result, QualType ¶mType); 11704 11705 // CheckMatrixCast - Check type constraints for matrix casts. 11706 // We allow casting between matrixes of the same dimensions i.e. when they 11707 // have the same number of rows and column. Returns true if the cast is 11708 // invalid. 11709 bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 11710 CastKind &Kind); 11711 11712 // CheckVectorCast - check type constraints for vectors. 11713 // Since vectors are an extension, there are no C standard reference for this. 11714 // We allow casting between vectors and integer datatypes of the same size. 11715 // returns true if the cast is invalid 11716 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 11717 CastKind &Kind); 11718 11719 /// Prepare `SplattedExpr` for a vector splat operation, adding 11720 /// implicit casts if necessary. 11721 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr); 11722 11723 // CheckExtVectorCast - check type constraints for extended vectors. 11724 // Since vectors are an extension, there are no C standard reference for this. 11725 // We allow casting between vectors and integer datatypes of the same size, 11726 // or vectors and the element type of that vector. 11727 // returns the cast expr 11728 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, 11729 CastKind &Kind); 11730 11731 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, 11732 SourceLocation LParenLoc, 11733 Expr *CastExpr, 11734 SourceLocation RParenLoc); 11735 11736 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error }; 11737 11738 /// Checks for invalid conversions and casts between 11739 /// retainable pointers and other pointer kinds for ARC and Weak. 11740 ARCConversionResult CheckObjCConversion(SourceRange castRange, 11741 QualType castType, Expr *&op, 11742 CheckedConversionKind CCK, 11743 bool Diagnose = true, 11744 bool DiagnoseCFAudited = false, 11745 BinaryOperatorKind Opc = BO_PtrMemD 11746 ); 11747 11748 Expr *stripARCUnbridgedCast(Expr *e); 11749 void diagnoseARCUnbridgedCast(Expr *e); 11750 11751 bool CheckObjCARCUnavailableWeakConversion(QualType castType, 11752 QualType ExprType); 11753 11754 /// checkRetainCycles - Check whether an Objective-C message send 11755 /// might create an obvious retain cycle. 11756 void checkRetainCycles(ObjCMessageExpr *msg); 11757 void checkRetainCycles(Expr *receiver, Expr *argument); 11758 void checkRetainCycles(VarDecl *Var, Expr *Init); 11759 11760 /// checkUnsafeAssigns - Check whether +1 expr is being assigned 11761 /// to weak/__unsafe_unretained type. 11762 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); 11763 11764 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned 11765 /// to weak/__unsafe_unretained expression. 11766 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); 11767 11768 /// CheckMessageArgumentTypes - Check types in an Obj-C message send. 11769 /// \param Method - May be null. 11770 /// \param [out] ReturnType - The return type of the send. 11771 /// \return true iff there were any incompatible types. 11772 bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType, 11773 MultiExprArg Args, Selector Sel, 11774 ArrayRef<SourceLocation> SelectorLocs, 11775 ObjCMethodDecl *Method, bool isClassMessage, 11776 bool isSuperMessage, SourceLocation lbrac, 11777 SourceLocation rbrac, SourceRange RecRange, 11778 QualType &ReturnType, ExprValueKind &VK); 11779 11780 /// Determine the result of a message send expression based on 11781 /// the type of the receiver, the method expected to receive the message, 11782 /// and the form of the message send. 11783 QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType, 11784 ObjCMethodDecl *Method, bool isClassMessage, 11785 bool isSuperMessage); 11786 11787 /// If the given expression involves a message send to a method 11788 /// with a related result type, emit a note describing what happened. 11789 void EmitRelatedResultTypeNote(const Expr *E); 11790 11791 /// Given that we had incompatible pointer types in a return 11792 /// statement, check whether we're in a method with a related result 11793 /// type, and if so, emit a note describing what happened. 11794 void EmitRelatedResultTypeNoteForReturn(QualType destType); 11795 11796 class ConditionResult { 11797 Decl *ConditionVar; 11798 FullExprArg Condition; 11799 bool Invalid; 11800 bool HasKnownValue; 11801 bool KnownValue; 11802 11803 friend class Sema; ConditionResult(Sema & S,Decl * ConditionVar,FullExprArg Condition,bool IsConstexpr)11804 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition, 11805 bool IsConstexpr) 11806 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false), 11807 HasKnownValue(IsConstexpr && Condition.get() && 11808 !Condition.get()->isValueDependent()), 11809 KnownValue(HasKnownValue && 11810 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {} ConditionResult(bool Invalid)11811 explicit ConditionResult(bool Invalid) 11812 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid), 11813 HasKnownValue(false), KnownValue(false) {} 11814 11815 public: ConditionResult()11816 ConditionResult() : ConditionResult(false) {} isInvalid()11817 bool isInvalid() const { return Invalid; } get()11818 std::pair<VarDecl *, Expr *> get() const { 11819 return std::make_pair(cast_or_null<VarDecl>(ConditionVar), 11820 Condition.get()); 11821 } getKnownValue()11822 llvm::Optional<bool> getKnownValue() const { 11823 if (!HasKnownValue) 11824 return None; 11825 return KnownValue; 11826 } 11827 }; ConditionError()11828 static ConditionResult ConditionError() { return ConditionResult(true); } 11829 11830 enum class ConditionKind { 11831 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'. 11832 ConstexprIf, ///< A constant boolean condition from 'if constexpr'. 11833 Switch ///< An integral condition for a 'switch' statement. 11834 }; 11835 11836 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, 11837 Expr *SubExpr, ConditionKind CK); 11838 11839 ConditionResult ActOnConditionVariable(Decl *ConditionVar, 11840 SourceLocation StmtLoc, 11841 ConditionKind CK); 11842 11843 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); 11844 11845 ExprResult CheckConditionVariable(VarDecl *ConditionVar, 11846 SourceLocation StmtLoc, 11847 ConditionKind CK); 11848 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond); 11849 11850 /// CheckBooleanCondition - Diagnose problems involving the use of 11851 /// the given expression as a boolean condition (e.g. in an if 11852 /// statement). Also performs the standard function and array 11853 /// decays, possibly changing the input variable. 11854 /// 11855 /// \param Loc - A location associated with the condition, e.g. the 11856 /// 'if' keyword. 11857 /// \return true iff there were any errors 11858 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, 11859 bool IsConstexpr = false); 11860 11861 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression 11862 /// found in an explicit(bool) specifier. 11863 ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E); 11864 11865 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier. 11866 /// Returns true if the explicit specifier is now resolved. 11867 bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec); 11868 11869 /// DiagnoseAssignmentAsCondition - Given that an expression is 11870 /// being used as a boolean condition, warn if it's an assignment. 11871 void DiagnoseAssignmentAsCondition(Expr *E); 11872 11873 /// Redundant parentheses over an equality comparison can indicate 11874 /// that the user intended an assignment used as condition. 11875 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); 11876 11877 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. 11878 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false); 11879 11880 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 11881 /// the specified width and sign. If an overflow occurs, detect it and emit 11882 /// the specified diagnostic. 11883 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, 11884 unsigned NewWidth, bool NewSign, 11885 SourceLocation Loc, unsigned DiagID); 11886 11887 /// Checks that the Objective-C declaration is declared in the global scope. 11888 /// Emits an error and marks the declaration as invalid if it's not declared 11889 /// in the global scope. 11890 bool CheckObjCDeclScope(Decl *D); 11891 11892 /// Abstract base class used for diagnosing integer constant 11893 /// expression violations. 11894 class VerifyICEDiagnoser { 11895 public: 11896 bool Suppress; 11897 Suppress(Suppress)11898 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } 11899 11900 virtual SemaDiagnosticBuilder 11901 diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T); 11902 virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 11903 SourceLocation Loc) = 0; 11904 virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc); ~VerifyICEDiagnoser()11905 virtual ~VerifyICEDiagnoser() {} 11906 }; 11907 11908 enum AllowFoldKind { 11909 NoFold, 11910 AllowFold, 11911 }; 11912 11913 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, 11914 /// and reports the appropriate diagnostics. Returns false on success. 11915 /// Can optionally return the value of the expression. 11916 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 11917 VerifyICEDiagnoser &Diagnoser, 11918 AllowFoldKind CanFold = NoFold); 11919 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 11920 unsigned DiagID, 11921 AllowFoldKind CanFold = NoFold); 11922 ExprResult VerifyIntegerConstantExpression(Expr *E, 11923 llvm::APSInt *Result = nullptr, 11924 AllowFoldKind CanFold = NoFold); 11925 ExprResult VerifyIntegerConstantExpression(Expr *E, 11926 AllowFoldKind CanFold = NoFold) { 11927 return VerifyIntegerConstantExpression(E, nullptr, CanFold); 11928 } 11929 11930 /// VerifyBitField - verifies that a bit field expression is an ICE and has 11931 /// the correct width, and that the field type is valid. 11932 /// Returns false on success. 11933 /// Can optionally return whether the bit-field is of width 0 11934 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 11935 QualType FieldTy, bool IsMsStruct, 11936 Expr *BitWidth, bool *ZeroWidth = nullptr); 11937 11938 private: 11939 unsigned ForceCUDAHostDeviceDepth = 0; 11940 11941 public: 11942 /// Increments our count of the number of times we've seen a pragma forcing 11943 /// functions to be __host__ __device__. So long as this count is greater 11944 /// than zero, all functions encountered will be __host__ __device__. 11945 void PushForceCUDAHostDevice(); 11946 11947 /// Decrements our count of the number of times we've seen a pragma forcing 11948 /// functions to be __host__ __device__. Returns false if the count is 0 11949 /// before incrementing, so you can emit an error. 11950 bool PopForceCUDAHostDevice(); 11951 11952 /// Diagnostics that are emitted only if we discover that the given function 11953 /// must be codegen'ed. Because handling these correctly adds overhead to 11954 /// compilation, this is currently only enabled for CUDA compilations. 11955 llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>, 11956 std::vector<PartialDiagnosticAt>> 11957 DeviceDeferredDiags; 11958 11959 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the 11960 /// key in a hashtable, both the FD and location are hashed. 11961 struct FunctionDeclAndLoc { 11962 CanonicalDeclPtr<FunctionDecl> FD; 11963 SourceLocation Loc; 11964 }; 11965 11966 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a 11967 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the 11968 /// same deferred diag twice. 11969 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags; 11970 11971 /// An inverse call graph, mapping known-emitted functions to one of their 11972 /// known-emitted callers (plus the location of the call). 11973 /// 11974 /// Functions that we can tell a priori must be emitted aren't added to this 11975 /// map. 11976 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>, 11977 /* Caller = */ FunctionDeclAndLoc> 11978 DeviceKnownEmittedFns; 11979 11980 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current 11981 /// context is "used as device code". 11982 /// 11983 /// - If CurContext is a __host__ function, does not emit any diagnostics 11984 /// unless \p EmitOnBothSides is true. 11985 /// - If CurContext is a __device__ or __global__ function, emits the 11986 /// diagnostics immediately. 11987 /// - If CurContext is a __host__ __device__ function and we are compiling for 11988 /// the device, creates a diagnostic which is emitted if and when we realize 11989 /// that the function will be codegen'ed. 11990 /// 11991 /// Example usage: 11992 /// 11993 /// // Variable-length arrays are not allowed in CUDA device code. 11994 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget()) 11995 /// return ExprError(); 11996 /// // Otherwise, continue parsing as normal. 11997 SemaDiagnosticBuilder CUDADiagIfDeviceCode(SourceLocation Loc, 11998 unsigned DiagID); 11999 12000 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current 12001 /// context is "used as host code". 12002 /// 12003 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched. 12004 SemaDiagnosticBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID); 12005 12006 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current 12007 /// context is "used as device code". 12008 /// 12009 /// - If CurContext is a `declare target` function or it is known that the 12010 /// function is emitted for the device, emits the diagnostics immediately. 12011 /// - If CurContext is a non-`declare target` function and we are compiling 12012 /// for the device, creates a diagnostic which is emitted if and when we 12013 /// realize that the function will be codegen'ed. 12014 /// 12015 /// Example usage: 12016 /// 12017 /// // Variable-length arrays are not allowed in NVPTX device code. 12018 /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported)) 12019 /// return ExprError(); 12020 /// // Otherwise, continue parsing as normal. 12021 SemaDiagnosticBuilder 12022 diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD); 12023 12024 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current 12025 /// context is "used as host code". 12026 /// 12027 /// - If CurContext is a `declare target` function or it is known that the 12028 /// function is emitted for the host, emits the diagnostics immediately. 12029 /// - If CurContext is a non-host function, just ignore it. 12030 /// 12031 /// Example usage: 12032 /// 12033 /// // Variable-length arrays are not allowed in NVPTX device code. 12034 /// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported)) 12035 /// return ExprError(); 12036 /// // Otherwise, continue parsing as normal. 12037 SemaDiagnosticBuilder diagIfOpenMPHostCode(SourceLocation Loc, 12038 unsigned DiagID, FunctionDecl *FD); 12039 12040 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, 12041 FunctionDecl *FD = nullptr); 12042 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, 12043 const PartialDiagnostic &PD, 12044 FunctionDecl *FD = nullptr) { 12045 return targetDiag(Loc, PD.getDiagID(), FD) << PD; 12046 } 12047 12048 /// Check if the expression is allowed to be used in expressions for the 12049 /// offloading devices. 12050 void checkDeviceDecl(ValueDecl *D, SourceLocation Loc); 12051 12052 enum CUDAFunctionTarget { 12053 CFT_Device, 12054 CFT_Global, 12055 CFT_Host, 12056 CFT_HostDevice, 12057 CFT_InvalidTarget 12058 }; 12059 12060 /// Determines whether the given function is a CUDA device/host/kernel/etc. 12061 /// function. 12062 /// 12063 /// Use this rather than examining the function's attributes yourself -- you 12064 /// will get it wrong. Returns CFT_Host if D is null. 12065 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D, 12066 bool IgnoreImplicitHDAttr = false); 12067 CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs); 12068 12069 enum CUDAVariableTarget { 12070 CVT_Device, /// Emitted on device side with a shadow variable on host side 12071 CVT_Host, /// Emitted on host side only 12072 CVT_Both, /// Emitted on both sides with different addresses 12073 CVT_Unified, /// Emitted as a unified address, e.g. managed variables 12074 }; 12075 /// Determines whether the given variable is emitted on host or device side. 12076 CUDAVariableTarget IdentifyCUDATarget(const VarDecl *D); 12077 12078 /// Gets the CUDA target for the current context. CurrentCUDATarget()12079 CUDAFunctionTarget CurrentCUDATarget() { 12080 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext)); 12081 } 12082 12083 static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D); 12084 12085 // CUDA function call preference. Must be ordered numerically from 12086 // worst to best. 12087 enum CUDAFunctionPreference { 12088 CFP_Never, // Invalid caller/callee combination. 12089 CFP_WrongSide, // Calls from host-device to host or device 12090 // function that do not match current compilation 12091 // mode. 12092 CFP_HostDevice, // Any calls to host/device functions. 12093 CFP_SameSide, // Calls from host-device to host or device 12094 // function matching current compilation mode. 12095 CFP_Native, // host-to-host or device-to-device calls. 12096 }; 12097 12098 /// Identifies relative preference of a given Caller/Callee 12099 /// combination, based on their host/device attributes. 12100 /// \param Caller function which needs address of \p Callee. 12101 /// nullptr in case of global context. 12102 /// \param Callee target function 12103 /// 12104 /// \returns preference value for particular Caller/Callee combination. 12105 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller, 12106 const FunctionDecl *Callee); 12107 12108 /// Determines whether Caller may invoke Callee, based on their CUDA 12109 /// host/device attributes. Returns false if the call is not allowed. 12110 /// 12111 /// Note: Will return true for CFP_WrongSide calls. These may appear in 12112 /// semantically correct CUDA programs, but only if they're never codegen'ed. IsAllowedCUDACall(const FunctionDecl * Caller,const FunctionDecl * Callee)12113 bool IsAllowedCUDACall(const FunctionDecl *Caller, 12114 const FunctionDecl *Callee) { 12115 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never; 12116 } 12117 12118 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, 12119 /// depending on FD and the current compilation settings. 12120 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD, 12121 const LookupResult &Previous); 12122 12123 /// May add implicit CUDAConstantAttr attribute to VD, depending on VD 12124 /// and current compilation settings. 12125 void MaybeAddCUDAConstantAttr(VarDecl *VD); 12126 12127 public: 12128 /// Check whether we're allowed to call Callee from the current context. 12129 /// 12130 /// - If the call is never allowed in a semantically-correct program 12131 /// (CFP_Never), emits an error and returns false. 12132 /// 12133 /// - If the call is allowed in semantically-correct programs, but only if 12134 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to 12135 /// be emitted if and when the caller is codegen'ed, and returns true. 12136 /// 12137 /// Will only create deferred diagnostics for a given SourceLocation once, 12138 /// so you can safely call this multiple times without generating duplicate 12139 /// deferred errors. 12140 /// 12141 /// - Otherwise, returns true without emitting any diagnostics. 12142 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee); 12143 12144 void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture); 12145 12146 /// Set __device__ or __host__ __device__ attributes on the given lambda 12147 /// operator() method. 12148 /// 12149 /// CUDA lambdas by default is host device function unless it has explicit 12150 /// host or device attribute. 12151 void CUDASetLambdaAttrs(CXXMethodDecl *Method); 12152 12153 /// Finds a function in \p Matches with highest calling priority 12154 /// from \p Caller context and erases all functions with lower 12155 /// calling priority. 12156 void EraseUnwantedCUDAMatches( 12157 const FunctionDecl *Caller, 12158 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches); 12159 12160 /// Given a implicit special member, infer its CUDA target from the 12161 /// calls it needs to make to underlying base/field special members. 12162 /// \param ClassDecl the class for which the member is being created. 12163 /// \param CSM the kind of special member. 12164 /// \param MemberDecl the special member itself. 12165 /// \param ConstRHS true if this is a copy operation with a const object on 12166 /// its RHS. 12167 /// \param Diagnose true if this call should emit diagnostics. 12168 /// \return true if there was an error inferring. 12169 /// The result of this call is implicit CUDA target attribute(s) attached to 12170 /// the member declaration. 12171 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, 12172 CXXSpecialMember CSM, 12173 CXXMethodDecl *MemberDecl, 12174 bool ConstRHS, 12175 bool Diagnose); 12176 12177 /// \return true if \p CD can be considered empty according to CUDA 12178 /// (E.2.3.1 in CUDA 7.5 Programming guide). 12179 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD); 12180 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD); 12181 12182 // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In 12183 // case of error emits appropriate diagnostic and invalidates \p Var. 12184 // 12185 // \details CUDA allows only empty constructors as initializers for global 12186 // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all 12187 // __shared__ variables whether they are local or not (they all are implicitly 12188 // static in CUDA). One exception is that CUDA allows constant initializers 12189 // for __constant__ and __device__ variables. 12190 void checkAllowedCUDAInitializer(VarDecl *VD); 12191 12192 /// Check whether NewFD is a valid overload for CUDA. Emits 12193 /// diagnostics and invalidates NewFD if not. 12194 void checkCUDATargetOverload(FunctionDecl *NewFD, 12195 const LookupResult &Previous); 12196 /// Copies target attributes from the template TD to the function FD. 12197 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD); 12198 12199 /// Returns the name of the launch configuration function. This is the name 12200 /// of the function that will be called to configure kernel call, with the 12201 /// parameters specified via <<<>>>. 12202 std::string getCudaConfigureFuncName() const; 12203 12204 /// \name Code completion 12205 //@{ 12206 /// Describes the context in which code completion occurs. 12207 enum ParserCompletionContext { 12208 /// Code completion occurs at top-level or namespace context. 12209 PCC_Namespace, 12210 /// Code completion occurs within a class, struct, or union. 12211 PCC_Class, 12212 /// Code completion occurs within an Objective-C interface, protocol, 12213 /// or category. 12214 PCC_ObjCInterface, 12215 /// Code completion occurs within an Objective-C implementation or 12216 /// category implementation 12217 PCC_ObjCImplementation, 12218 /// Code completion occurs within the list of instance variables 12219 /// in an Objective-C interface, protocol, category, or implementation. 12220 PCC_ObjCInstanceVariableList, 12221 /// Code completion occurs following one or more template 12222 /// headers. 12223 PCC_Template, 12224 /// Code completion occurs following one or more template 12225 /// headers within a class. 12226 PCC_MemberTemplate, 12227 /// Code completion occurs within an expression. 12228 PCC_Expression, 12229 /// Code completion occurs within a statement, which may 12230 /// also be an expression or a declaration. 12231 PCC_Statement, 12232 /// Code completion occurs at the beginning of the 12233 /// initialization statement (or expression) in a for loop. 12234 PCC_ForInit, 12235 /// Code completion occurs within the condition of an if, 12236 /// while, switch, or for statement. 12237 PCC_Condition, 12238 /// Code completion occurs within the body of a function on a 12239 /// recovery path, where we do not have a specific handle on our position 12240 /// in the grammar. 12241 PCC_RecoveryInFunction, 12242 /// Code completion occurs where only a type is permitted. 12243 PCC_Type, 12244 /// Code completion occurs in a parenthesized expression, which 12245 /// might also be a type cast. 12246 PCC_ParenthesizedExpression, 12247 /// Code completion occurs within a sequence of declaration 12248 /// specifiers within a function, method, or block. 12249 PCC_LocalDeclarationSpecifiers 12250 }; 12251 12252 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); 12253 void CodeCompleteOrdinaryName(Scope *S, 12254 ParserCompletionContext CompletionContext); 12255 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, 12256 bool AllowNonIdentifiers, 12257 bool AllowNestedNameSpecifiers); 12258 12259 struct CodeCompleteExpressionData; 12260 void CodeCompleteExpression(Scope *S, 12261 const CodeCompleteExpressionData &Data); 12262 void CodeCompleteExpression(Scope *S, QualType PreferredType, 12263 bool IsParenthesized = false); 12264 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase, 12265 SourceLocation OpLoc, bool IsArrow, 12266 bool IsBaseExprStatement, 12267 QualType PreferredType); 12268 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS, 12269 QualType PreferredType); 12270 void CodeCompleteTag(Scope *S, unsigned TagSpec); 12271 void CodeCompleteTypeQualifiers(DeclSpec &DS); 12272 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, 12273 const VirtSpecifiers *VS = nullptr); 12274 void CodeCompleteBracketDeclarator(Scope *S); 12275 void CodeCompleteCase(Scope *S); 12276 /// Determines the preferred type of the current function argument, by 12277 /// examining the signatures of all possible overloads. 12278 /// Returns null if unknown or ambiguous, or if code completion is off. 12279 /// 12280 /// If the code completion point has been reached, also reports the function 12281 /// signatures that were considered. 12282 /// 12283 /// FIXME: rename to GuessCallArgumentType to reduce confusion. 12284 QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args, 12285 SourceLocation OpenParLoc); 12286 QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type, 12287 SourceLocation Loc, 12288 ArrayRef<Expr *> Args, 12289 SourceLocation OpenParLoc); 12290 QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl, 12291 CXXScopeSpec SS, 12292 ParsedType TemplateTypeTy, 12293 ArrayRef<Expr *> ArgExprs, 12294 IdentifierInfo *II, 12295 SourceLocation OpenParLoc); 12296 void CodeCompleteInitializer(Scope *S, Decl *D); 12297 /// Trigger code completion for a record of \p BaseType. \p InitExprs are 12298 /// expressions in the initializer list seen so far and \p D is the current 12299 /// Designation being parsed. 12300 void CodeCompleteDesignator(const QualType BaseType, 12301 llvm::ArrayRef<Expr *> InitExprs, 12302 const Designation &D); 12303 void CodeCompleteAfterIf(Scope *S, bool IsBracedThen); 12304 12305 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext, 12306 bool IsUsingDeclaration, QualType BaseType, 12307 QualType PreferredType); 12308 void CodeCompleteUsing(Scope *S); 12309 void CodeCompleteUsingDirective(Scope *S); 12310 void CodeCompleteNamespaceDecl(Scope *S); 12311 void CodeCompleteNamespaceAliasDecl(Scope *S); 12312 void CodeCompleteOperatorName(Scope *S); 12313 void CodeCompleteConstructorInitializer( 12314 Decl *Constructor, 12315 ArrayRef<CXXCtorInitializer *> Initializers); 12316 12317 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, 12318 bool AfterAmpersand); 12319 void CodeCompleteAfterFunctionEquals(Declarator &D); 12320 12321 void CodeCompleteObjCAtDirective(Scope *S); 12322 void CodeCompleteObjCAtVisibility(Scope *S); 12323 void CodeCompleteObjCAtStatement(Scope *S); 12324 void CodeCompleteObjCAtExpression(Scope *S); 12325 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); 12326 void CodeCompleteObjCPropertyGetter(Scope *S); 12327 void CodeCompleteObjCPropertySetter(Scope *S); 12328 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, 12329 bool IsParameter); 12330 void CodeCompleteObjCMessageReceiver(Scope *S); 12331 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, 12332 ArrayRef<IdentifierInfo *> SelIdents, 12333 bool AtArgumentExpression); 12334 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, 12335 ArrayRef<IdentifierInfo *> SelIdents, 12336 bool AtArgumentExpression, 12337 bool IsSuper = false); 12338 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, 12339 ArrayRef<IdentifierInfo *> SelIdents, 12340 bool AtArgumentExpression, 12341 ObjCInterfaceDecl *Super = nullptr); 12342 void CodeCompleteObjCForCollection(Scope *S, 12343 DeclGroupPtrTy IterationVar); 12344 void CodeCompleteObjCSelector(Scope *S, 12345 ArrayRef<IdentifierInfo *> SelIdents); 12346 void CodeCompleteObjCProtocolReferences( 12347 ArrayRef<IdentifierLocPair> Protocols); 12348 void CodeCompleteObjCProtocolDecl(Scope *S); 12349 void CodeCompleteObjCInterfaceDecl(Scope *S); 12350 void CodeCompleteObjCSuperclass(Scope *S, 12351 IdentifierInfo *ClassName, 12352 SourceLocation ClassNameLoc); 12353 void CodeCompleteObjCImplementationDecl(Scope *S); 12354 void CodeCompleteObjCInterfaceCategory(Scope *S, 12355 IdentifierInfo *ClassName, 12356 SourceLocation ClassNameLoc); 12357 void CodeCompleteObjCImplementationCategory(Scope *S, 12358 IdentifierInfo *ClassName, 12359 SourceLocation ClassNameLoc); 12360 void CodeCompleteObjCPropertyDefinition(Scope *S); 12361 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, 12362 IdentifierInfo *PropertyName); 12363 void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, 12364 ParsedType ReturnType); 12365 void CodeCompleteObjCMethodDeclSelector(Scope *S, 12366 bool IsInstanceMethod, 12367 bool AtParameterName, 12368 ParsedType ReturnType, 12369 ArrayRef<IdentifierInfo *> SelIdents); 12370 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName, 12371 SourceLocation ClassNameLoc, 12372 bool IsBaseExprStatement); 12373 void CodeCompletePreprocessorDirective(bool InConditional); 12374 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); 12375 void CodeCompletePreprocessorMacroName(bool IsDefinition); 12376 void CodeCompletePreprocessorExpression(); 12377 void CodeCompletePreprocessorMacroArgument(Scope *S, 12378 IdentifierInfo *Macro, 12379 MacroInfo *MacroInfo, 12380 unsigned Argument); 12381 void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled); 12382 void CodeCompleteNaturalLanguage(); 12383 void CodeCompleteAvailabilityPlatformName(); 12384 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, 12385 CodeCompletionTUInfo &CCTUInfo, 12386 SmallVectorImpl<CodeCompletionResult> &Results); 12387 //@} 12388 12389 //===--------------------------------------------------------------------===// 12390 // Extra semantic analysis beyond the C type system 12391 12392 public: 12393 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, 12394 unsigned ByteNo) const; 12395 12396 private: 12397 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 12398 const ArraySubscriptExpr *ASE=nullptr, 12399 bool AllowOnePastEnd=true, bool IndexNegated=false); 12400 void CheckArrayAccess(const Expr *E); 12401 // Used to grab the relevant information from a FormatAttr and a 12402 // FunctionDeclaration. 12403 struct FormatStringInfo { 12404 unsigned FormatIdx; 12405 unsigned FirstDataArg; 12406 bool HasVAListArg; 12407 }; 12408 12409 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 12410 FormatStringInfo *FSI); 12411 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 12412 const FunctionProtoType *Proto); 12413 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, 12414 ArrayRef<const Expr *> Args); 12415 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 12416 const FunctionProtoType *Proto); 12417 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto); 12418 void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 12419 ArrayRef<const Expr *> Args, 12420 const FunctionProtoType *Proto, SourceLocation Loc); 12421 12422 void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 12423 StringRef ParamName, QualType ArgTy, QualType ParamTy); 12424 12425 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 12426 const Expr *ThisArg, ArrayRef<const Expr *> Args, 12427 bool IsMemberFunction, SourceLocation Loc, SourceRange Range, 12428 VariadicCallType CallType); 12429 12430 bool CheckObjCString(Expr *Arg); 12431 ExprResult CheckOSLogFormatStringArg(Expr *Arg); 12432 12433 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, 12434 unsigned BuiltinID, CallExpr *TheCall); 12435 12436 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12437 CallExpr *TheCall); 12438 12439 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall); 12440 12441 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 12442 unsigned MaxWidth); 12443 bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12444 CallExpr *TheCall); 12445 bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 12446 bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 12447 bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12448 CallExpr *TheCall); 12449 bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg, 12450 bool WantCDE); 12451 bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12452 CallExpr *TheCall); 12453 12454 bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12455 CallExpr *TheCall); 12456 bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 12457 bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 12458 bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); 12459 bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12460 CallExpr *TheCall); 12461 bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 12462 CallExpr *TheCall); 12463 bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); 12464 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 12465 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall); 12466 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall); 12467 bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall); 12468 bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 12469 ArrayRef<int> ArgNums); 12470 bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums); 12471 bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 12472 ArrayRef<int> ArgNums); 12473 bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12474 CallExpr *TheCall); 12475 bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12476 CallExpr *TheCall); 12477 bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 12478 bool CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum); 12479 bool CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12480 CallExpr *TheCall); 12481 12482 bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall); 12483 bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call); 12484 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); 12485 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); 12486 bool SemaBuiltinComplex(CallExpr *TheCall); 12487 bool SemaBuiltinVSX(CallExpr *TheCall); 12488 bool SemaBuiltinOSLogFormat(CallExpr *TheCall); 12489 12490 public: 12491 // Used by C++ template instantiation. 12492 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); 12493 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 12494 SourceLocation BuiltinLoc, 12495 SourceLocation RParenLoc); 12496 12497 private: 12498 bool SemaBuiltinPrefetch(CallExpr *TheCall); 12499 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall); 12500 bool SemaBuiltinAssume(CallExpr *TheCall); 12501 bool SemaBuiltinAssumeAligned(CallExpr *TheCall); 12502 bool SemaBuiltinLongjmp(CallExpr *TheCall); 12503 bool SemaBuiltinSetjmp(CallExpr *TheCall); 12504 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); 12505 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult); 12506 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, 12507 AtomicExpr::AtomicOp Op); 12508 ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, 12509 bool IsDelete); 12510 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 12511 llvm::APSInt &Result); 12512 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, 12513 int High, bool RangeIsError = true); 12514 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 12515 unsigned Multiple); 12516 bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum); 12517 bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 12518 unsigned ArgBits); 12519 bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum, 12520 unsigned ArgBits); 12521 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 12522 int ArgNum, unsigned ExpectedFieldNum, 12523 bool AllowName); 12524 bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall); 12525 bool SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeDesc); 12526 12527 bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc); 12528 12529 // Matrix builtin handling. 12530 ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall, 12531 ExprResult CallResult); 12532 ExprResult SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 12533 ExprResult CallResult); 12534 ExprResult SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 12535 ExprResult CallResult); 12536 12537 public: 12538 enum FormatStringType { 12539 FST_Scanf, 12540 FST_Printf, 12541 FST_NSString, 12542 FST_Strftime, 12543 FST_Strfmon, 12544 FST_Kprintf, 12545 FST_FreeBSDKPrintf, 12546 FST_OSTrace, 12547 FST_OSLog, 12548 FST_Unknown 12549 }; 12550 static FormatStringType GetFormatStringType(const FormatAttr *Format); 12551 12552 bool FormatStringHasSArg(const StringLiteral *FExpr); 12553 12554 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx); 12555 12556 private: 12557 bool CheckFormatArguments(const FormatAttr *Format, 12558 ArrayRef<const Expr *> Args, 12559 bool IsCXXMember, 12560 VariadicCallType CallType, 12561 SourceLocation Loc, SourceRange Range, 12562 llvm::SmallBitVector &CheckedVarArgs); 12563 bool CheckFormatArguments(ArrayRef<const Expr *> Args, 12564 bool HasVAListArg, unsigned format_idx, 12565 unsigned firstDataArg, FormatStringType Type, 12566 VariadicCallType CallType, 12567 SourceLocation Loc, SourceRange range, 12568 llvm::SmallBitVector &CheckedVarArgs); 12569 12570 void CheckAbsoluteValueFunction(const CallExpr *Call, 12571 const FunctionDecl *FDecl); 12572 12573 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl); 12574 12575 void CheckMemaccessArguments(const CallExpr *Call, 12576 unsigned BId, 12577 IdentifierInfo *FnName); 12578 12579 void CheckStrlcpycatArguments(const CallExpr *Call, 12580 IdentifierInfo *FnName); 12581 12582 void CheckStrncatArguments(const CallExpr *Call, 12583 IdentifierInfo *FnName); 12584 12585 void CheckFreeArguments(const CallExpr *E); 12586 12587 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 12588 SourceLocation ReturnLoc, 12589 bool isObjCMethod = false, 12590 const AttrVec *Attrs = nullptr, 12591 const FunctionDecl *FD = nullptr); 12592 12593 public: 12594 void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS); 12595 12596 private: 12597 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); 12598 void CheckBoolLikeConversion(Expr *E, SourceLocation CC); 12599 void CheckForIntOverflow(Expr *E); 12600 void CheckUnsequencedOperations(const Expr *E); 12601 12602 /// Perform semantic checks on a completed expression. This will either 12603 /// be a full-expression or a default argument expression. 12604 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(), 12605 bool IsConstexpr = false); 12606 12607 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, 12608 Expr *Init); 12609 12610 /// Check if there is a field shadowing. 12611 void CheckShadowInheritedFields(const SourceLocation &Loc, 12612 DeclarationName FieldName, 12613 const CXXRecordDecl *RD, 12614 bool DeclIsField = true); 12615 12616 /// Check if the given expression contains 'break' or 'continue' 12617 /// statement that produces control flow different from GCC. 12618 void CheckBreakContinueBinding(Expr *E); 12619 12620 /// Check whether receiver is mutable ObjC container which 12621 /// attempts to add itself into the container 12622 void CheckObjCCircularContainer(ObjCMessageExpr *Message); 12623 12624 void CheckTCBEnforcement(const CallExpr *TheCall, const FunctionDecl *Callee); 12625 12626 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE); 12627 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, 12628 bool DeleteWasArrayForm); 12629 public: 12630 /// Register a magic integral constant to be used as a type tag. 12631 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 12632 uint64_t MagicValue, QualType Type, 12633 bool LayoutCompatible, bool MustBeNull); 12634 12635 struct TypeTagData { TypeTagDataTypeTagData12636 TypeTagData() {} 12637 TypeTagDataTypeTagData12638 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) : 12639 Type(Type), LayoutCompatible(LayoutCompatible), 12640 MustBeNull(MustBeNull) 12641 {} 12642 12643 QualType Type; 12644 12645 /// If true, \c Type should be compared with other expression's types for 12646 /// layout-compatibility. 12647 unsigned LayoutCompatible : 1; 12648 unsigned MustBeNull : 1; 12649 }; 12650 12651 /// A pair of ArgumentKind identifier and magic value. This uniquely 12652 /// identifies the magic value. 12653 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; 12654 12655 private: 12656 /// A map from magic value to type information. 12657 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>> 12658 TypeTagForDatatypeMagicValues; 12659 12660 /// Peform checks on a call of a function with argument_with_type_tag 12661 /// or pointer_with_type_tag attributes. 12662 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 12663 const ArrayRef<const Expr *> ExprArgs, 12664 SourceLocation CallSiteLoc); 12665 12666 /// Check if we are taking the address of a packed field 12667 /// as this may be a problem if the pointer value is dereferenced. 12668 void CheckAddressOfPackedMember(Expr *rhs); 12669 12670 /// The parser's current scope. 12671 /// 12672 /// The parser maintains this state here. 12673 Scope *CurScope; 12674 12675 mutable IdentifierInfo *Ident_super; 12676 mutable IdentifierInfo *Ident___float128; 12677 12678 /// Nullability type specifiers. 12679 IdentifierInfo *Ident__Nonnull = nullptr; 12680 IdentifierInfo *Ident__Nullable = nullptr; 12681 IdentifierInfo *Ident__Nullable_result = nullptr; 12682 IdentifierInfo *Ident__Null_unspecified = nullptr; 12683 12684 IdentifierInfo *Ident_NSError = nullptr; 12685 12686 /// The handler for the FileChanged preprocessor events. 12687 /// 12688 /// Used for diagnostics that implement custom semantic analysis for #include 12689 /// directives, like -Wpragma-pack. 12690 sema::SemaPPCallbacks *SemaPPCallbackHandler; 12691 12692 protected: 12693 friend class Parser; 12694 friend class InitializationSequence; 12695 friend class ASTReader; 12696 friend class ASTDeclReader; 12697 friend class ASTWriter; 12698 12699 public: 12700 /// Retrieve the keyword associated 12701 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability); 12702 12703 /// The struct behind the CFErrorRef pointer. 12704 RecordDecl *CFError = nullptr; 12705 bool isCFError(RecordDecl *D); 12706 12707 /// Retrieve the identifier "NSError". 12708 IdentifierInfo *getNSErrorIdent(); 12709 12710 /// Retrieve the parser's current scope. 12711 /// 12712 /// This routine must only be used when it is certain that semantic analysis 12713 /// and the parser are in precisely the same context, which is not the case 12714 /// when, e.g., we are performing any kind of template instantiation. 12715 /// Therefore, the only safe places to use this scope are in the parser 12716 /// itself and in routines directly invoked from the parser and *never* from 12717 /// template substitution or instantiation. getCurScope()12718 Scope *getCurScope() const { return CurScope; } 12719 incrementMSManglingNumber()12720 void incrementMSManglingNumber() const { 12721 return CurScope->incrementMSManglingNumber(); 12722 } 12723 12724 IdentifierInfo *getSuperIdentifier() const; 12725 IdentifierInfo *getFloat128Identifier() const; 12726 12727 Decl *getObjCDeclContext() const; 12728 getCurLexicalContext()12729 DeclContext *getCurLexicalContext() const { 12730 return OriginalLexicalContext ? OriginalLexicalContext : CurContext; 12731 } 12732 getCurObjCLexicalContext()12733 const DeclContext *getCurObjCLexicalContext() const { 12734 const DeclContext *DC = getCurLexicalContext(); 12735 // A category implicitly has the attribute of the interface. 12736 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC)) 12737 DC = CatD->getClassInterface(); 12738 return DC; 12739 } 12740 12741 /// Determine the number of levels of enclosing template parameters. This is 12742 /// only usable while parsing. Note that this does not include dependent 12743 /// contexts in which no template parameters have yet been declared, such as 12744 /// in a terse function template or generic lambda before the first 'auto' is 12745 /// encountered. 12746 unsigned getTemplateDepth(Scope *S) const; 12747 12748 /// To be used for checking whether the arguments being passed to 12749 /// function exceeds the number of parameters expected for it. 12750 static bool TooManyArguments(size_t NumParams, size_t NumArgs, 12751 bool PartialOverloading = false) { 12752 // We check whether we're just after a comma in code-completion. 12753 if (NumArgs > 0 && PartialOverloading) 12754 return NumArgs + 1 > NumParams; // If so, we view as an extra argument. 12755 return NumArgs > NumParams; 12756 } 12757 12758 // Emitting members of dllexported classes is delayed until the class 12759 // (including field initializers) is fully parsed. 12760 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses; 12761 SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions; 12762 12763 private: 12764 int ParsingClassDepth = 0; 12765 12766 class SavePendingParsedClassStateRAII { 12767 public: SavePendingParsedClassStateRAII(Sema & S)12768 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); } 12769 ~SavePendingParsedClassStateRAII()12770 ~SavePendingParsedClassStateRAII() { 12771 assert(S.DelayedOverridingExceptionSpecChecks.empty() && 12772 "there shouldn't be any pending delayed exception spec checks"); 12773 assert(S.DelayedEquivalentExceptionSpecChecks.empty() && 12774 "there shouldn't be any pending delayed exception spec checks"); 12775 swapSavedState(); 12776 } 12777 12778 private: 12779 Sema &S; 12780 decltype(DelayedOverridingExceptionSpecChecks) 12781 SavedOverridingExceptionSpecChecks; 12782 decltype(DelayedEquivalentExceptionSpecChecks) 12783 SavedEquivalentExceptionSpecChecks; 12784 swapSavedState()12785 void swapSavedState() { 12786 SavedOverridingExceptionSpecChecks.swap( 12787 S.DelayedOverridingExceptionSpecChecks); 12788 SavedEquivalentExceptionSpecChecks.swap( 12789 S.DelayedEquivalentExceptionSpecChecks); 12790 } 12791 }; 12792 12793 /// Helper class that collects misaligned member designations and 12794 /// their location info for delayed diagnostics. 12795 struct MisalignedMember { 12796 Expr *E; 12797 RecordDecl *RD; 12798 ValueDecl *MD; 12799 CharUnits Alignment; 12800 MisalignedMemberMisalignedMember12801 MisalignedMember() : E(), RD(), MD(), Alignment() {} MisalignedMemberMisalignedMember12802 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD, 12803 CharUnits Alignment) 12804 : E(E), RD(RD), MD(MD), Alignment(Alignment) {} MisalignedMemberMisalignedMember12805 explicit MisalignedMember(Expr *E) 12806 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {} 12807 12808 bool operator==(const MisalignedMember &m) { return this->E == m.E; } 12809 }; 12810 /// Small set of gathered accesses to potentially misaligned members 12811 /// due to the packed attribute. 12812 SmallVector<MisalignedMember, 4> MisalignedMembers; 12813 12814 /// Adds an expression to the set of gathered misaligned members. 12815 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 12816 CharUnits Alignment); 12817 12818 public: 12819 /// Diagnoses the current set of gathered accesses. This typically 12820 /// happens at full expression level. The set is cleared after emitting the 12821 /// diagnostics. 12822 void DiagnoseMisalignedMembers(); 12823 12824 /// This function checks if the expression is in the sef of potentially 12825 /// misaligned members and it is converted to some pointer type T with lower 12826 /// or equal alignment requirements. If so it removes it. This is used when 12827 /// we do not want to diagnose such misaligned access (e.g. in conversions to 12828 /// void*). 12829 void DiscardMisalignedMemberAddress(const Type *T, Expr *E); 12830 12831 /// This function calls Action when it determines that E designates a 12832 /// misaligned member due to the packed attribute. This is used to emit 12833 /// local diagnostics like in reference binding. 12834 void RefersToMemberWithReducedAlignment( 12835 Expr *E, 12836 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 12837 Action); 12838 12839 /// Describes the reason a calling convention specification was ignored, used 12840 /// for diagnostics. 12841 enum class CallingConventionIgnoredReason { 12842 ForThisTarget = 0, 12843 VariadicFunction, 12844 ConstructorDestructor, 12845 BuiltinFunction 12846 }; 12847 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current 12848 /// context is "used as device code". 12849 /// 12850 /// - If CurLexicalContext is a kernel function or it is known that the 12851 /// function will be emitted for the device, emits the diagnostics 12852 /// immediately. 12853 /// - If CurLexicalContext is a function and we are compiling 12854 /// for the device, but we don't know that this function will be codegen'ed 12855 /// for devive yet, creates a diagnostic which is emitted if and when we 12856 /// realize that the function will be codegen'ed. 12857 /// 12858 /// Example usage: 12859 /// 12860 /// Diagnose __float128 type usage only from SYCL device code if the current 12861 /// target doesn't support it 12862 /// if (!S.Context.getTargetInfo().hasFloat128Type() && 12863 /// S.getLangOpts().SYCLIsDevice) 12864 /// SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128"; 12865 SemaDiagnosticBuilder SYCLDiagIfDeviceCode(SourceLocation Loc, 12866 unsigned DiagID); 12867 12868 /// Check whether we're allowed to call Callee from the current context. 12869 /// 12870 /// - If the call is never allowed in a semantically-correct program 12871 /// emits an error and returns false. 12872 /// 12873 /// - If the call is allowed in semantically-correct programs, but only if 12874 /// it's never codegen'ed, creates a deferred diagnostic to be emitted if 12875 /// and when the caller is codegen'ed, and returns true. 12876 /// 12877 /// - Otherwise, returns true without emitting any diagnostics. 12878 /// 12879 /// Adds Callee to DeviceCallGraph if we don't know if its caller will be 12880 /// codegen'ed yet. 12881 bool checkSYCLDeviceFunction(SourceLocation Loc, FunctionDecl *Callee); 12882 }; 12883 12884 /// RAII object that enters a new expression evaluation context. 12885 class EnterExpressionEvaluationContext { 12886 Sema &Actions; 12887 bool Entered = true; 12888 12889 public: 12890 EnterExpressionEvaluationContext( 12891 Sema &Actions, Sema::ExpressionEvaluationContext NewContext, 12892 Decl *LambdaContextDecl = nullptr, 12893 Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = 12894 Sema::ExpressionEvaluationContextRecord::EK_Other, 12895 bool ShouldEnter = true) Actions(Actions)12896 : Actions(Actions), Entered(ShouldEnter) { 12897 if (Entered) 12898 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, 12899 ExprContext); 12900 } 12901 EnterExpressionEvaluationContext( 12902 Sema &Actions, Sema::ExpressionEvaluationContext NewContext, 12903 Sema::ReuseLambdaContextDecl_t, 12904 Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = 12905 Sema::ExpressionEvaluationContextRecord::EK_Other) Actions(Actions)12906 : Actions(Actions) { 12907 Actions.PushExpressionEvaluationContext( 12908 NewContext, Sema::ReuseLambdaContextDecl, ExprContext); 12909 } 12910 12911 enum InitListTag { InitList }; 12912 EnterExpressionEvaluationContext(Sema &Actions, InitListTag, 12913 bool ShouldEnter = true) Actions(Actions)12914 : Actions(Actions), Entered(false) { 12915 // In C++11 onwards, narrowing checks are performed on the contents of 12916 // braced-init-lists, even when they occur within unevaluated operands. 12917 // Therefore we still need to instantiate constexpr functions used in such 12918 // a context. 12919 if (ShouldEnter && Actions.isUnevaluatedContext() && 12920 Actions.getLangOpts().CPlusPlus11) { 12921 Actions.PushExpressionEvaluationContext( 12922 Sema::ExpressionEvaluationContext::UnevaluatedList); 12923 Entered = true; 12924 } 12925 } 12926 ~EnterExpressionEvaluationContext()12927 ~EnterExpressionEvaluationContext() { 12928 if (Entered) 12929 Actions.PopExpressionEvaluationContext(); 12930 } 12931 }; 12932 12933 DeductionFailureInfo 12934 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, 12935 sema::TemplateDeductionInfo &Info); 12936 12937 /// Contains a late templated function. 12938 /// Will be parsed at the end of the translation unit, used by Sema & Parser. 12939 struct LateParsedTemplate { 12940 CachedTokens Toks; 12941 /// The template function declaration to be late parsed. 12942 Decl *D; 12943 }; 12944 12945 template <> 12946 void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation, 12947 PragmaMsStackAction Action, 12948 llvm::StringRef StackSlotLabel, 12949 AlignPackInfo Value); 12950 12951 } // end namespace clang 12952 12953 namespace llvm { 12954 // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its 12955 // SourceLocation. 12956 template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> { 12957 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc; 12958 using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>; 12959 12960 static FunctionDeclAndLoc getEmptyKey() { 12961 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()}; 12962 } 12963 12964 static FunctionDeclAndLoc getTombstoneKey() { 12965 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()}; 12966 } 12967 12968 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) { 12969 return hash_combine(FDBaseInfo::getHashValue(FDL.FD), 12970 FDL.Loc.getHashValue()); 12971 } 12972 12973 static bool isEqual(const FunctionDeclAndLoc &LHS, 12974 const FunctionDeclAndLoc &RHS) { 12975 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc; 12976 } 12977 }; 12978 } // namespace llvm 12979 12980 #endif 12981