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/SmallSet.h" 62 #include "llvm/ADT/SmallPtrSet.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 /// Keeps track of expected type during expression parsing. The type is tied to 290 /// a particular token, all functions that update or consume the type take a 291 /// start location of the token they are looking at as a parameter. This allows 292 /// to avoid updating the type on hot paths in the parser. 293 class PreferredTypeBuilder { 294 public: 295 PreferredTypeBuilder() = default; PreferredTypeBuilder(QualType Type)296 explicit PreferredTypeBuilder(QualType Type) : Type(Type) {} 297 298 void enterCondition(Sema &S, SourceLocation Tok); 299 void enterReturn(Sema &S, SourceLocation Tok); 300 void enterVariableInit(SourceLocation Tok, Decl *D); 301 /// Computing a type for the function argument may require running 302 /// overloading, so we postpone its computation until it is actually needed. 303 /// 304 /// Clients should be very careful when using this funciton, as it stores a 305 /// function_ref, clients should make sure all calls to get() with the same 306 /// location happen while function_ref is alive. 307 void enterFunctionArgument(SourceLocation Tok, 308 llvm::function_ref<QualType()> ComputeType); 309 310 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc); 311 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, 312 SourceLocation OpLoc); 313 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op); 314 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base); 315 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS); 316 /// Handles all type casts, including C-style cast, C++ casts, etc. 317 void enterTypeCast(SourceLocation Tok, QualType CastType); 318 get(SourceLocation Tok)319 QualType get(SourceLocation Tok) const { 320 if (Tok != ExpectedLoc) 321 return QualType(); 322 if (!Type.isNull()) 323 return Type; 324 if (ComputeType) 325 return ComputeType(); 326 return QualType(); 327 } 328 329 private: 330 /// Start position of a token for which we store expected type. 331 SourceLocation ExpectedLoc; 332 /// Expected type for a token starting at ExpectedLoc. 333 QualType Type; 334 /// A function to compute expected type at ExpectedLoc. It is only considered 335 /// if Type is null. 336 llvm::function_ref<QualType()> ComputeType; 337 }; 338 339 /// Sema - This implements semantic analysis and AST building for C. 340 class Sema final { 341 Sema(const Sema &) = delete; 342 void operator=(const Sema &) = delete; 343 344 /// A key method to reduce duplicate debug info from Sema. 345 virtual void anchor(); 346 347 ///Source of additional semantic information. 348 ExternalSemaSource *ExternalSource; 349 350 ///Whether Sema has generated a multiplexer and has to delete it. 351 bool isMultiplexExternalSource; 352 353 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); 354 355 bool isVisibleSlow(const NamedDecl *D); 356 357 /// Determine whether two declarations should be linked together, given that 358 /// the old declaration might not be visible and the new declaration might 359 /// not have external linkage. shouldLinkPossiblyHiddenDecl(const NamedDecl * Old,const NamedDecl * New)360 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, 361 const NamedDecl *New) { 362 if (isVisible(Old)) 363 return true; 364 // See comment in below overload for why it's safe to compute the linkage 365 // of the new declaration here. 366 if (New->isExternallyDeclarable()) { 367 assert(Old->isExternallyDeclarable() && 368 "should not have found a non-externally-declarable previous decl"); 369 return true; 370 } 371 return false; 372 } 373 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New); 374 375 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 376 QualType ResultTy, 377 ArrayRef<QualType> Args); 378 379 public: 380 /// The maximum alignment, same as in llvm::Value. We duplicate them here 381 /// because that allows us not to duplicate the constants in clang code, 382 /// which we must to since we can't directly use the llvm constants. 383 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp 384 /// 385 /// This is the greatest alignment value supported by load, store, and alloca 386 /// instructions, and global values. 387 static const unsigned MaxAlignmentExponent = 29; 388 static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent; 389 390 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; 391 typedef OpaquePtr<TemplateName> TemplateTy; 392 typedef OpaquePtr<QualType> TypeTy; 393 394 OpenCLOptions OpenCLFeatures; 395 FPOptions CurFPFeatures; 396 397 const LangOptions &LangOpts; 398 Preprocessor &PP; 399 ASTContext &Context; 400 ASTConsumer &Consumer; 401 DiagnosticsEngine &Diags; 402 SourceManager &SourceMgr; 403 404 /// Flag indicating whether or not to collect detailed statistics. 405 bool CollectStats; 406 407 /// Code-completion consumer. 408 CodeCompleteConsumer *CodeCompleter; 409 410 /// CurContext - This is the current declaration context of parsing. 411 DeclContext *CurContext; 412 413 /// Generally null except when we temporarily switch decl contexts, 414 /// like in \see ActOnObjCTemporaryExitContainerContext. 415 DeclContext *OriginalLexicalContext; 416 417 /// VAListTagName - The declaration name corresponding to __va_list_tag. 418 /// This is used as part of a hack to omit that class from ADL results. 419 DeclarationName VAListTagName; 420 421 bool MSStructPragmaOn; // True when \#pragma ms_struct on 422 423 /// Controls member pointer representation format under the MS ABI. 424 LangOptions::PragmaMSPointersToMembersKind 425 MSPointerToMemberRepresentationMethod; 426 427 /// Stack of active SEH __finally scopes. Can be empty. 428 SmallVector<Scope*, 2> CurrentSEHFinally; 429 430 /// Source location for newly created implicit MSInheritanceAttrs 431 SourceLocation ImplicitMSInheritanceAttrLoc; 432 433 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by 434 /// `TransformTypos` in order to keep track of any TypoExprs that are created 435 /// recursively during typo correction and wipe them away if the correction 436 /// fails. 437 llvm::SmallVector<TypoExpr *, 2> TypoExprs; 438 439 /// pragma clang section kind 440 enum PragmaClangSectionKind { 441 PCSK_Invalid = 0, 442 PCSK_BSS = 1, 443 PCSK_Data = 2, 444 PCSK_Rodata = 3, 445 PCSK_Text = 4, 446 PCSK_Relro = 5 447 }; 448 449 enum PragmaClangSectionAction { 450 PCSA_Set = 0, 451 PCSA_Clear = 1 452 }; 453 454 struct PragmaClangSection { 455 std::string SectionName; 456 bool Valid = false; 457 SourceLocation PragmaLocation; 458 459 void Act(SourceLocation PragmaLocation, 460 PragmaClangSectionAction Action, 461 StringLiteral* Name); 462 }; 463 464 PragmaClangSection PragmaClangBSSSection; 465 PragmaClangSection PragmaClangDataSection; 466 PragmaClangSection PragmaClangRodataSection; 467 PragmaClangSection PragmaClangRelroSection; 468 PragmaClangSection PragmaClangTextSection; 469 470 enum PragmaMsStackAction { 471 PSK_Reset = 0x0, // #pragma () 472 PSK_Set = 0x1, // #pragma (value) 473 PSK_Push = 0x2, // #pragma (push[, id]) 474 PSK_Pop = 0x4, // #pragma (pop[, id]) 475 PSK_Show = 0x8, // #pragma (show) -- only for "pack"! 476 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value) 477 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value) 478 }; 479 480 template<typename ValueType> 481 struct PragmaStack { 482 struct Slot { 483 llvm::StringRef StackSlotLabel; 484 ValueType Value; 485 SourceLocation PragmaLocation; 486 SourceLocation PragmaPushLocation; SlotPragmaStack::Slot487 Slot(llvm::StringRef StackSlotLabel, ValueType Value, 488 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation) 489 : StackSlotLabel(StackSlotLabel), Value(Value), 490 PragmaLocation(PragmaLocation), 491 PragmaPushLocation(PragmaPushLocation) {} 492 }; 493 ActPragmaStack494 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, 495 llvm::StringRef StackSlotLabel, ValueType Value) { 496 if (Action == PSK_Reset) { 497 CurrentValue = DefaultValue; 498 CurrentPragmaLocation = PragmaLocation; 499 return; 500 } 501 if (Action & PSK_Push) 502 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation, 503 PragmaLocation); 504 else if (Action & PSK_Pop) { 505 if (!StackSlotLabel.empty()) { 506 // If we've got a label, try to find it and jump there. 507 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) { 508 return x.StackSlotLabel == StackSlotLabel; 509 }); 510 // If we found the label so pop from there. 511 if (I != Stack.rend()) { 512 CurrentValue = I->Value; 513 CurrentPragmaLocation = I->PragmaLocation; 514 Stack.erase(std::prev(I.base()), Stack.end()); 515 } 516 } else if (!Stack.empty()) { 517 // We do not have a label, just pop the last entry. 518 CurrentValue = Stack.back().Value; 519 CurrentPragmaLocation = Stack.back().PragmaLocation; 520 Stack.pop_back(); 521 } 522 } 523 if (Action & PSK_Set) { 524 CurrentValue = Value; 525 CurrentPragmaLocation = PragmaLocation; 526 } 527 } 528 529 // MSVC seems to add artificial slots to #pragma stacks on entering a C++ 530 // method body to restore the stacks on exit, so it works like this: 531 // 532 // struct S { 533 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>) 534 // void Method {} 535 // #pragma <name>(pop, InternalPragmaSlot) 536 // }; 537 // 538 // It works even with #pragma vtordisp, although MSVC doesn't support 539 // #pragma vtordisp(push [, id], n) 540 // syntax. 541 // 542 // Push / pop a named sentinel slot. SentinelActionPragmaStack543 void SentinelAction(PragmaMsStackAction Action, StringRef Label) { 544 assert((Action == PSK_Push || Action == PSK_Pop) && 545 "Can only push / pop #pragma stack sentinels!"); 546 Act(CurrentPragmaLocation, Action, Label, CurrentValue); 547 } 548 549 // Constructors. PragmaStackPragmaStack550 explicit PragmaStack(const ValueType &Default) 551 : DefaultValue(Default), CurrentValue(Default) {} 552 hasValuePragmaStack553 bool hasValue() const { return CurrentValue != DefaultValue; } 554 555 SmallVector<Slot, 2> Stack; 556 ValueType DefaultValue; // Value used for PSK_Reset action. 557 ValueType CurrentValue; 558 SourceLocation CurrentPragmaLocation; 559 }; 560 // FIXME: We should serialize / deserialize these if they occur in a PCH (but 561 // we shouldn't do so if they're in a module). 562 563 /// Whether to insert vtordisps prior to virtual bases in the Microsoft 564 /// C++ ABI. Possible values are 0, 1, and 2, which mean: 565 /// 566 /// 0: Suppress all vtordisps 567 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial 568 /// structors 569 /// 2: Always insert vtordisps to support RTTI on partially constructed 570 /// objects 571 PragmaStack<MSVtorDispMode> VtorDispStack; 572 // #pragma pack. 573 // Sentinel to represent when the stack is set to mac68k alignment. 574 static const unsigned kMac68kAlignmentSentinel = ~0U; 575 PragmaStack<unsigned> PackStack; 576 // The current #pragma pack values and locations at each #include. 577 struct PackIncludeState { 578 unsigned CurrentValue; 579 SourceLocation CurrentPragmaLocation; 580 bool HasNonDefaultValue, ShouldWarnOnInclude; 581 }; 582 SmallVector<PackIncludeState, 8> PackIncludeStack; 583 // Segment #pragmas. 584 PragmaStack<StringLiteral *> DataSegStack; 585 PragmaStack<StringLiteral *> BSSSegStack; 586 PragmaStack<StringLiteral *> ConstSegStack; 587 PragmaStack<StringLiteral *> CodeSegStack; 588 589 // This stack tracks the current state of Sema.CurFPFeatures. 590 PragmaStack<unsigned> FpPragmaStack; CurFPFeatureOverrides()591 FPOptionsOverride CurFPFeatureOverrides() { 592 FPOptionsOverride result; 593 if (!FpPragmaStack.hasValue()) { 594 result = FPOptionsOverride(); 595 } else { 596 result = FPOptionsOverride(FpPragmaStack.CurrentValue); 597 } 598 return result; 599 } 600 601 // RAII object to push / pop sentinel slots for all MS #pragma stacks. 602 // Actions should be performed only if we enter / exit a C++ method body. 603 class PragmaStackSentinelRAII { 604 public: 605 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct); 606 ~PragmaStackSentinelRAII(); 607 608 private: 609 Sema &S; 610 StringRef SlotLabel; 611 bool ShouldAct; 612 }; 613 614 /// A mapping that describes the nullability we've seen in each header file. 615 FileNullabilityMap NullabilityMap; 616 617 /// Last section used with #pragma init_seg. 618 StringLiteral *CurInitSeg; 619 SourceLocation CurInitSegLoc; 620 621 /// VisContext - Manages the stack for \#pragma GCC visibility. 622 void *VisContext; // Really a "PragmaVisStack*" 623 624 /// This an attribute introduced by \#pragma clang attribute. 625 struct PragmaAttributeEntry { 626 SourceLocation Loc; 627 ParsedAttr *Attribute; 628 SmallVector<attr::SubjectMatchRule, 4> MatchRules; 629 bool IsUsed; 630 }; 631 632 /// A push'd group of PragmaAttributeEntries. 633 struct PragmaAttributeGroup { 634 /// The location of the push attribute. 635 SourceLocation Loc; 636 /// The namespace of this push group. 637 const IdentifierInfo *Namespace; 638 SmallVector<PragmaAttributeEntry, 2> Entries; 639 }; 640 641 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack; 642 643 /// The declaration that is currently receiving an attribute from the 644 /// #pragma attribute stack. 645 const Decl *PragmaAttributeCurrentTargetDecl; 646 647 /// This represents the last location of a "#pragma clang optimize off" 648 /// directive if such a directive has not been closed by an "on" yet. If 649 /// optimizations are currently "on", this is set to an invalid location. 650 SourceLocation OptimizeOffPragmaLocation; 651 652 /// Flag indicating if Sema is building a recovery call expression. 653 /// 654 /// This flag is used to avoid building recovery call expressions 655 /// if Sema is already doing so, which would cause infinite recursions. 656 bool IsBuildingRecoveryCallExpr; 657 658 /// Used to control the generation of ExprWithCleanups. 659 CleanupInfo Cleanup; 660 661 /// ExprCleanupObjects - This is the stack of objects requiring 662 /// cleanup that are created by the current full expression. 663 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects; 664 665 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference 666 /// to a variable (constant) that may or may not be odr-used in this Expr, and 667 /// we won't know until all lvalue-to-rvalue and discarded value conversions 668 /// have been applied to all subexpressions of the enclosing full expression. 669 /// This is cleared at the end of each full expression. 670 using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>, 671 llvm::SmallPtrSet<Expr *, 4>>; 672 MaybeODRUseExprSet MaybeODRUseExprs; 673 674 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope; 675 676 /// Stack containing information about each of the nested 677 /// function, block, and method scopes that are currently active. 678 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; 679 680 /// The index of the first FunctionScope that corresponds to the current 681 /// context. 682 unsigned FunctionScopesStart = 0; 683 getFunctionScopes()684 ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const { 685 return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart, 686 FunctionScopes.end()); 687 } 688 689 /// Stack containing information needed when in C++2a an 'auto' is encountered 690 /// in a function declaration parameter type specifier in order to invent a 691 /// corresponding template parameter in the enclosing abbreviated function 692 /// template. This information is also present in LambdaScopeInfo, stored in 693 /// the FunctionScopes stack. 694 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos; 695 696 /// The index of the first InventedParameterInfo that refers to the current 697 /// context. 698 unsigned InventedParameterInfosStart = 0; 699 getInventedParameterInfos()700 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const { 701 return llvm::makeArrayRef(InventedParameterInfos.begin() + 702 InventedParameterInfosStart, 703 InventedParameterInfos.end()); 704 } 705 706 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, 707 &ExternalSemaSource::ReadExtVectorDecls, 2, 2> 708 ExtVectorDeclsType; 709 710 /// ExtVectorDecls - This is a list all the extended vector types. This allows 711 /// us to associate a raw vector type with one of the ext_vector type names. 712 /// This is only necessary for issuing pretty diagnostics. 713 ExtVectorDeclsType ExtVectorDecls; 714 715 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. 716 std::unique_ptr<CXXFieldCollector> FieldCollector; 717 718 typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType; 719 720 /// Set containing all declared private fields that are not used. 721 NamedDeclSetType UnusedPrivateFields; 722 723 /// Set containing all typedefs that are likely unused. 724 llvm::SmallSetVector<const TypedefNameDecl *, 4> 725 UnusedLocalTypedefNameCandidates; 726 727 /// Delete-expressions to be analyzed at the end of translation unit 728 /// 729 /// This list contains class members, and locations of delete-expressions 730 /// that could not be proven as to whether they mismatch with new-expression 731 /// used in initializer of the field. 732 typedef std::pair<SourceLocation, bool> DeleteExprLoc; 733 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs; 734 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs; 735 736 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; 737 738 /// PureVirtualClassDiagSet - a set of class declarations which we have 739 /// emitted a list of pure virtual functions. Used to prevent emitting the 740 /// same list more than once. 741 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet; 742 743 /// ParsingInitForAutoVars - a set of declarations with auto types for which 744 /// we are currently parsing the initializer. 745 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; 746 747 /// Look for a locally scoped extern "C" declaration by the given name. 748 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name); 749 750 typedef LazyVector<VarDecl *, ExternalSemaSource, 751 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> 752 TentativeDefinitionsType; 753 754 /// All the tentative definitions encountered in the TU. 755 TentativeDefinitionsType TentativeDefinitions; 756 757 /// All the external declarations encoutered and used in the TU. 758 SmallVector<VarDecl *, 4> ExternalDeclarations; 759 760 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, 761 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> 762 UnusedFileScopedDeclsType; 763 764 /// The set of file scoped decls seen so far that have not been used 765 /// and must warn if not used. Only contains the first declaration. 766 UnusedFileScopedDeclsType UnusedFileScopedDecls; 767 768 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, 769 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> 770 DelegatingCtorDeclsType; 771 772 /// All the delegating constructors seen so far in the file, used for 773 /// cycle detection at the end of the TU. 774 DelegatingCtorDeclsType DelegatingCtorDecls; 775 776 /// All the overriding functions seen during a class definition 777 /// that had their exception spec checks delayed, plus the overridden 778 /// function. 779 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2> 780 DelayedOverridingExceptionSpecChecks; 781 782 /// All the function redeclarations seen during a class definition that had 783 /// their exception spec checks delayed, plus the prior declaration they 784 /// should be checked against. Except during error recovery, the new decl 785 /// should always be a friend declaration, as that's the only valid way to 786 /// redeclare a special member before its class is complete. 787 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2> 788 DelayedEquivalentExceptionSpecChecks; 789 790 typedef llvm::MapVector<const FunctionDecl *, 791 std::unique_ptr<LateParsedTemplate>> 792 LateParsedTemplateMapT; 793 LateParsedTemplateMapT LateParsedTemplateMap; 794 795 /// Callback to the parser to parse templated functions when needed. 796 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT); 797 typedef void LateTemplateParserCleanupCB(void *P); 798 LateTemplateParserCB *LateTemplateParser; 799 LateTemplateParserCleanupCB *LateTemplateParserCleanup; 800 void *OpaqueParser; 801 SetLateTemplateParser(LateTemplateParserCB * LTP,LateTemplateParserCleanupCB * LTPCleanup,void * P)802 void SetLateTemplateParser(LateTemplateParserCB *LTP, 803 LateTemplateParserCleanupCB *LTPCleanup, 804 void *P) { 805 LateTemplateParser = LTP; 806 LateTemplateParserCleanup = LTPCleanup; 807 OpaqueParser = P; 808 } 809 810 class DelayedDiagnostics; 811 812 class DelayedDiagnosticsState { 813 sema::DelayedDiagnosticPool *SavedPool; 814 friend class Sema::DelayedDiagnostics; 815 }; 816 typedef DelayedDiagnosticsState ParsingDeclState; 817 typedef DelayedDiagnosticsState ProcessingContextState; 818 819 /// A class which encapsulates the logic for delaying diagnostics 820 /// during parsing and other processing. 821 class DelayedDiagnostics { 822 /// The current pool of diagnostics into which delayed 823 /// diagnostics should go. 824 sema::DelayedDiagnosticPool *CurPool; 825 826 public: DelayedDiagnostics()827 DelayedDiagnostics() : CurPool(nullptr) {} 828 829 /// Adds a delayed diagnostic. 830 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h 831 832 /// Determines whether diagnostics should be delayed. shouldDelayDiagnostics()833 bool shouldDelayDiagnostics() { return CurPool != nullptr; } 834 835 /// Returns the current delayed-diagnostics pool. getCurrentPool()836 sema::DelayedDiagnosticPool *getCurrentPool() const { 837 return CurPool; 838 } 839 840 /// Enter a new scope. Access and deprecation diagnostics will be 841 /// collected in this pool. push(sema::DelayedDiagnosticPool & pool)842 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { 843 DelayedDiagnosticsState state; 844 state.SavedPool = CurPool; 845 CurPool = &pool; 846 return state; 847 } 848 849 /// Leave a delayed-diagnostic state that was previously pushed. 850 /// Do not emit any of the diagnostics. This is performed as part 851 /// of the bookkeeping of popping a pool "properly". popWithoutEmitting(DelayedDiagnosticsState state)852 void popWithoutEmitting(DelayedDiagnosticsState state) { 853 CurPool = state.SavedPool; 854 } 855 856 /// Enter a new scope where access and deprecation diagnostics are 857 /// not delayed. pushUndelayed()858 DelayedDiagnosticsState pushUndelayed() { 859 DelayedDiagnosticsState state; 860 state.SavedPool = CurPool; 861 CurPool = nullptr; 862 return state; 863 } 864 865 /// Undo a previous pushUndelayed(). popUndelayed(DelayedDiagnosticsState state)866 void popUndelayed(DelayedDiagnosticsState state) { 867 assert(CurPool == nullptr); 868 CurPool = state.SavedPool; 869 } 870 } DelayedDiagnostics; 871 872 /// A RAII object to temporarily push a declaration context. 873 class ContextRAII { 874 private: 875 Sema &S; 876 DeclContext *SavedContext; 877 ProcessingContextState SavedContextState; 878 QualType SavedCXXThisTypeOverride; 879 unsigned SavedFunctionScopesStart; 880 unsigned SavedInventedParameterInfosStart; 881 882 public: 883 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) S(S)884 : S(S), SavedContext(S.CurContext), 885 SavedContextState(S.DelayedDiagnostics.pushUndelayed()), 886 SavedCXXThisTypeOverride(S.CXXThisTypeOverride), 887 SavedFunctionScopesStart(S.FunctionScopesStart), 888 SavedInventedParameterInfosStart(S.InventedParameterInfosStart) 889 { 890 assert(ContextToPush && "pushing null context"); 891 S.CurContext = ContextToPush; 892 if (NewThisContext) 893 S.CXXThisTypeOverride = QualType(); 894 // Any saved FunctionScopes do not refer to this context. 895 S.FunctionScopesStart = S.FunctionScopes.size(); 896 S.InventedParameterInfosStart = S.InventedParameterInfos.size(); 897 } 898 pop()899 void pop() { 900 if (!SavedContext) return; 901 S.CurContext = SavedContext; 902 S.DelayedDiagnostics.popUndelayed(SavedContextState); 903 S.CXXThisTypeOverride = SavedCXXThisTypeOverride; 904 S.FunctionScopesStart = SavedFunctionScopesStart; 905 S.InventedParameterInfosStart = SavedInventedParameterInfosStart; 906 SavedContext = nullptr; 907 } 908 ~ContextRAII()909 ~ContextRAII() { 910 pop(); 911 } 912 }; 913 914 /// Whether the AST is currently being rebuilt to correct immediate 915 /// invocations. Immediate invocation candidates and references to consteval 916 /// functions aren't tracked when this is set. 917 bool RebuildingImmediateInvocation = false; 918 919 /// Used to change context to isConstantEvaluated without pushing a heavy 920 /// ExpressionEvaluationContextRecord object. 921 bool isConstantEvaluatedOverride; 922 isConstantEvaluated()923 bool isConstantEvaluated() { 924 return ExprEvalContexts.back().isConstantEvaluated() || 925 isConstantEvaluatedOverride; 926 } 927 928 /// RAII object to handle the state changes required to synthesize 929 /// a function body. 930 class SynthesizedFunctionScope { 931 Sema &S; 932 Sema::ContextRAII SavedContext; 933 bool PushedCodeSynthesisContext = false; 934 935 public: SynthesizedFunctionScope(Sema & S,DeclContext * DC)936 SynthesizedFunctionScope(Sema &S, DeclContext *DC) 937 : S(S), SavedContext(S, DC) { 938 S.PushFunctionScope(); 939 S.PushExpressionEvaluationContext( 940 Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 941 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 942 FD->setWillHaveBody(true); 943 else 944 assert(isa<ObjCMethodDecl>(DC)); 945 } 946 addContextNote(SourceLocation UseLoc)947 void addContextNote(SourceLocation UseLoc) { 948 assert(!PushedCodeSynthesisContext); 949 950 Sema::CodeSynthesisContext Ctx; 951 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction; 952 Ctx.PointOfInstantiation = UseLoc; 953 Ctx.Entity = cast<Decl>(S.CurContext); 954 S.pushCodeSynthesisContext(Ctx); 955 956 PushedCodeSynthesisContext = true; 957 } 958 ~SynthesizedFunctionScope()959 ~SynthesizedFunctionScope() { 960 if (PushedCodeSynthesisContext) 961 S.popCodeSynthesisContext(); 962 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) 963 FD->setWillHaveBody(false); 964 S.PopExpressionEvaluationContext(); 965 S.PopFunctionScopeInfo(); 966 } 967 }; 968 969 /// WeakUndeclaredIdentifiers - Identifiers contained in 970 /// \#pragma weak before declared. rare. may alias another 971 /// identifier, declared or undeclared 972 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers; 973 974 /// ExtnameUndeclaredIdentifiers - Identifiers contained in 975 /// \#pragma redefine_extname before declared. Used in Solaris system headers 976 /// to define functions that occur in multiple standards to call the version 977 /// in the currently selected standard. 978 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers; 979 980 981 /// Load weak undeclared identifiers from the external source. 982 void LoadExternalWeakUndeclaredIdentifiers(); 983 984 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by 985 /// \#pragma weak during processing of other Decls. 986 /// I couldn't figure out a clean way to generate these in-line, so 987 /// we store them here and handle separately -- which is a hack. 988 /// It would be best to refactor this. 989 SmallVector<Decl*,2> WeakTopLevelDecl; 990 991 IdentifierResolver IdResolver; 992 993 /// Translation Unit Scope - useful to Objective-C actions that need 994 /// to lookup file scope declarations in the "ordinary" C decl namespace. 995 /// For example, user-defined classes, built-in "id" type, etc. 996 Scope *TUScope; 997 998 /// The C++ "std" namespace, where the standard library resides. 999 LazyDeclPtr StdNamespace; 1000 1001 /// The C++ "std::bad_alloc" class, which is defined by the C++ 1002 /// standard library. 1003 LazyDeclPtr StdBadAlloc; 1004 1005 /// The C++ "std::align_val_t" enum class, which is defined by the C++ 1006 /// standard library. 1007 LazyDeclPtr StdAlignValT; 1008 1009 /// The C++ "std::experimental" namespace, where the experimental parts 1010 /// of the standard library resides. 1011 NamespaceDecl *StdExperimentalNamespaceCache; 1012 1013 /// The C++ "std::initializer_list" template, which is defined in 1014 /// \<initializer_list>. 1015 ClassTemplateDecl *StdInitializerList; 1016 1017 /// The C++ "std::coroutine_traits" template, which is defined in 1018 /// \<coroutine_traits> 1019 ClassTemplateDecl *StdCoroutineTraitsCache; 1020 1021 /// The C++ "type_info" declaration, which is defined in \<typeinfo>. 1022 RecordDecl *CXXTypeInfoDecl; 1023 1024 /// The MSVC "_GUID" struct, which is defined in MSVC header files. 1025 RecordDecl *MSVCGuidDecl; 1026 1027 /// Caches identifiers/selectors for NSFoundation APIs. 1028 std::unique_ptr<NSAPI> NSAPIObj; 1029 1030 /// The declaration of the Objective-C NSNumber class. 1031 ObjCInterfaceDecl *NSNumberDecl; 1032 1033 /// The declaration of the Objective-C NSValue class. 1034 ObjCInterfaceDecl *NSValueDecl; 1035 1036 /// Pointer to NSNumber type (NSNumber *). 1037 QualType NSNumberPointer; 1038 1039 /// Pointer to NSValue type (NSValue *). 1040 QualType NSValuePointer; 1041 1042 /// The Objective-C NSNumber methods used to create NSNumber literals. 1043 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; 1044 1045 /// The declaration of the Objective-C NSString class. 1046 ObjCInterfaceDecl *NSStringDecl; 1047 1048 /// Pointer to NSString type (NSString *). 1049 QualType NSStringPointer; 1050 1051 /// The declaration of the stringWithUTF8String: method. 1052 ObjCMethodDecl *StringWithUTF8StringMethod; 1053 1054 /// The declaration of the valueWithBytes:objCType: method. 1055 ObjCMethodDecl *ValueWithBytesObjCTypeMethod; 1056 1057 /// The declaration of the Objective-C NSArray class. 1058 ObjCInterfaceDecl *NSArrayDecl; 1059 1060 /// The declaration of the arrayWithObjects:count: method. 1061 ObjCMethodDecl *ArrayWithObjectsMethod; 1062 1063 /// The declaration of the Objective-C NSDictionary class. 1064 ObjCInterfaceDecl *NSDictionaryDecl; 1065 1066 /// The declaration of the dictionaryWithObjects:forKeys:count: method. 1067 ObjCMethodDecl *DictionaryWithObjectsMethod; 1068 1069 /// id<NSCopying> type. 1070 QualType QIDNSCopying; 1071 1072 /// will hold 'respondsToSelector:' 1073 Selector RespondsToSelectorSel; 1074 1075 /// A flag to remember whether the implicit forms of operator new and delete 1076 /// have been declared. 1077 bool GlobalNewDeleteDeclared; 1078 1079 /// A flag to indicate that we're in a context that permits abstract 1080 /// references to fields. This is really a 1081 bool AllowAbstractFieldReference; 1082 1083 /// Describes how the expressions currently being parsed are 1084 /// evaluated at run-time, if at all. 1085 enum class ExpressionEvaluationContext { 1086 /// The current expression and its subexpressions occur within an 1087 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of 1088 /// \c sizeof, where the type of the expression may be significant but 1089 /// no code will be generated to evaluate the value of the expression at 1090 /// run time. 1091 Unevaluated, 1092 1093 /// The current expression occurs within a braced-init-list within 1094 /// an unevaluated operand. This is mostly like a regular unevaluated 1095 /// context, except that we still instantiate constexpr functions that are 1096 /// referenced here so that we can perform narrowing checks correctly. 1097 UnevaluatedList, 1098 1099 /// The current expression occurs within a discarded statement. 1100 /// This behaves largely similarly to an unevaluated operand in preventing 1101 /// definitions from being required, but not in other ways. 1102 DiscardedStatement, 1103 1104 /// The current expression occurs within an unevaluated 1105 /// operand that unconditionally permits abstract references to 1106 /// fields, such as a SIZE operator in MS-style inline assembly. 1107 UnevaluatedAbstract, 1108 1109 /// The current context is "potentially evaluated" in C++11 terms, 1110 /// but the expression is evaluated at compile-time (like the values of 1111 /// cases in a switch statement). 1112 ConstantEvaluated, 1113 1114 /// The current expression is potentially evaluated at run time, 1115 /// which means that code may be generated to evaluate the value of the 1116 /// expression at run time. 1117 PotentiallyEvaluated, 1118 1119 /// The current expression is potentially evaluated, but any 1120 /// declarations referenced inside that expression are only used if 1121 /// in fact the current expression is used. 1122 /// 1123 /// This value is used when parsing default function arguments, for which 1124 /// we would like to provide diagnostics (e.g., passing non-POD arguments 1125 /// through varargs) but do not want to mark declarations as "referenced" 1126 /// until the default argument is used. 1127 PotentiallyEvaluatedIfUsed 1128 }; 1129 1130 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>; 1131 1132 /// Data structure used to record current or nested 1133 /// expression evaluation contexts. 1134 struct ExpressionEvaluationContextRecord { 1135 /// The expression evaluation context. 1136 ExpressionEvaluationContext Context; 1137 1138 /// Whether the enclosing context needed a cleanup. 1139 CleanupInfo ParentCleanup; 1140 1141 /// Whether we are in a decltype expression. 1142 bool IsDecltype; 1143 1144 /// The number of active cleanup objects when we entered 1145 /// this expression evaluation context. 1146 unsigned NumCleanupObjects; 1147 1148 /// The number of typos encountered during this expression evaluation 1149 /// context (i.e. the number of TypoExprs created). 1150 unsigned NumTypos; 1151 1152 MaybeODRUseExprSet SavedMaybeODRUseExprs; 1153 1154 /// The lambdas that are present within this context, if it 1155 /// is indeed an unevaluated context. 1156 SmallVector<LambdaExpr *, 2> Lambdas; 1157 1158 /// The declaration that provides context for lambda expressions 1159 /// and block literals if the normal declaration context does not 1160 /// suffice, e.g., in a default function argument. 1161 Decl *ManglingContextDecl; 1162 1163 /// If we are processing a decltype type, a set of call expressions 1164 /// for which we have deferred checking the completeness of the return type. 1165 SmallVector<CallExpr *, 8> DelayedDecltypeCalls; 1166 1167 /// If we are processing a decltype type, a set of temporary binding 1168 /// expressions for which we have deferred checking the destructor. 1169 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; 1170 1171 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs; 1172 1173 /// Expressions appearing as the LHS of a volatile assignment in this 1174 /// context. We produce a warning for these when popping the context if 1175 /// they are not discarded-value expressions nor unevaluated operands. 1176 SmallVector<Expr*, 2> VolatileAssignmentLHSs; 1177 1178 /// Set of candidates for starting an immediate invocation. 1179 llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates; 1180 1181 /// Set of DeclRefExprs referencing a consteval function when used in a 1182 /// context not already known to be immediately invoked. 1183 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval; 1184 1185 /// \brief Describes whether we are in an expression constext which we have 1186 /// to handle differently. 1187 enum ExpressionKind { 1188 EK_Decltype, EK_TemplateArgument, EK_Other 1189 } ExprContext; 1190 ExpressionEvaluationContextRecordExpressionEvaluationContextRecord1191 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, 1192 unsigned NumCleanupObjects, 1193 CleanupInfo ParentCleanup, 1194 Decl *ManglingContextDecl, 1195 ExpressionKind ExprContext) 1196 : Context(Context), ParentCleanup(ParentCleanup), 1197 NumCleanupObjects(NumCleanupObjects), NumTypos(0), 1198 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {} 1199 isUnevaluatedExpressionEvaluationContextRecord1200 bool isUnevaluated() const { 1201 return Context == ExpressionEvaluationContext::Unevaluated || 1202 Context == ExpressionEvaluationContext::UnevaluatedAbstract || 1203 Context == ExpressionEvaluationContext::UnevaluatedList; 1204 } isConstantEvaluatedExpressionEvaluationContextRecord1205 bool isConstantEvaluated() const { 1206 return Context == ExpressionEvaluationContext::ConstantEvaluated; 1207 } 1208 }; 1209 1210 /// A stack of expression evaluation contexts. 1211 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; 1212 1213 /// Emit a warning for all pending noderef expressions that we recorded. 1214 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec); 1215 1216 /// Compute the mangling number context for a lambda expression or 1217 /// block literal. Also return the extra mangling decl if any. 1218 /// 1219 /// \param DC - The DeclContext containing the lambda expression or 1220 /// block literal. 1221 std::tuple<MangleNumberingContext *, Decl *> 1222 getCurrentMangleNumberContext(const DeclContext *DC); 1223 1224 1225 /// SpecialMemberOverloadResult - The overloading result for a special member 1226 /// function. 1227 /// 1228 /// This is basically a wrapper around PointerIntPair. The lowest bits of the 1229 /// integer are used to determine whether overload resolution succeeded. 1230 class SpecialMemberOverloadResult { 1231 public: 1232 enum Kind { 1233 NoMemberOrDeleted, 1234 Ambiguous, 1235 Success 1236 }; 1237 1238 private: 1239 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; 1240 1241 public: SpecialMemberOverloadResult()1242 SpecialMemberOverloadResult() : Pair() {} SpecialMemberOverloadResult(CXXMethodDecl * MD)1243 SpecialMemberOverloadResult(CXXMethodDecl *MD) 1244 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {} 1245 getMethod()1246 CXXMethodDecl *getMethod() const { return Pair.getPointer(); } setMethod(CXXMethodDecl * MD)1247 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } 1248 getKind()1249 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } setKind(Kind K)1250 void setKind(Kind K) { Pair.setInt(K); } 1251 }; 1252 1253 class SpecialMemberOverloadResultEntry 1254 : public llvm::FastFoldingSetNode, 1255 public SpecialMemberOverloadResult { 1256 public: SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID & ID)1257 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID) 1258 : FastFoldingSetNode(ID) 1259 {} 1260 }; 1261 1262 /// A cache of special member function overload resolution results 1263 /// for C++ records. 1264 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache; 1265 1266 /// A cache of the flags available in enumerations with the flag_bits 1267 /// attribute. 1268 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache; 1269 1270 /// The kind of translation unit we are processing. 1271 /// 1272 /// When we're processing a complete translation unit, Sema will perform 1273 /// end-of-translation-unit semantic tasks (such as creating 1274 /// initializers for tentative definitions in C) once parsing has 1275 /// completed. Modules and precompiled headers perform different kinds of 1276 /// checks. 1277 TranslationUnitKind TUKind; 1278 1279 llvm::BumpPtrAllocator BumpAlloc; 1280 1281 /// The number of SFINAE diagnostics that have been trapped. 1282 unsigned NumSFINAEErrors; 1283 1284 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>> 1285 UnparsedDefaultArgInstantiationsMap; 1286 1287 /// A mapping from parameters with unparsed default arguments to the 1288 /// set of instantiations of each parameter. 1289 /// 1290 /// This mapping is a temporary data structure used when parsing 1291 /// nested class templates or nested classes of class templates, 1292 /// where we might end up instantiating an inner class before the 1293 /// default arguments of its methods have been parsed. 1294 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; 1295 1296 // Contains the locations of the beginning of unparsed default 1297 // argument locations. 1298 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs; 1299 1300 /// UndefinedInternals - all the used, undefined objects which require a 1301 /// definition in this translation unit. 1302 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed; 1303 1304 /// Determine if VD, which must be a variable or function, is an external 1305 /// symbol that nonetheless can't be referenced from outside this translation 1306 /// unit because its type has no linkage and it's not extern "C". 1307 bool isExternalWithNoLinkageType(ValueDecl *VD); 1308 1309 /// Obtain a sorted list of functions that are undefined but ODR-used. 1310 void getUndefinedButUsed( 1311 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined); 1312 1313 /// Retrieves list of suspicious delete-expressions that will be checked at 1314 /// the end of translation unit. 1315 const llvm::MapVector<FieldDecl *, DeleteLocs> & 1316 getMismatchingDeleteExpressions() const; 1317 1318 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods; 1319 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool; 1320 1321 /// Method Pool - allows efficient lookup when typechecking messages to "id". 1322 /// We need to maintain a list, since selectors can have differing signatures 1323 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% 1324 /// of selectors are "overloaded"). 1325 /// At the head of the list it is recorded whether there were 0, 1, or >= 2 1326 /// methods inside categories with a particular selector. 1327 GlobalMethodPool MethodPool; 1328 1329 /// Method selectors used in a \@selector expression. Used for implementation 1330 /// of -Wselector. 1331 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors; 1332 1333 /// List of SourceLocations where 'self' is implicitly retained inside a 1334 /// block. 1335 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1> 1336 ImplicitlyRetainedSelfLocs; 1337 1338 /// Kinds of C++ special members. 1339 enum CXXSpecialMember { 1340 CXXDefaultConstructor, 1341 CXXCopyConstructor, 1342 CXXMoveConstructor, 1343 CXXCopyAssignment, 1344 CXXMoveAssignment, 1345 CXXDestructor, 1346 CXXInvalid 1347 }; 1348 1349 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember> 1350 SpecialMemberDecl; 1351 1352 /// The C++ special members which we are currently in the process of 1353 /// declaring. If this process recursively triggers the declaration of the 1354 /// same special member, we should act as if it is not yet declared. 1355 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; 1356 1357 /// Kinds of defaulted comparison operator functions. 1358 enum class DefaultedComparisonKind : unsigned char { 1359 /// This is not a defaultable comparison operator. 1360 None, 1361 /// This is an operator== that should be implemented as a series of 1362 /// subobject comparisons. 1363 Equal, 1364 /// This is an operator<=> that should be implemented as a series of 1365 /// subobject comparisons. 1366 ThreeWay, 1367 /// This is an operator!= that should be implemented as a rewrite in terms 1368 /// of a == comparison. 1369 NotEqual, 1370 /// This is an <, <=, >, or >= that should be implemented as a rewrite in 1371 /// terms of a <=> comparison. 1372 Relational, 1373 }; 1374 1375 /// The function definitions which were renamed as part of typo-correction 1376 /// to match their respective declarations. We want to keep track of them 1377 /// to ensure that we don't emit a "redefinition" error if we encounter a 1378 /// correctly named definition after the renamed definition. 1379 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions; 1380 1381 /// Stack of types that correspond to the parameter entities that are 1382 /// currently being copy-initialized. Can be empty. 1383 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes; 1384 1385 void ReadMethodPool(Selector Sel); 1386 void updateOutOfDateSelector(Selector Sel); 1387 1388 /// Private Helper predicate to check for 'self'. 1389 bool isSelfExpr(Expr *RExpr); 1390 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method); 1391 1392 /// Cause the active diagnostic on the DiagosticsEngine to be 1393 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and 1394 /// should not be used elsewhere. 1395 void EmitCurrentDiagnostic(unsigned DiagID); 1396 1397 /// Records and restores the CurFPFeatures state on entry/exit of compound 1398 /// statements. 1399 class FPFeaturesStateRAII { 1400 public: FPFeaturesStateRAII(Sema & S)1401 FPFeaturesStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.CurFPFeatures) { 1402 OldOverrides = S.FpPragmaStack.CurrentValue; 1403 } ~FPFeaturesStateRAII()1404 ~FPFeaturesStateRAII() { 1405 S.CurFPFeatures = OldFPFeaturesState; 1406 S.FpPragmaStack.CurrentValue = OldOverrides; 1407 } getOverrides()1408 unsigned getOverrides() { return OldOverrides; } 1409 1410 private: 1411 Sema& S; 1412 FPOptions OldFPFeaturesState; 1413 unsigned OldOverrides; 1414 }; 1415 1416 void addImplicitTypedef(StringRef Name, QualType T); 1417 1418 bool WarnedStackExhausted = false; 1419 1420 public: 1421 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 1422 TranslationUnitKind TUKind = TU_Complete, 1423 CodeCompleteConsumer *CompletionConsumer = nullptr); 1424 ~Sema(); 1425 1426 /// Perform initialization that occurs after the parser has been 1427 /// initialized but before it parses anything. 1428 void Initialize(); 1429 getLangOpts()1430 const LangOptions &getLangOpts() const { return LangOpts; } getOpenCLOptions()1431 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } getCurFPFeatures()1432 FPOptions &getCurFPFeatures() { return CurFPFeatures; } 1433 getDiagnostics()1434 DiagnosticsEngine &getDiagnostics() const { return Diags; } getSourceManager()1435 SourceManager &getSourceManager() const { return SourceMgr; } getPreprocessor()1436 Preprocessor &getPreprocessor() const { return PP; } getASTContext()1437 ASTContext &getASTContext() const { return Context; } getASTConsumer()1438 ASTConsumer &getASTConsumer() const { return Consumer; } 1439 ASTMutationListener *getASTMutationListener() const; getExternalSource()1440 ExternalSemaSource* getExternalSource() const { return ExternalSource; } 1441 1442 ///Registers an external source. If an external source already exists, 1443 /// creates a multiplex external source and appends to it. 1444 /// 1445 ///\param[in] E - A non-null external sema source. 1446 /// 1447 void addExternalSource(ExternalSemaSource *E); 1448 1449 void PrintStats() const; 1450 1451 /// Warn that the stack is nearly exhausted. 1452 void warnStackExhausted(SourceLocation Loc); 1453 1454 /// Run some code with "sufficient" stack space. (Currently, at least 256K is 1455 /// guaranteed). Produces a warning if we're low on stack space and allocates 1456 /// more in that case. Use this in code that may recurse deeply (for example, 1457 /// in template instantiation) to avoid stack overflow. 1458 void runWithSufficientStackSpace(SourceLocation Loc, 1459 llvm::function_ref<void()> Fn); 1460 1461 /// Helper class that creates diagnostics with optional 1462 /// template instantiation stacks. 1463 /// 1464 /// This class provides a wrapper around the basic DiagnosticBuilder 1465 /// class that emits diagnostics. SemaDiagnosticBuilder is 1466 /// responsible for emitting the diagnostic (as DiagnosticBuilder 1467 /// does) and, if the diagnostic comes from inside a template 1468 /// instantiation, printing the template instantiation stack as 1469 /// well. 1470 class SemaDiagnosticBuilder : public DiagnosticBuilder { 1471 Sema &SemaRef; 1472 unsigned DiagID; 1473 1474 public: SemaDiagnosticBuilder(DiagnosticBuilder & DB,Sema & SemaRef,unsigned DiagID)1475 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) 1476 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { } 1477 1478 // This is a cunning lie. DiagnosticBuilder actually performs move 1479 // construction in its copy constructor (but due to varied uses, it's not 1480 // possible to conveniently express this as actual move construction). So 1481 // the default copy ctor here is fine, because the base class disables the 1482 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op 1483 // in that case anwyay. 1484 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default; 1485 ~SemaDiagnosticBuilder()1486 ~SemaDiagnosticBuilder() { 1487 // If we aren't active, there is nothing to do. 1488 if (!isActive()) return; 1489 1490 // Otherwise, we need to emit the diagnostic. First flush the underlying 1491 // DiagnosticBuilder data, and clear the diagnostic builder itself so it 1492 // won't emit the diagnostic in its own destructor. 1493 // 1494 // This seems wasteful, in that as written the DiagnosticBuilder dtor will 1495 // do its own needless checks to see if the diagnostic needs to be 1496 // emitted. However, because we take care to ensure that the builder 1497 // objects never escape, a sufficiently smart compiler will be able to 1498 // eliminate that code. 1499 FlushCounts(); 1500 Clear(); 1501 1502 // Dispatch to Sema to emit the diagnostic. 1503 SemaRef.EmitCurrentDiagnostic(DiagID); 1504 } 1505 1506 /// Teach operator<< to produce an object of the correct type. 1507 template<typename T> 1508 friend const SemaDiagnosticBuilder &operator<<( 1509 const SemaDiagnosticBuilder &Diag, const T &Value) { 1510 const DiagnosticBuilder &BaseDiag = Diag; 1511 BaseDiag << Value; 1512 return Diag; 1513 } 1514 }; 1515 1516 /// Emit a diagnostic. Diag(SourceLocation Loc,unsigned DiagID)1517 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { 1518 DiagnosticBuilder DB = Diags.Report(Loc, DiagID); 1519 return SemaDiagnosticBuilder(DB, *this, DiagID); 1520 } 1521 1522 /// Emit a partial diagnostic. 1523 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD); 1524 1525 /// Build a partial diagnostic. 1526 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h 1527 1528 bool findMacroSpelling(SourceLocation &loc, StringRef name); 1529 1530 /// Get a string to suggest for zero-initialization of a type. 1531 std::string 1532 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const; 1533 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const; 1534 1535 /// Calls \c Lexer::getLocForEndOfToken() 1536 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); 1537 1538 /// Retrieve the module loader associated with the preprocessor. 1539 ModuleLoader &getModuleLoader() const; 1540 1541 /// Invent a new identifier for parameters of abbreviated templates. 1542 IdentifierInfo * 1543 InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName, 1544 unsigned Index); 1545 1546 void emitAndClearUnusedLocalTypedefWarnings(); 1547 1548 private: 1549 /// Function or variable declarations to be checked for whether the deferred 1550 /// diagnostics should be emitted. 1551 SmallVector<Decl *, 4> DeclsToCheckForDeferredDiags; 1552 1553 public: 1554 // Emit all deferred diagnostics. 1555 void emitDeferredDiags(); 1556 1557 enum TUFragmentKind { 1558 /// The global module fragment, between 'module;' and a module-declaration. 1559 Global, 1560 /// A normal translation unit fragment. For a non-module unit, this is the 1561 /// entire translation unit. Otherwise, it runs from the module-declaration 1562 /// to the private-module-fragment (if any) or the end of the TU (if not). 1563 Normal, 1564 /// The private module fragment, between 'module :private;' and the end of 1565 /// the translation unit. 1566 Private 1567 }; 1568 1569 void ActOnStartOfTranslationUnit(); 1570 void ActOnEndOfTranslationUnit(); 1571 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind); 1572 1573 void CheckDelegatingCtorCycles(); 1574 1575 Scope *getScopeForContext(DeclContext *Ctx); 1576 1577 void PushFunctionScope(); 1578 void PushBlockScope(Scope *BlockScope, BlockDecl *Block); 1579 sema::LambdaScopeInfo *PushLambdaScope(); 1580 1581 /// This is used to inform Sema what the current TemplateParameterDepth 1582 /// is during Parsing. Currently it is used to pass on the depth 1583 /// when parsing generic lambda 'auto' parameters. 1584 void RecordParsingTemplateParameterDepth(unsigned Depth); 1585 1586 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, 1587 RecordDecl *RD, CapturedRegionKind K, 1588 unsigned OpenMPCaptureLevel = 0); 1589 1590 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short 1591 /// time after they've been popped. 1592 class PoppedFunctionScopeDeleter { 1593 Sema *Self; 1594 1595 public: PoppedFunctionScopeDeleter(Sema * Self)1596 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {} 1597 void operator()(sema::FunctionScopeInfo *Scope) const; 1598 }; 1599 1600 using PoppedFunctionScopePtr = 1601 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>; 1602 1603 PoppedFunctionScopePtr 1604 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, 1605 const Decl *D = nullptr, 1606 QualType BlockType = QualType()); 1607 getCurFunction()1608 sema::FunctionScopeInfo *getCurFunction() const { 1609 return FunctionScopes.empty() ? nullptr : FunctionScopes.back(); 1610 } 1611 1612 sema::FunctionScopeInfo *getEnclosingFunction() const; 1613 1614 void setFunctionHasBranchIntoScope(); 1615 void setFunctionHasBranchProtectedScope(); 1616 void setFunctionHasIndirectGoto(); 1617 1618 void PushCompoundScope(bool IsStmtExpr); 1619 void PopCompoundScope(); 1620 1621 sema::CompoundScopeInfo &getCurCompoundScope() const; 1622 1623 bool hasAnyUnrecoverableErrorsInThisFunction() const; 1624 1625 /// Retrieve the current block, if any. 1626 sema::BlockScopeInfo *getCurBlock(); 1627 1628 /// Get the innermost lambda enclosing the current location, if any. This 1629 /// looks through intervening non-lambda scopes such as local functions and 1630 /// blocks. 1631 sema::LambdaScopeInfo *getEnclosingLambda() const; 1632 1633 /// Retrieve the current lambda scope info, if any. 1634 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most 1635 /// lambda scope info ignoring all inner capturing scopes that are not 1636 /// lambda scopes. 1637 sema::LambdaScopeInfo * 1638 getCurLambda(bool IgnoreNonLambdaCapturingScope = false); 1639 1640 /// Retrieve the current generic lambda info, if any. 1641 sema::LambdaScopeInfo *getCurGenericLambda(); 1642 1643 /// Retrieve the current captured region, if any. 1644 sema::CapturedRegionScopeInfo *getCurCapturedRegion(); 1645 1646 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls WeakTopLevelDecls()1647 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } 1648 1649 /// Called before parsing a function declarator belonging to a function 1650 /// declaration. 1651 void ActOnStartFunctionDeclarationDeclarator(Declarator &D, 1652 unsigned TemplateParameterDepth); 1653 1654 /// Called after parsing a function declarator belonging to a function 1655 /// declaration. 1656 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D); 1657 1658 void ActOnComment(SourceRange Comment); 1659 1660 //===--------------------------------------------------------------------===// 1661 // Type Analysis / Processing: SemaType.cpp. 1662 // 1663 1664 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, 1665 const DeclSpec *DS = nullptr); 1666 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, 1667 const DeclSpec *DS = nullptr); 1668 QualType BuildPointerType(QualType T, SourceLocation Loc, 1669 DeclarationName Entity, bool* ValidPointer); 1670 QualType BuildReferenceType(QualType T, bool LValueRef, 1671 SourceLocation Loc, DeclarationName Entity); 1672 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, 1673 Expr *ArraySize, unsigned Quals, 1674 SourceRange Brackets, DeclarationName Entity); 1675 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc); 1676 QualType BuildExtVectorType(QualType T, Expr *ArraySize, 1677 SourceLocation AttrLoc); 1678 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, 1679 SourceLocation AttrLoc); 1680 1681 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, 1682 SourceLocation AttrLoc); 1683 1684 /// Same as above, but constructs the AddressSpace index if not provided. 1685 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, 1686 SourceLocation AttrLoc); 1687 1688 QualType BuildPointerInterpretationAttr(QualType T, 1689 PointerInterpretationKind PIK, 1690 SourceLocation QualifierLoc); 1691 1692 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc); 1693 1694 bool CheckFunctionReturnType(QualType T, SourceLocation Loc); 1695 1696 /// Build a function type. 1697 /// 1698 /// This routine checks the function type according to C++ rules and 1699 /// under the assumption that the result type and parameter types have 1700 /// just been instantiated from a template. It therefore duplicates 1701 /// some of the behavior of GetTypeForDeclarator, but in a much 1702 /// simpler form that is only suitable for this narrow use case. 1703 /// 1704 /// \param T The return type of the function. 1705 /// 1706 /// \param ParamTypes The parameter types of the function. This array 1707 /// will be modified to account for adjustments to the types of the 1708 /// function parameters. 1709 /// 1710 /// \param Loc The location of the entity whose type involves this 1711 /// function type or, if there is no such entity, the location of the 1712 /// type that will have function type. 1713 /// 1714 /// \param Entity The name of the entity that involves the function 1715 /// type, if known. 1716 /// 1717 /// \param EPI Extra information about the function type. Usually this will 1718 /// be taken from an existing function with the same prototype. 1719 /// 1720 /// \returns A suitable function type, if there are no errors. The 1721 /// unqualified type will always be a FunctionProtoType. 1722 /// Otherwise, returns a NULL type. 1723 QualType BuildFunctionType(QualType T, 1724 MutableArrayRef<QualType> ParamTypes, 1725 SourceLocation Loc, DeclarationName Entity, 1726 const FunctionProtoType::ExtProtoInfo &EPI); 1727 1728 QualType BuildMemberPointerType(QualType T, QualType Class, 1729 SourceLocation Loc, 1730 DeclarationName Entity); 1731 QualType BuildBlockPointerType(QualType T, 1732 SourceLocation Loc, DeclarationName Entity); 1733 QualType BuildParenType(QualType T); 1734 QualType BuildAtomicType(QualType T, SourceLocation Loc); 1735 QualType BuildReadPipeType(QualType T, 1736 SourceLocation Loc); 1737 QualType BuildWritePipeType(QualType T, 1738 SourceLocation Loc); 1739 QualType BuildExtIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc); 1740 1741 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); 1742 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); 1743 1744 /// Package the given type and TSI into a ParsedType. 1745 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); 1746 DeclarationNameInfo GetNameForDeclarator(Declarator &D); 1747 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); 1748 static QualType GetTypeFromParser(ParsedType Ty, 1749 TypeSourceInfo **TInfo = nullptr); 1750 CanThrowResult canThrow(const Stmt *E); 1751 /// Determine whether the callee of a particular function call can throw. 1752 /// E, D and Loc are all optional. 1753 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D, 1754 SourceLocation Loc = SourceLocation()); 1755 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, 1756 const FunctionProtoType *FPT); 1757 void UpdateExceptionSpec(FunctionDecl *FD, 1758 const FunctionProtoType::ExceptionSpecInfo &ESI); 1759 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range); 1760 bool CheckDistantExceptionSpec(QualType T); 1761 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); 1762 bool CheckEquivalentExceptionSpec( 1763 const FunctionProtoType *Old, SourceLocation OldLoc, 1764 const FunctionProtoType *New, SourceLocation NewLoc); 1765 bool CheckEquivalentExceptionSpec( 1766 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, 1767 const FunctionProtoType *Old, SourceLocation OldLoc, 1768 const FunctionProtoType *New, SourceLocation NewLoc); 1769 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType); 1770 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID, 1771 const PartialDiagnostic &NestedDiagID, 1772 const PartialDiagnostic &NoteID, 1773 const PartialDiagnostic &NoThrowDiagID, 1774 const FunctionProtoType *Superset, 1775 SourceLocation SuperLoc, 1776 const FunctionProtoType *Subset, 1777 SourceLocation SubLoc); 1778 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID, 1779 const PartialDiagnostic &NoteID, 1780 const FunctionProtoType *Target, 1781 SourceLocation TargetLoc, 1782 const FunctionProtoType *Source, 1783 SourceLocation SourceLoc); 1784 1785 TypeResult ActOnTypeName(Scope *S, Declarator &D); 1786 1787 /// The parser has parsed the context-sensitive type 'instancetype' 1788 /// in an Objective-C message declaration. Return the appropriate type. 1789 ParsedType ActOnObjCInstanceType(SourceLocation Loc); 1790 1791 /// Abstract class used to diagnose incomplete types. 1792 struct TypeDiagnoser { TypeDiagnoserTypeDiagnoser1793 TypeDiagnoser() {} 1794 1795 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0; ~TypeDiagnoserTypeDiagnoser1796 virtual ~TypeDiagnoser() {} 1797 }; 1798 getPrintable(int I)1799 static int getPrintable(int I) { return I; } getPrintable(unsigned I)1800 static unsigned getPrintable(unsigned I) { return I; } getPrintable(bool B)1801 static bool getPrintable(bool B) { return B; } getPrintable(const char * S)1802 static const char * getPrintable(const char *S) { return S; } getPrintable(StringRef S)1803 static StringRef getPrintable(StringRef S) { return S; } getPrintable(const std::string & S)1804 static const std::string &getPrintable(const std::string &S) { return S; } getPrintable(const IdentifierInfo * II)1805 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) { 1806 return II; 1807 } getPrintable(DeclarationName N)1808 static DeclarationName getPrintable(DeclarationName N) { return N; } getPrintable(QualType T)1809 static QualType getPrintable(QualType T) { return T; } getPrintable(SourceRange R)1810 static SourceRange getPrintable(SourceRange R) { return R; } getPrintable(SourceLocation L)1811 static SourceRange getPrintable(SourceLocation L) { return L; } getPrintable(const Expr * E)1812 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); } getPrintable(TypeLoc TL)1813 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();} 1814 1815 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser { 1816 protected: 1817 unsigned DiagID; 1818 std::tuple<const Ts &...> Args; 1819 1820 template <std::size_t... Is> emit(const SemaDiagnosticBuilder & DB,std::index_sequence<Is...>)1821 void emit(const SemaDiagnosticBuilder &DB, 1822 std::index_sequence<Is...>) const { 1823 // Apply all tuple elements to the builder in order. 1824 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...}; 1825 (void)Dummy; 1826 } 1827 1828 public: BoundTypeDiagnoser(unsigned DiagID,const Ts &...Args)1829 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args) 1830 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) { 1831 assert(DiagID != 0 && "no diagnostic for type diagnoser"); 1832 } 1833 diagnose(Sema & S,SourceLocation Loc,QualType T)1834 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 1835 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID); 1836 emit(DB, std::index_sequence_for<Ts...>()); 1837 DB << T; 1838 } 1839 }; 1840 1841 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type 1842 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless. 1843 /// For example, a diagnostic with no other parameters would generally have 1844 /// the form "...%select{incomplete|sizeless}0 type %1...". 1845 template <typename... Ts> 1846 class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> { 1847 public: SizelessTypeDiagnoser(unsigned DiagID,const Ts &...Args)1848 SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args) 1849 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {} 1850 diagnose(Sema & S,SourceLocation Loc,QualType T)1851 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 1852 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID); 1853 this->emit(DB, std::index_sequence_for<Ts...>()); 1854 DB << T->isSizelessType() << T; 1855 } 1856 }; 1857 1858 enum class CompleteTypeKind { 1859 /// Apply the normal rules for complete types. In particular, 1860 /// treat all sizeless types as incomplete. 1861 Normal, 1862 1863 /// Relax the normal rules for complete types so that they include 1864 /// sizeless built-in types. 1865 AcceptSizeless, 1866 1867 // FIXME: Eventually we should flip the default to Normal and opt in 1868 // to AcceptSizeless rather than opt out of it. 1869 Default = AcceptSizeless 1870 }; 1871 1872 private: 1873 /// Methods for marking which expressions involve dereferencing a pointer 1874 /// marked with the 'noderef' attribute. Expressions are checked bottom up as 1875 /// they are parsed, meaning that a noderef pointer may not be accessed. For 1876 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the 1877 /// `*p`, but need to check that `address of` is called on it. This requires 1878 /// keeping a container of all pending expressions and checking if the address 1879 /// of them are eventually taken. 1880 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E); 1881 void CheckAddressOfNoDeref(const Expr *E); 1882 void CheckMemberAccessOfNoDeref(const MemberExpr *E); 1883 1884 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, 1885 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser); 1886 1887 struct ModuleScope { 1888 SourceLocation BeginLoc; 1889 clang::Module *Module = nullptr; 1890 bool ModuleInterface = false; 1891 bool ImplicitGlobalModuleFragment = false; 1892 VisibleModuleSet OuterVisibleModules; 1893 }; 1894 /// The modules we're currently parsing. 1895 llvm::SmallVector<ModuleScope, 16> ModuleScopes; 1896 1897 /// Namespace definitions that we will export when they finish. 1898 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces; 1899 1900 /// Get the module whose scope we are currently within. getCurrentModule()1901 Module *getCurrentModule() const { 1902 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module; 1903 } 1904 1905 VisibleModuleSet VisibleModules; 1906 1907 public: 1908 /// Get the module owning an entity. getOwningModule(const Decl * Entity)1909 Module *getOwningModule(const Decl *Entity) { 1910 return Entity->getOwningModule(); 1911 } 1912 1913 /// Make a merged definition of an existing hidden definition \p ND 1914 /// visible at the specified location. 1915 void makeMergedDefinitionVisible(NamedDecl *ND); 1916 1917 bool isModuleVisible(const Module *M, bool ModulePrivate = false); 1918 1919 /// Determine whether a declaration is visible to name lookup. isVisible(const NamedDecl * D)1920 bool isVisible(const NamedDecl *D) { 1921 return D->isUnconditionallyVisible() || isVisibleSlow(D); 1922 } 1923 1924 /// Determine whether any declaration of an entity is visible. 1925 bool 1926 hasVisibleDeclaration(const NamedDecl *D, 1927 llvm::SmallVectorImpl<Module *> *Modules = nullptr) { 1928 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules); 1929 } 1930 bool hasVisibleDeclarationSlow(const NamedDecl *D, 1931 llvm::SmallVectorImpl<Module *> *Modules); 1932 1933 bool hasVisibleMergedDefinition(NamedDecl *Def); 1934 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def); 1935 1936 /// Determine if \p D and \p Suggested have a structurally compatible 1937 /// layout as described in C11 6.2.7/1. 1938 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested); 1939 1940 /// Determine if \p D has a visible definition. If not, suggest a declaration 1941 /// that should be made visible to expose the definition. 1942 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, 1943 bool OnlyNeedComplete = false); hasVisibleDefinition(const NamedDecl * D)1944 bool hasVisibleDefinition(const NamedDecl *D) { 1945 NamedDecl *Hidden; 1946 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden); 1947 } 1948 1949 /// Determine if the template parameter \p D has a visible default argument. 1950 bool 1951 hasVisibleDefaultArgument(const NamedDecl *D, 1952 llvm::SmallVectorImpl<Module *> *Modules = nullptr); 1953 1954 /// Determine if there is a visible declaration of \p D that is an explicit 1955 /// specialization declaration for a specialization of a template. (For a 1956 /// member specialization, use hasVisibleMemberSpecialization.) 1957 bool hasVisibleExplicitSpecialization( 1958 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); 1959 1960 /// Determine if there is a visible declaration of \p D that is a member 1961 /// specialization declaration (as opposed to an instantiated declaration). 1962 bool hasVisibleMemberSpecialization( 1963 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); 1964 1965 /// Determine if \p A and \p B are equivalent internal linkage declarations 1966 /// from different modules, and thus an ambiguity error can be downgraded to 1967 /// an extension warning. 1968 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 1969 const NamedDecl *B); 1970 void diagnoseEquivalentInternalLinkageDeclarations( 1971 SourceLocation Loc, const NamedDecl *D, 1972 ArrayRef<const NamedDecl *> Equiv); 1973 1974 bool isUsualDeallocationFunction(const CXXMethodDecl *FD); 1975 1976 bool isCompleteType(SourceLocation Loc, QualType T, 1977 CompleteTypeKind Kind = CompleteTypeKind::Default) { 1978 return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr); 1979 } 1980 bool RequireCompleteType(SourceLocation Loc, QualType T, 1981 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser); 1982 bool RequireCompleteType(SourceLocation Loc, QualType T, 1983 CompleteTypeKind Kind, unsigned DiagID); 1984 RequireCompleteType(SourceLocation Loc,QualType T,TypeDiagnoser & Diagnoser)1985 bool RequireCompleteType(SourceLocation Loc, QualType T, 1986 TypeDiagnoser &Diagnoser) { 1987 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser); 1988 } RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID)1989 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) { 1990 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID); 1991 } 1992 1993 template <typename... Ts> RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)1994 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, 1995 const Ts &...Args) { 1996 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 1997 return RequireCompleteType(Loc, T, Diagnoser); 1998 } 1999 2000 template <typename... Ts> RequireCompleteSizedType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)2001 bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, 2002 const Ts &... Args) { 2003 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 2004 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser); 2005 } 2006 2007 void completeExprArrayBound(Expr *E); 2008 bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, 2009 TypeDiagnoser &Diagnoser); 2010 bool RequireCompleteExprType(Expr *E, unsigned DiagID); 2011 2012 template <typename... Ts> RequireCompleteExprType(Expr * E,unsigned DiagID,const Ts &...Args)2013 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) { 2014 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 2015 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser); 2016 } 2017 2018 template <typename... Ts> RequireCompleteSizedExprType(Expr * E,unsigned DiagID,const Ts &...Args)2019 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, 2020 const Ts &... Args) { 2021 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 2022 return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser); 2023 } 2024 2025 bool RequireLiteralType(SourceLocation Loc, QualType T, 2026 TypeDiagnoser &Diagnoser); 2027 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); 2028 2029 template <typename... Ts> RequireLiteralType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)2030 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, 2031 const Ts &...Args) { 2032 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 2033 return RequireLiteralType(Loc, T, Diagnoser); 2034 } 2035 2036 QualType getElaboratedType(ElaboratedTypeKeyword Keyword, 2037 const CXXScopeSpec &SS, QualType T, 2038 TagDecl *OwnedTagDecl = nullptr); 2039 2040 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc); 2041 /// If AsUnevaluated is false, E is treated as though it were an evaluated 2042 /// context, such as when building a type for decltype(auto). 2043 QualType BuildDecltypeType(Expr *E, SourceLocation Loc, 2044 bool AsUnevaluated = true); 2045 QualType BuildUnaryTransformType(QualType BaseType, 2046 UnaryTransformType::UTTKind UKind, 2047 SourceLocation Loc); 2048 2049 //===--------------------------------------------------------------------===// 2050 // Symbol table / Decl tracking callbacks: SemaDecl.cpp. 2051 // 2052 2053 struct SkipBodyInfo { SkipBodyInfoSkipBodyInfo2054 SkipBodyInfo() 2055 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr), 2056 New(nullptr) {} 2057 bool ShouldSkip; 2058 bool CheckSameAsPrevious; 2059 NamedDecl *Previous; 2060 NamedDecl *New; 2061 }; 2062 2063 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); 2064 2065 void DiagnoseUseOfUnimplementedSelectors(); 2066 2067 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const; 2068 2069 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 2070 Scope *S, CXXScopeSpec *SS = nullptr, 2071 bool isClassName = false, bool HasTrailingDot = false, 2072 ParsedType ObjectType = nullptr, 2073 bool IsCtorOrDtorName = false, 2074 bool WantNontrivialTypeSourceInfo = false, 2075 bool IsClassTemplateDeductionContext = true, 2076 IdentifierInfo **CorrectedII = nullptr); 2077 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); 2078 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); 2079 void DiagnoseUnknownTypeName(IdentifierInfo *&II, 2080 SourceLocation IILoc, 2081 Scope *S, 2082 CXXScopeSpec *SS, 2083 ParsedType &SuggestedType, 2084 bool IsTemplateName = false); 2085 2086 /// Attempt to behave like MSVC in situations where lookup of an unqualified 2087 /// type name has failed in a dependent context. In these situations, we 2088 /// automatically form a DependentTypeName that will retry lookup in a related 2089 /// scope during instantiation. 2090 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 2091 SourceLocation NameLoc, 2092 bool IsTemplateTypeArg); 2093 2094 /// Describes the result of the name lookup and resolution performed 2095 /// by \c ClassifyName(). 2096 enum NameClassificationKind { 2097 /// This name is not a type or template in this context, but might be 2098 /// something else. 2099 NC_Unknown, 2100 /// Classification failed; an error has been produced. 2101 NC_Error, 2102 /// The name has been typo-corrected to a keyword. 2103 NC_Keyword, 2104 /// The name was classified as a type. 2105 NC_Type, 2106 /// The name was classified as a specific non-type, non-template 2107 /// declaration. ActOnNameClassifiedAsNonType should be called to 2108 /// convert the declaration to an expression. 2109 NC_NonType, 2110 /// The name was classified as an ADL-only function name. 2111 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the 2112 /// result to an expression. 2113 NC_UndeclaredNonType, 2114 /// The name denotes a member of a dependent type that could not be 2115 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to 2116 /// convert the result to an expression. 2117 NC_DependentNonType, 2118 /// The name was classified as a non-type, and an expression representing 2119 /// that name has been formed. 2120 NC_ContextIndependentExpr, 2121 /// The name was classified as a template whose specializations are types. 2122 NC_TypeTemplate, 2123 /// The name was classified as a variable template name. 2124 NC_VarTemplate, 2125 /// The name was classified as a function template name. 2126 NC_FunctionTemplate, 2127 /// The name was classified as an ADL-only function template name. 2128 NC_UndeclaredTemplate, 2129 /// The name was classified as a concept name. 2130 NC_Concept, 2131 }; 2132 2133 class NameClassification { 2134 NameClassificationKind Kind; 2135 union { 2136 ExprResult Expr; 2137 NamedDecl *NonTypeDecl; 2138 TemplateName Template; 2139 ParsedType Type; 2140 }; 2141 NameClassification(NameClassificationKind Kind)2142 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} 2143 2144 public: NameClassification(ParsedType Type)2145 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} 2146 NameClassification(const IdentifierInfo * Keyword)2147 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {} 2148 Error()2149 static NameClassification Error() { 2150 return NameClassification(NC_Error); 2151 } 2152 Unknown()2153 static NameClassification Unknown() { 2154 return NameClassification(NC_Unknown); 2155 } 2156 ContextIndependentExpr(ExprResult E)2157 static NameClassification ContextIndependentExpr(ExprResult E) { 2158 NameClassification Result(NC_ContextIndependentExpr); 2159 Result.Expr = E; 2160 return Result; 2161 } 2162 NonType(NamedDecl * D)2163 static NameClassification NonType(NamedDecl *D) { 2164 NameClassification Result(NC_NonType); 2165 Result.NonTypeDecl = D; 2166 return Result; 2167 } 2168 UndeclaredNonType()2169 static NameClassification UndeclaredNonType() { 2170 return NameClassification(NC_UndeclaredNonType); 2171 } 2172 DependentNonType()2173 static NameClassification DependentNonType() { 2174 return NameClassification(NC_DependentNonType); 2175 } 2176 TypeTemplate(TemplateName Name)2177 static NameClassification TypeTemplate(TemplateName Name) { 2178 NameClassification Result(NC_TypeTemplate); 2179 Result.Template = Name; 2180 return Result; 2181 } 2182 VarTemplate(TemplateName Name)2183 static NameClassification VarTemplate(TemplateName Name) { 2184 NameClassification Result(NC_VarTemplate); 2185 Result.Template = Name; 2186 return Result; 2187 } 2188 FunctionTemplate(TemplateName Name)2189 static NameClassification FunctionTemplate(TemplateName Name) { 2190 NameClassification Result(NC_FunctionTemplate); 2191 Result.Template = Name; 2192 return Result; 2193 } 2194 Concept(TemplateName Name)2195 static NameClassification Concept(TemplateName Name) { 2196 NameClassification Result(NC_Concept); 2197 Result.Template = Name; 2198 return Result; 2199 } 2200 UndeclaredTemplate(TemplateName Name)2201 static NameClassification UndeclaredTemplate(TemplateName Name) { 2202 NameClassification Result(NC_UndeclaredTemplate); 2203 Result.Template = Name; 2204 return Result; 2205 } 2206 getKind()2207 NameClassificationKind getKind() const { return Kind; } 2208 getExpression()2209 ExprResult getExpression() const { 2210 assert(Kind == NC_ContextIndependentExpr); 2211 return Expr; 2212 } 2213 getType()2214 ParsedType getType() const { 2215 assert(Kind == NC_Type); 2216 return Type; 2217 } 2218 getNonTypeDecl()2219 NamedDecl *getNonTypeDecl() const { 2220 assert(Kind == NC_NonType); 2221 return NonTypeDecl; 2222 } 2223 getTemplateName()2224 TemplateName getTemplateName() const { 2225 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || 2226 Kind == NC_VarTemplate || Kind == NC_Concept || 2227 Kind == NC_UndeclaredTemplate); 2228 return Template; 2229 } 2230 getTemplateNameKind()2231 TemplateNameKind getTemplateNameKind() const { 2232 switch (Kind) { 2233 case NC_TypeTemplate: 2234 return TNK_Type_template; 2235 case NC_FunctionTemplate: 2236 return TNK_Function_template; 2237 case NC_VarTemplate: 2238 return TNK_Var_template; 2239 case NC_Concept: 2240 return TNK_Concept_template; 2241 case NC_UndeclaredTemplate: 2242 return TNK_Undeclared_template; 2243 default: 2244 llvm_unreachable("unsupported name classification."); 2245 } 2246 } 2247 }; 2248 2249 /// Perform name lookup on the given name, classifying it based on 2250 /// the results of name lookup and the following token. 2251 /// 2252 /// This routine is used by the parser to resolve identifiers and help direct 2253 /// parsing. When the identifier cannot be found, this routine will attempt 2254 /// to correct the typo and classify based on the resulting name. 2255 /// 2256 /// \param S The scope in which we're performing name lookup. 2257 /// 2258 /// \param SS The nested-name-specifier that precedes the name. 2259 /// 2260 /// \param Name The identifier. If typo correction finds an alternative name, 2261 /// this pointer parameter will be updated accordingly. 2262 /// 2263 /// \param NameLoc The location of the identifier. 2264 /// 2265 /// \param NextToken The token following the identifier. Used to help 2266 /// disambiguate the name. 2267 /// 2268 /// \param CCC The correction callback, if typo correction is desired. 2269 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, 2270 IdentifierInfo *&Name, SourceLocation NameLoc, 2271 const Token &NextToken, 2272 CorrectionCandidateCallback *CCC = nullptr); 2273 2274 /// Act on the result of classifying a name as an undeclared (ADL-only) 2275 /// non-type declaration. 2276 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 2277 SourceLocation NameLoc); 2278 /// Act on the result of classifying a name as an undeclared member of a 2279 /// dependent base class. 2280 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 2281 IdentifierInfo *Name, 2282 SourceLocation NameLoc, 2283 bool IsAddressOfOperand); 2284 /// Act on the result of classifying a name as a specific non-type 2285 /// declaration. 2286 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 2287 NamedDecl *Found, 2288 SourceLocation NameLoc, 2289 const Token &NextToken); 2290 2291 /// Describes the detailed kind of a template name. Used in diagnostics. 2292 enum class TemplateNameKindForDiagnostics { 2293 ClassTemplate, 2294 FunctionTemplate, 2295 VarTemplate, 2296 AliasTemplate, 2297 TemplateTemplateParam, 2298 Concept, 2299 DependentTemplate 2300 }; 2301 TemplateNameKindForDiagnostics 2302 getTemplateNameKindForDiagnostics(TemplateName Name); 2303 2304 /// Determine whether it's plausible that E was intended to be a 2305 /// template-name. mightBeIntendedToBeTemplateName(ExprResult E,bool & Dependent)2306 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) { 2307 if (!getLangOpts().CPlusPlus || E.isInvalid()) 2308 return false; 2309 Dependent = false; 2310 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get())) 2311 return !DRE->hasExplicitTemplateArgs(); 2312 if (auto *ME = dyn_cast<MemberExpr>(E.get())) 2313 return !ME->hasExplicitTemplateArgs(); 2314 Dependent = true; 2315 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get())) 2316 return !DSDRE->hasExplicitTemplateArgs(); 2317 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get())) 2318 return !DSME->hasExplicitTemplateArgs(); 2319 // Any additional cases recognized here should also be handled by 2320 // diagnoseExprIntendedAsTemplateName. 2321 return false; 2322 } 2323 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, 2324 SourceLocation Less, 2325 SourceLocation Greater); 2326 2327 Decl *ActOnDeclarator(Scope *S, Declarator &D); 2328 2329 NamedDecl *HandleDeclarator(Scope *S, Declarator &D, 2330 MultiTemplateParamsArg TemplateParameterLists); 2331 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S); 2332 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); 2333 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 2334 DeclarationName Name, SourceLocation Loc, 2335 bool IsTemplateId); 2336 void 2337 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, 2338 SourceLocation FallbackLoc, 2339 SourceLocation ConstQualLoc = SourceLocation(), 2340 SourceLocation VolatileQualLoc = SourceLocation(), 2341 SourceLocation RestrictQualLoc = SourceLocation(), 2342 SourceLocation AtomicQualLoc = SourceLocation(), 2343 SourceLocation UnalignedQualLoc = SourceLocation()); 2344 2345 static bool adjustContextForLocalExternDecl(DeclContext *&DC); 2346 void DiagnoseFunctionSpecifiers(const DeclSpec &DS); 2347 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D, 2348 const LookupResult &R); 2349 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R); 2350 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 2351 const LookupResult &R); 2352 void CheckShadow(Scope *S, VarDecl *D); 2353 2354 /// Warn if 'E', which is an expression that is about to be modified, refers 2355 /// to a shadowing declaration. 2356 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc); 2357 2358 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI); 2359 2360 private: 2361 /// Map of current shadowing declarations to shadowed declarations. Warn if 2362 /// it looks like the user is trying to modify the shadowing declaration. 2363 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls; 2364 2365 public: 2366 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); 2367 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope); 2368 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 2369 TypedefNameDecl *NewTD); 2370 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); 2371 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 2372 TypeSourceInfo *TInfo, 2373 LookupResult &Previous); 2374 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, 2375 LookupResult &Previous, bool &Redeclaration); 2376 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 2377 TypeSourceInfo *TInfo, 2378 LookupResult &Previous, 2379 MultiTemplateParamsArg TemplateParamLists, 2380 bool &AddToScope, 2381 ArrayRef<BindingDecl *> Bindings = None); 2382 NamedDecl * 2383 ActOnDecompositionDeclarator(Scope *S, Declarator &D, 2384 MultiTemplateParamsArg TemplateParamLists); 2385 // Returns true if the variable declaration is a redeclaration 2386 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); 2387 void CheckVariableDeclarationType(VarDecl *NewVD); 2388 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 2389 Expr *Init); 2390 void CheckCompleteVariableDeclaration(VarDecl *VD); 2391 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD); 2392 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); 2393 2394 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, 2395 TypeSourceInfo *TInfo, 2396 LookupResult &Previous, 2397 MultiTemplateParamsArg TemplateParamLists, 2398 bool &AddToScope); 2399 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); 2400 2401 enum class CheckConstexprKind { 2402 /// Diagnose issues that are non-constant or that are extensions. 2403 Diagnose, 2404 /// Identify whether this function satisfies the formal rules for constexpr 2405 /// functions in the current lanugage mode (with no extensions). 2406 CheckValid 2407 }; 2408 2409 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, 2410 CheckConstexprKind Kind); 2411 2412 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); 2413 void FindHiddenVirtualMethods(CXXMethodDecl *MD, 2414 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); 2415 void NoteHiddenVirtualMethods(CXXMethodDecl *MD, 2416 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); 2417 // Returns true if the function declaration is a redeclaration 2418 bool CheckFunctionDeclaration(Scope *S, 2419 FunctionDecl *NewFD, LookupResult &Previous, 2420 bool IsMemberSpecialization); 2421 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl); 2422 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 2423 QualType NewT, QualType OldT); 2424 void CheckMain(FunctionDecl *FD, const DeclSpec &D); 2425 void CheckMSVCRTEntryPoint(FunctionDecl *FD); 2426 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 2427 bool IsDefinition); 2428 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D); 2429 Decl *ActOnParamDeclarator(Scope *S, Declarator &D); 2430 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, 2431 SourceLocation Loc, 2432 QualType T); 2433 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, 2434 SourceLocation NameLoc, IdentifierInfo *Name, 2435 QualType T, TypeSourceInfo *TSInfo, 2436 StorageClass SC); 2437 void ActOnParamDefaultArgument(Decl *param, 2438 SourceLocation EqualLoc, 2439 Expr *defarg); 2440 void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, 2441 SourceLocation ArgLoc); 2442 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc); 2443 ExprResult ConvertParamDefaultArgument(const ParmVarDecl *Param, 2444 Expr *DefaultArg, 2445 SourceLocation EqualLoc); 2446 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, 2447 SourceLocation EqualLoc); 2448 2449 // Contexts where using non-trivial C union types can be disallowed. This is 2450 // passed to err_non_trivial_c_union_in_invalid_context. 2451 enum NonTrivialCUnionContext { 2452 // Function parameter. 2453 NTCUC_FunctionParam, 2454 // Function return. 2455 NTCUC_FunctionReturn, 2456 // Default-initialized object. 2457 NTCUC_DefaultInitializedObject, 2458 // Variable with automatic storage duration. 2459 NTCUC_AutoVar, 2460 // Initializer expression that might copy from another object. 2461 NTCUC_CopyInit, 2462 // Assignment. 2463 NTCUC_Assignment, 2464 // Compound literal. 2465 NTCUC_CompoundLiteral, 2466 // Block capture. 2467 NTCUC_BlockCapture, 2468 // lvalue-to-rvalue conversion of volatile type. 2469 NTCUC_LValueToRValueVolatile, 2470 }; 2471 2472 /// Emit diagnostics if the initializer or any of its explicit or 2473 /// implicitly-generated subexpressions require copying or 2474 /// default-initializing a type that is or contains a C union type that is 2475 /// non-trivial to copy or default-initialize. 2476 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc); 2477 2478 // These flags are passed to checkNonTrivialCUnion. 2479 enum NonTrivialCUnionKind { 2480 NTCUK_Init = 0x1, 2481 NTCUK_Destruct = 0x2, 2482 NTCUK_Copy = 0x4, 2483 }; 2484 2485 /// Emit diagnostics if a non-trivial C union type or a struct that contains 2486 /// a non-trivial C union is used in an invalid context. 2487 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 2488 NonTrivialCUnionContext UseContext, 2489 unsigned NonTrivialKind); 2490 2491 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit); 2492 void ActOnUninitializedDecl(Decl *dcl); 2493 void ActOnInitializerError(Decl *Dcl); 2494 2495 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc); 2496 void ActOnCXXForRangeDecl(Decl *D); 2497 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 2498 IdentifierInfo *Ident, 2499 ParsedAttributes &Attrs, 2500 SourceLocation AttrEnd); 2501 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); 2502 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); 2503 void CheckStaticLocalForDllExport(VarDecl *VD); 2504 void FinalizeDeclaration(Decl *D); 2505 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 2506 ArrayRef<Decl *> Group); 2507 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group); 2508 2509 /// Should be called on all declarations that might have attached 2510 /// documentation comments. 2511 void ActOnDocumentableDecl(Decl *D); 2512 void ActOnDocumentableDecls(ArrayRef<Decl *> Group); 2513 2514 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 2515 SourceLocation LocAfterDecls); 2516 void CheckForFunctionRedefinition( 2517 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr, 2518 SkipBodyInfo *SkipBody = nullptr); 2519 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D, 2520 MultiTemplateParamsArg TemplateParamLists, 2521 SkipBodyInfo *SkipBody = nullptr); 2522 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D, 2523 SkipBodyInfo *SkipBody = nullptr); 2524 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D); 2525 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr); 2526 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); isObjCMethodDecl(Decl * D)2527 bool isObjCMethodDecl(Decl *D) { 2528 return D && isa<ObjCMethodDecl>(D); 2529 } 2530 2531 /// Determine whether we can delay parsing the body of a function or 2532 /// function template until it is used, assuming we don't care about emitting 2533 /// code for that function. 2534 /// 2535 /// This will be \c false if we may need the body of the function in the 2536 /// middle of parsing an expression (where it's impractical to switch to 2537 /// parsing a different function), for instance, if it's constexpr in C++11 2538 /// or has an 'auto' return type in C++14. These cases are essentially bugs. 2539 bool canDelayFunctionBody(const Declarator &D); 2540 2541 /// Determine whether we can skip parsing the body of a function 2542 /// definition, assuming we don't care about analyzing its body or emitting 2543 /// code for that function. 2544 /// 2545 /// This will be \c false only if we may need the body of the function in 2546 /// order to parse the rest of the program (for instance, if it is 2547 /// \c constexpr in C++11 or has an 'auto' return type in C++14). 2548 bool canSkipFunctionBody(Decl *D); 2549 2550 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); 2551 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); 2552 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); 2553 Decl *ActOnSkippedFunctionBody(Decl *Decl); 2554 void ActOnFinishInlineFunctionDef(FunctionDecl *D); 2555 2556 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an 2557 /// attribute for which parsing is delayed. 2558 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); 2559 2560 /// Diagnose any unused parameters in the given sequence of 2561 /// ParmVarDecl pointers. 2562 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters); 2563 2564 /// Diagnose whether the size of parameters or return value of a 2565 /// function or obj-c method definition is pass-by-value and larger than a 2566 /// specified threshold. 2567 void 2568 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters, 2569 QualType ReturnTy, NamedDecl *D); 2570 2571 void DiagnoseInvalidJumps(Stmt *Body); 2572 Decl *ActOnFileScopeAsmDecl(Expr *expr, 2573 SourceLocation AsmLoc, 2574 SourceLocation RParenLoc); 2575 2576 /// Handle a C++11 empty-declaration and attribute-declaration. 2577 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, 2578 SourceLocation SemiLoc); 2579 2580 enum class ModuleDeclKind { 2581 Interface, ///< 'export module X;' 2582 Implementation, ///< 'module X;' 2583 }; 2584 2585 /// The parser has processed a module-declaration that begins the definition 2586 /// of a module interface or implementation. 2587 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, 2588 SourceLocation ModuleLoc, ModuleDeclKind MDK, 2589 ModuleIdPath Path, bool IsFirstDecl); 2590 2591 /// The parser has processed a global-module-fragment declaration that begins 2592 /// the definition of the global module fragment of the current module unit. 2593 /// \param ModuleLoc The location of the 'module' keyword. 2594 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc); 2595 2596 /// The parser has processed a private-module-fragment declaration that begins 2597 /// the definition of the private module fragment of the current module unit. 2598 /// \param ModuleLoc The location of the 'module' keyword. 2599 /// \param PrivateLoc The location of the 'private' keyword. 2600 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, 2601 SourceLocation PrivateLoc); 2602 2603 /// The parser has processed a module import declaration. 2604 /// 2605 /// \param StartLoc The location of the first token in the declaration. This 2606 /// could be the location of an '@', 'export', or 'import'. 2607 /// \param ExportLoc The location of the 'export' keyword, if any. 2608 /// \param ImportLoc The location of the 'import' keyword. 2609 /// \param Path The module access path. 2610 DeclResult ActOnModuleImport(SourceLocation StartLoc, 2611 SourceLocation ExportLoc, 2612 SourceLocation ImportLoc, ModuleIdPath Path); 2613 DeclResult ActOnModuleImport(SourceLocation StartLoc, 2614 SourceLocation ExportLoc, 2615 SourceLocation ImportLoc, Module *M, 2616 ModuleIdPath Path = {}); 2617 2618 /// The parser has processed a module import translated from a 2619 /// #include or similar preprocessing directive. 2620 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod); 2621 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod); 2622 2623 /// The parsed has entered a submodule. 2624 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod); 2625 /// The parser has left a submodule. 2626 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod); 2627 2628 /// Create an implicit import of the given module at the given 2629 /// source location, for error recovery, if possible. 2630 /// 2631 /// This routine is typically used when an entity found by name lookup 2632 /// is actually hidden within a module that we know about but the user 2633 /// has forgotten to import. 2634 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 2635 Module *Mod); 2636 2637 /// Kinds of missing import. Note, the values of these enumerators correspond 2638 /// to %select values in diagnostics. 2639 enum class MissingImportKind { 2640 Declaration, 2641 Definition, 2642 DefaultArgument, 2643 ExplicitSpecialization, 2644 PartialSpecialization 2645 }; 2646 2647 /// Diagnose that the specified declaration needs to be visible but 2648 /// isn't, and suggest a module import that would resolve the problem. 2649 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, 2650 MissingImportKind MIK, bool Recover = true); 2651 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, 2652 SourceLocation DeclLoc, ArrayRef<Module *> Modules, 2653 MissingImportKind MIK, bool Recover); 2654 2655 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 2656 SourceLocation LBraceLoc); 2657 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, 2658 SourceLocation RBraceLoc); 2659 2660 /// We've found a use of a templated declaration that would trigger an 2661 /// implicit instantiation. Check that any relevant explicit specializations 2662 /// and partial specializations are visible, and diagnose if not. 2663 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); 2664 2665 /// We've found a use of a template specialization that would select a 2666 /// partial specialization. Check that the partial specialization is visible, 2667 /// and diagnose if not. 2668 void checkPartialSpecializationVisibility(SourceLocation Loc, 2669 NamedDecl *Spec); 2670 2671 /// Retrieve a suitable printing policy for diagnostics. getPrintingPolicy()2672 PrintingPolicy getPrintingPolicy() const { 2673 return getPrintingPolicy(Context, PP); 2674 } 2675 2676 /// Retrieve a suitable printing policy for diagnostics. 2677 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, 2678 const Preprocessor &PP); 2679 2680 /// Scope actions. 2681 void ActOnPopScope(SourceLocation Loc, Scope *S); 2682 void ActOnTranslationUnitScope(Scope *S); 2683 2684 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 2685 RecordDecl *&AnonRecord); 2686 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 2687 MultiTemplateParamsArg TemplateParams, 2688 bool IsExplicitInstantiation, 2689 RecordDecl *&AnonRecord); 2690 2691 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 2692 AccessSpecifier AS, 2693 RecordDecl *Record, 2694 const PrintingPolicy &Policy); 2695 2696 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 2697 RecordDecl *Record); 2698 2699 /// Common ways to introduce type names without a tag for use in diagnostics. 2700 /// Keep in sync with err_tag_reference_non_tag. 2701 enum NonTagKind { 2702 NTK_NonStruct, 2703 NTK_NonClass, 2704 NTK_NonUnion, 2705 NTK_NonEnum, 2706 NTK_Typedef, 2707 NTK_TypeAlias, 2708 NTK_Template, 2709 NTK_TypeAliasTemplate, 2710 NTK_TemplateTemplateArgument, 2711 }; 2712 2713 /// Given a non-tag type declaration, returns an enum useful for indicating 2714 /// what kind of non-tag type this is. 2715 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK); 2716 2717 bool isAcceptableTagRedeclaration(const TagDecl *Previous, 2718 TagTypeKind NewTag, bool isDefinition, 2719 SourceLocation NewTagLoc, 2720 const IdentifierInfo *Name); 2721 2722 enum TagUseKind { 2723 TUK_Reference, // Reference to a tag: 'struct foo *X;' 2724 TUK_Declaration, // Fwd decl of a tag: 'struct foo;' 2725 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' 2726 TUK_Friend // Friend declaration: 'friend struct foo;' 2727 }; 2728 2729 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 2730 SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, 2731 SourceLocation NameLoc, const ParsedAttributesView &Attr, 2732 AccessSpecifier AS, SourceLocation ModulePrivateLoc, 2733 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, 2734 bool &IsDependent, SourceLocation ScopedEnumKWLoc, 2735 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 2736 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 2737 SkipBodyInfo *SkipBody = nullptr); 2738 2739 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 2740 unsigned TagSpec, SourceLocation TagLoc, 2741 CXXScopeSpec &SS, IdentifierInfo *Name, 2742 SourceLocation NameLoc, 2743 const ParsedAttributesView &Attr, 2744 MultiTemplateParamsArg TempParamLists); 2745 2746 TypeResult ActOnDependentTag(Scope *S, 2747 unsigned TagSpec, 2748 TagUseKind TUK, 2749 const CXXScopeSpec &SS, 2750 IdentifierInfo *Name, 2751 SourceLocation TagLoc, 2752 SourceLocation NameLoc); 2753 2754 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, 2755 IdentifierInfo *ClassName, 2756 SmallVectorImpl<Decl *> &Decls); 2757 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 2758 Declarator &D, Expr *BitfieldWidth); 2759 2760 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, 2761 Declarator &D, Expr *BitfieldWidth, 2762 InClassInitStyle InitStyle, 2763 AccessSpecifier AS); 2764 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, 2765 SourceLocation DeclStart, Declarator &D, 2766 Expr *BitfieldWidth, 2767 InClassInitStyle InitStyle, 2768 AccessSpecifier AS, 2769 const ParsedAttr &MSPropertyAttr); 2770 2771 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, 2772 TypeSourceInfo *TInfo, 2773 RecordDecl *Record, SourceLocation Loc, 2774 bool Mutable, Expr *BitfieldWidth, 2775 InClassInitStyle InitStyle, 2776 SourceLocation TSSL, 2777 AccessSpecifier AS, NamedDecl *PrevDecl, 2778 Declarator *D = nullptr); 2779 2780 bool CheckNontrivialField(FieldDecl *FD); 2781 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM); 2782 2783 enum TrivialABIHandling { 2784 /// The triviality of a method unaffected by "trivial_abi". 2785 TAH_IgnoreTrivialABI, 2786 2787 /// The triviality of a method affected by "trivial_abi". 2788 TAH_ConsiderTrivialABI 2789 }; 2790 2791 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 2792 TrivialABIHandling TAH = TAH_IgnoreTrivialABI, 2793 bool Diagnose = false); 2794 2795 /// For a defaulted function, the kind of defaulted function that it is. 2796 class DefaultedFunctionKind { 2797 CXXSpecialMember SpecialMember : 8; 2798 DefaultedComparisonKind Comparison : 8; 2799 2800 public: DefaultedFunctionKind()2801 DefaultedFunctionKind() 2802 : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) { 2803 } DefaultedFunctionKind(CXXSpecialMember CSM)2804 DefaultedFunctionKind(CXXSpecialMember CSM) 2805 : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {} DefaultedFunctionKind(DefaultedComparisonKind Comp)2806 DefaultedFunctionKind(DefaultedComparisonKind Comp) 2807 : SpecialMember(CXXInvalid), Comparison(Comp) {} 2808 isSpecialMember()2809 bool isSpecialMember() const { return SpecialMember != CXXInvalid; } isComparison()2810 bool isComparison() const { 2811 return Comparison != DefaultedComparisonKind::None; 2812 } 2813 2814 explicit operator bool() const { 2815 return isSpecialMember() || isComparison(); 2816 } 2817 asSpecialMember()2818 CXXSpecialMember asSpecialMember() const { return SpecialMember; } asComparison()2819 DefaultedComparisonKind asComparison() const { return Comparison; } 2820 2821 /// Get the index of this function kind for use in diagnostics. getDiagnosticIndex()2822 unsigned getDiagnosticIndex() const { 2823 static_assert(CXXInvalid > CXXDestructor, 2824 "invalid should have highest index"); 2825 static_assert((unsigned)DefaultedComparisonKind::None == 0, 2826 "none should be equal to zero"); 2827 return SpecialMember + (unsigned)Comparison; 2828 } 2829 }; 2830 2831 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD); 2832 getSpecialMember(const CXXMethodDecl * MD)2833 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) { 2834 return getDefaultedFunctionKind(MD).asSpecialMember(); 2835 } getDefaultedComparisonKind(const FunctionDecl * FD)2836 DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) { 2837 return getDefaultedFunctionKind(FD).asComparison(); 2838 } 2839 2840 void ActOnLastBitfield(SourceLocation DeclStart, 2841 SmallVectorImpl<Decl *> &AllIvarDecls); 2842 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, 2843 Declarator &D, Expr *BitfieldWidth, 2844 tok::ObjCKeywordKind visibility); 2845 2846 // This is used for both record definitions and ObjC interface declarations. 2847 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, 2848 ArrayRef<Decl *> Fields, SourceLocation LBrac, 2849 SourceLocation RBrac, const ParsedAttributesView &AttrList); 2850 2851 /// ActOnTagStartDefinition - Invoked when we have entered the 2852 /// scope of a tag's definition (e.g., for an enumeration, class, 2853 /// struct, or union). 2854 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); 2855 2856 /// Perform ODR-like check for C/ObjC when merging tag types from modules. 2857 /// Differently from C++, actually parse the body and reject / error out 2858 /// in case of a structural mismatch. 2859 bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 2860 SkipBodyInfo &SkipBody); 2861 2862 typedef void *SkippedDefinitionContext; 2863 2864 /// Invoked when we enter a tag definition that we're skipping. 2865 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD); 2866 2867 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl); 2868 2869 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a 2870 /// C++ record definition's base-specifiers clause and are starting its 2871 /// member declarations. 2872 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, 2873 SourceLocation FinalLoc, 2874 bool IsFinalSpelledSealed, 2875 SourceLocation LBraceLoc); 2876 2877 /// ActOnTagFinishDefinition - Invoked once we have finished parsing 2878 /// the definition of a tag (enumeration, class, struct, or union). 2879 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, 2880 SourceRange BraceRange); 2881 2882 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context); 2883 2884 void ActOnObjCContainerFinishDefinition(); 2885 2886 /// Invoked when we must temporarily exit the objective-c container 2887 /// scope for parsing/looking-up C constructs. 2888 /// 2889 /// Must be followed by a call to \see ActOnObjCReenterContainerContext 2890 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC); 2891 void ActOnObjCReenterContainerContext(DeclContext *DC); 2892 2893 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable 2894 /// error parsing the definition of a tag. 2895 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); 2896 2897 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, 2898 EnumConstantDecl *LastEnumConst, 2899 SourceLocation IdLoc, 2900 IdentifierInfo *Id, 2901 Expr *val); 2902 bool CheckEnumUnderlyingType(TypeSourceInfo *TI); 2903 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 2904 QualType EnumUnderlyingTy, bool IsFixed, 2905 const EnumDecl *Prev); 2906 2907 /// Determine whether the body of an anonymous enumeration should be skipped. 2908 /// \param II The name of the first enumerator. 2909 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 2910 SourceLocation IILoc); 2911 2912 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, 2913 SourceLocation IdLoc, IdentifierInfo *Id, 2914 const ParsedAttributesView &Attrs, 2915 SourceLocation EqualLoc, Expr *Val); 2916 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 2917 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S, 2918 const ParsedAttributesView &Attr); 2919 2920 /// Set the current declaration context until it gets popped. 2921 void PushDeclContext(Scope *S, DeclContext *DC); 2922 void PopDeclContext(); 2923 2924 /// EnterDeclaratorContext - Used when we must lookup names in the context 2925 /// of a declarator's nested name specifier. 2926 void EnterDeclaratorContext(Scope *S, DeclContext *DC); 2927 void ExitDeclaratorContext(Scope *S); 2928 2929 /// Enter a template parameter scope, after it's been associated with a particular 2930 /// DeclContext. Causes lookup within the scope to chain through enclosing contexts 2931 /// in the correct order. 2932 void EnterTemplatedContext(Scope *S, DeclContext *DC); 2933 2934 /// Push the parameters of D, which must be a function, into scope. 2935 void ActOnReenterFunctionContext(Scope* S, Decl* D); 2936 void ActOnExitFunctionContext(); 2937 2938 DeclContext *getFunctionLevelDeclContext(); 2939 2940 /// getCurFunctionDecl - If inside of a function body, this returns a pointer 2941 /// to the function decl for the function being parsed. If we're currently 2942 /// in a 'block', this returns the containing context. 2943 FunctionDecl *getCurFunctionDecl(); 2944 2945 /// getCurMethodDecl - If inside of a method body, this returns a pointer to 2946 /// the method decl for the method being parsed. If we're currently 2947 /// in a 'block', this returns the containing context. 2948 ObjCMethodDecl *getCurMethodDecl(); 2949 2950 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method 2951 /// or C function we're in, otherwise return null. If we're currently 2952 /// in a 'block', this returns the containing context. 2953 NamedDecl *getCurFunctionOrMethodDecl(); 2954 2955 /// Add this decl to the scope shadowed decl chains. 2956 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); 2957 2958 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true 2959 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns 2960 /// true if 'D' belongs to the given declaration context. 2961 /// 2962 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the 2963 /// enclosing namespace set of the context, rather than contained 2964 /// directly within it. 2965 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr, 2966 bool AllowInlineNamespace = false); 2967 2968 /// Finds the scope corresponding to the given decl context, if it 2969 /// happens to be an enclosing scope. Otherwise return NULL. 2970 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); 2971 2972 /// Subroutines of ActOnDeclarator(). 2973 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 2974 TypeSourceInfo *TInfo); 2975 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New); 2976 2977 /// Describes the kind of merge to perform for availability 2978 /// attributes (including "deprecated", "unavailable", and "availability"). 2979 enum AvailabilityMergeKind { 2980 /// Don't merge availability attributes at all. 2981 AMK_None, 2982 /// Merge availability attributes for a redeclaration, which requires 2983 /// an exact match. 2984 AMK_Redeclaration, 2985 /// Merge availability attributes for an override, which requires 2986 /// an exact match or a weakening of constraints. 2987 AMK_Override, 2988 /// Merge availability attributes for an implementation of 2989 /// a protocol requirement. 2990 AMK_ProtocolImplementation, 2991 }; 2992 2993 /// Describes the kind of priority given to an availability attribute. 2994 /// 2995 /// The sum of priorities deteremines the final priority of the attribute. 2996 /// The final priority determines how the attribute will be merged. 2997 /// An attribute with a lower priority will always remove higher priority 2998 /// attributes for the specified platform when it is being applied. An 2999 /// attribute with a higher priority will not be applied if the declaration 3000 /// already has an availability attribute with a lower priority for the 3001 /// specified platform. The final prirority values are not expected to match 3002 /// the values in this enumeration, but instead should be treated as a plain 3003 /// integer value. This enumeration just names the priority weights that are 3004 /// used to calculate that final vaue. 3005 enum AvailabilityPriority : int { 3006 /// The availability attribute was specified explicitly next to the 3007 /// declaration. 3008 AP_Explicit = 0, 3009 3010 /// The availability attribute was applied using '#pragma clang attribute'. 3011 AP_PragmaClangAttribute = 1, 3012 3013 /// The availability attribute for a specific platform was inferred from 3014 /// an availability attribute for another platform. 3015 AP_InferredFromOtherPlatform = 2 3016 }; 3017 3018 /// Attribute merging methods. Return true if a new attribute was added. 3019 AvailabilityAttr * 3020 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, 3021 IdentifierInfo *Platform, bool Implicit, 3022 VersionTuple Introduced, VersionTuple Deprecated, 3023 VersionTuple Obsoleted, bool IsUnavailable, 3024 StringRef Message, bool IsStrict, StringRef Replacement, 3025 AvailabilityMergeKind AMK, int Priority); 3026 TypeVisibilityAttr * 3027 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, 3028 TypeVisibilityAttr::VisibilityType Vis); 3029 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, 3030 VisibilityAttr::VisibilityType Vis); 3031 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, 3032 StringRef UuidAsWritten, MSGuidDecl *GuidDecl); 3033 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI); 3034 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI); 3035 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D, 3036 const AttributeCommonInfo &CI, 3037 bool BestCase, 3038 MSInheritanceModel Model); 3039 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, 3040 IdentifierInfo *Format, int FormatIdx, 3041 int FirstArg); 3042 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, 3043 StringRef Name); 3044 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, 3045 StringRef Name); 3046 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, 3047 const AttributeCommonInfo &CI, 3048 const IdentifierInfo *Ident); 3049 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI); 3050 NoSpeculativeLoadHardeningAttr * 3051 mergeNoSpeculativeLoadHardeningAttr(Decl *D, 3052 const NoSpeculativeLoadHardeningAttr &AL); 3053 SpeculativeLoadHardeningAttr * 3054 mergeSpeculativeLoadHardeningAttr(Decl *D, 3055 const SpeculativeLoadHardeningAttr &AL); 3056 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, 3057 const AttributeCommonInfo &CI); 3058 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL); 3059 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, 3060 const InternalLinkageAttr &AL); 3061 CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL); 3062 CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL); 3063 WebAssemblyImportNameAttr *mergeImportNameAttr( 3064 Decl *D, const WebAssemblyImportNameAttr &AL); 3065 WebAssemblyImportModuleAttr *mergeImportModuleAttr( 3066 Decl *D, const WebAssemblyImportModuleAttr &AL); 3067 3068 void mergeDeclAttributes(NamedDecl *New, Decl *Old, 3069 AvailabilityMergeKind AMK = AMK_Redeclaration); 3070 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 3071 LookupResult &OldDecls); 3072 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, 3073 bool MergeTypeWithOld); 3074 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3075 Scope *S, bool MergeTypeWithOld); 3076 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); 3077 void MergeVarDecl(VarDecl *New, LookupResult &Previous); 3078 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld); 3079 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); 3080 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn); 3081 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New); 3082 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); 3083 3084 // AssignmentAction - This is used by all the assignment diagnostic functions 3085 // to represent what is actually causing the operation 3086 enum AssignmentAction { 3087 AA_Assigning, 3088 AA_Passing, 3089 AA_Returning, 3090 AA_Converting, 3091 AA_Initializing, 3092 AA_Sending, 3093 AA_Casting, 3094 AA_Passing_CFAudited 3095 }; 3096 3097 /// C++ Overloading. 3098 enum OverloadKind { 3099 /// This is a legitimate overload: the existing declarations are 3100 /// functions or function templates with different signatures. 3101 Ovl_Overload, 3102 3103 /// This is not an overload because the signature exactly matches 3104 /// an existing declaration. 3105 Ovl_Match, 3106 3107 /// This is not an overload because the lookup results contain a 3108 /// non-function. 3109 Ovl_NonFunction 3110 }; 3111 OverloadKind CheckOverload(Scope *S, 3112 FunctionDecl *New, 3113 const LookupResult &OldDecls, 3114 NamedDecl *&OldDecl, 3115 bool IsForUsingDecl); 3116 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl, 3117 bool ConsiderCudaAttrs = true, 3118 bool ConsiderRequiresClauses = true); 3119 3120 enum class AllowedExplicit { 3121 /// Allow no explicit functions to be used. 3122 None, 3123 /// Allow explicit conversion functions but not explicit constructors. 3124 Conversions, 3125 /// Allow both explicit conversion functions and explicit constructors. 3126 All 3127 }; 3128 3129 ImplicitConversionSequence 3130 TryImplicitConversion(Expr *From, QualType ToType, 3131 bool SuppressUserConversions, 3132 AllowedExplicit AllowExplicit, 3133 bool InOverloadResolution, 3134 bool CStyle, 3135 bool AllowObjCWritebackConversion); 3136 3137 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); 3138 bool IsFloatingPointPromotion(QualType FromType, QualType ToType); 3139 bool IsComplexPromotion(QualType FromType, QualType ToType); 3140 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 3141 bool InOverloadResolution, 3142 QualType& ConvertedType, bool &IncompatibleObjC); 3143 bool isObjCPointerConversion(QualType FromType, QualType ToType, 3144 QualType& ConvertedType, bool &IncompatibleObjC); 3145 bool isObjCWritebackConversion(QualType FromType, QualType ToType, 3146 QualType &ConvertedType); 3147 bool IsBlockPointerConversion(QualType FromType, QualType ToType, 3148 QualType& ConvertedType); 3149 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 3150 const FunctionProtoType *NewType, 3151 unsigned *ArgPos = nullptr); 3152 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 3153 QualType FromType, QualType ToType); 3154 3155 void maybeExtendBlockObject(ExprResult &E); 3156 CastKind PrepareCastToObjCObjectPointer(ExprResult &E); 3157 bool CheckPointerConversion(Expr *From, QualType ToType, 3158 CastKind &Kind, 3159 CXXCastPath& BasePath, 3160 bool IgnoreBaseAccess, 3161 bool Diagnose = true); 3162 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, 3163 bool InOverloadResolution, 3164 QualType &ConvertedType); 3165 bool CheckMemberPointerConversion(Expr *From, QualType ToType, 3166 CastKind &Kind, 3167 CXXCastPath &BasePath, 3168 bool IgnoreBaseAccess); 3169 bool IsQualificationConversion(QualType FromType, QualType ToType, 3170 bool CStyle, bool &ObjCLifetimeConversion); 3171 bool IsFunctionConversion(QualType FromType, QualType ToType, 3172 QualType &ResultTy); 3173 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); 3174 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg); 3175 3176 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, 3177 const VarDecl *NRVOCandidate, 3178 QualType ResultType, 3179 Expr *Value, 3180 bool AllowNRVO = true); 3181 3182 bool CanPerformAggregateInitializationForOverloadResolution( 3183 const InitializedEntity &Entity, InitListExpr *From); 3184 3185 bool CanPerformCopyInitialization(const InitializedEntity &Entity, 3186 ExprResult Init); 3187 ExprResult PerformCopyInitialization(const InitializedEntity &Entity, 3188 SourceLocation EqualLoc, 3189 ExprResult Init, 3190 bool TopLevelOfInitList = false, 3191 bool AllowExplicit = false); 3192 ExprResult PerformObjectArgumentInitialization(Expr *From, 3193 NestedNameSpecifier *Qualifier, 3194 NamedDecl *FoundDecl, 3195 CXXMethodDecl *Method); 3196 3197 /// Check that the lifetime of the initializer (and its subobjects) is 3198 /// sufficient for initializing the entity, and perform lifetime extension 3199 /// (when permitted) if not. 3200 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init); 3201 3202 ExprResult PerformContextuallyConvertToBool(Expr *From); 3203 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); 3204 3205 /// Contexts in which a converted constant expression is required. 3206 enum CCEKind { 3207 CCEK_CaseValue, ///< Expression in a case label. 3208 CCEK_Enumerator, ///< Enumerator value with fixed underlying type. 3209 CCEK_TemplateArg, ///< Value of a non-type template parameter. 3210 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator. 3211 CCEK_ConstexprIf, ///< Condition in a constexpr if statement. 3212 CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier. 3213 }; 3214 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, 3215 llvm::APSInt &Value, CCEKind CCE); 3216 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, 3217 APValue &Value, CCEKind CCE); 3218 3219 /// Abstract base class used to perform a contextual implicit 3220 /// conversion from an expression to any type passing a filter. 3221 class ContextualImplicitConverter { 3222 public: 3223 bool Suppress; 3224 bool SuppressConversion; 3225 3226 ContextualImplicitConverter(bool Suppress = false, 3227 bool SuppressConversion = false) Suppress(Suppress)3228 : Suppress(Suppress), SuppressConversion(SuppressConversion) {} 3229 3230 /// Determine whether the specified type is a valid destination type 3231 /// for this conversion. 3232 virtual bool match(QualType T) = 0; 3233 3234 /// Emits a diagnostic complaining that the expression does not have 3235 /// integral or enumeration type. 3236 virtual SemaDiagnosticBuilder 3237 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0; 3238 3239 /// Emits a diagnostic when the expression has incomplete class type. 3240 virtual SemaDiagnosticBuilder 3241 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; 3242 3243 /// Emits a diagnostic when the only matching conversion function 3244 /// is explicit. 3245 virtual SemaDiagnosticBuilder diagnoseExplicitConv( 3246 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; 3247 3248 /// Emits a note for the explicit conversion function. 3249 virtual SemaDiagnosticBuilder 3250 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; 3251 3252 /// Emits a diagnostic when there are multiple possible conversion 3253 /// functions. 3254 virtual SemaDiagnosticBuilder 3255 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0; 3256 3257 /// Emits a note for one of the candidate conversions. 3258 virtual SemaDiagnosticBuilder 3259 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; 3260 3261 /// Emits a diagnostic when we picked a conversion function 3262 /// (for cases when we are not allowed to pick a conversion function). 3263 virtual SemaDiagnosticBuilder diagnoseConversion( 3264 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; 3265 ~ContextualImplicitConverter()3266 virtual ~ContextualImplicitConverter() {} 3267 }; 3268 3269 class ICEConvertDiagnoser : public ContextualImplicitConverter { 3270 bool AllowScopedEnumerations; 3271 3272 public: ICEConvertDiagnoser(bool AllowScopedEnumerations,bool Suppress,bool SuppressConversion)3273 ICEConvertDiagnoser(bool AllowScopedEnumerations, 3274 bool Suppress, bool SuppressConversion) 3275 : ContextualImplicitConverter(Suppress, SuppressConversion), 3276 AllowScopedEnumerations(AllowScopedEnumerations) {} 3277 3278 /// Match an integral or (possibly scoped) enumeration type. 3279 bool match(QualType T) override; 3280 3281 SemaDiagnosticBuilder diagnoseNoMatch(Sema & S,SourceLocation Loc,QualType T)3282 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override { 3283 return diagnoseNotInt(S, Loc, T); 3284 } 3285 3286 /// Emits a diagnostic complaining that the expression does not have 3287 /// integral or enumeration type. 3288 virtual SemaDiagnosticBuilder 3289 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0; 3290 }; 3291 3292 /// Perform a contextual implicit conversion. 3293 ExprResult PerformContextualImplicitConversion( 3294 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter); 3295 3296 3297 enum ObjCSubscriptKind { 3298 OS_Array, 3299 OS_Dictionary, 3300 OS_Error 3301 }; 3302 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); 3303 3304 // Note that LK_String is intentionally after the other literals, as 3305 // this is used for diagnostics logic. 3306 enum ObjCLiteralKind { 3307 LK_Array, 3308 LK_Dictionary, 3309 LK_Numeric, 3310 LK_Boxed, 3311 LK_String, 3312 LK_Block, 3313 LK_None 3314 }; 3315 ObjCLiteralKind CheckLiteralKind(Expr *FromE); 3316 3317 ExprResult PerformObjectMemberConversion(Expr *From, 3318 NestedNameSpecifier *Qualifier, 3319 NamedDecl *FoundDecl, 3320 NamedDecl *Member); 3321 3322 // Members have to be NamespaceDecl* or TranslationUnitDecl*. 3323 // TODO: make this is a typesafe union. 3324 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet; 3325 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet; 3326 3327 using ADLCallKind = CallExpr::ADLCallKind; 3328 3329 void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, 3330 ArrayRef<Expr *> Args, 3331 OverloadCandidateSet &CandidateSet, 3332 bool SuppressUserConversions = false, 3333 bool PartialOverloading = false, 3334 bool AllowExplicit = true, 3335 bool AllowExplicitConversion = false, 3336 ADLCallKind IsADLCandidate = ADLCallKind::NotADL, 3337 ConversionSequenceList EarlyConversions = None, 3338 OverloadCandidateParamOrder PO = {}); 3339 void AddFunctionCandidates(const UnresolvedSetImpl &Functions, 3340 ArrayRef<Expr *> Args, 3341 OverloadCandidateSet &CandidateSet, 3342 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, 3343 bool SuppressUserConversions = false, 3344 bool PartialOverloading = false, 3345 bool FirstArgumentIsBase = false); 3346 void AddMethodCandidate(DeclAccessPair FoundDecl, 3347 QualType ObjectType, 3348 Expr::Classification ObjectClassification, 3349 ArrayRef<Expr *> Args, 3350 OverloadCandidateSet& CandidateSet, 3351 bool SuppressUserConversion = false, 3352 OverloadCandidateParamOrder PO = {}); 3353 void AddMethodCandidate(CXXMethodDecl *Method, 3354 DeclAccessPair FoundDecl, 3355 CXXRecordDecl *ActingContext, QualType ObjectType, 3356 Expr::Classification ObjectClassification, 3357 ArrayRef<Expr *> Args, 3358 OverloadCandidateSet& CandidateSet, 3359 bool SuppressUserConversions = false, 3360 bool PartialOverloading = false, 3361 ConversionSequenceList EarlyConversions = None, 3362 OverloadCandidateParamOrder PO = {}); 3363 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 3364 DeclAccessPair FoundDecl, 3365 CXXRecordDecl *ActingContext, 3366 TemplateArgumentListInfo *ExplicitTemplateArgs, 3367 QualType ObjectType, 3368 Expr::Classification ObjectClassification, 3369 ArrayRef<Expr *> Args, 3370 OverloadCandidateSet& CandidateSet, 3371 bool SuppressUserConversions = false, 3372 bool PartialOverloading = false, 3373 OverloadCandidateParamOrder PO = {}); 3374 void AddTemplateOverloadCandidate( 3375 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 3376 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 3377 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, 3378 bool PartialOverloading = false, bool AllowExplicit = true, 3379 ADLCallKind IsADLCandidate = ADLCallKind::NotADL, 3380 OverloadCandidateParamOrder PO = {}); 3381 bool CheckNonDependentConversions( 3382 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 3383 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 3384 ConversionSequenceList &Conversions, bool SuppressUserConversions, 3385 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(), 3386 Expr::Classification ObjectClassification = {}, 3387 OverloadCandidateParamOrder PO = {}); 3388 void AddConversionCandidate( 3389 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 3390 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 3391 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 3392 bool AllowExplicit, bool AllowResultConversion = true); 3393 void AddTemplateConversionCandidate( 3394 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 3395 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 3396 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 3397 bool AllowExplicit, bool AllowResultConversion = true); 3398 void AddSurrogateCandidate(CXXConversionDecl *Conversion, 3399 DeclAccessPair FoundDecl, 3400 CXXRecordDecl *ActingContext, 3401 const FunctionProtoType *Proto, 3402 Expr *Object, ArrayRef<Expr *> Args, 3403 OverloadCandidateSet& CandidateSet); 3404 void AddNonMemberOperatorCandidates( 3405 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, 3406 OverloadCandidateSet &CandidateSet, 3407 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); 3408 void AddMemberOperatorCandidates(OverloadedOperatorKind Op, 3409 SourceLocation OpLoc, ArrayRef<Expr *> Args, 3410 OverloadCandidateSet &CandidateSet, 3411 OverloadCandidateParamOrder PO = {}); 3412 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 3413 OverloadCandidateSet& CandidateSet, 3414 bool IsAssignmentOperator = false, 3415 unsigned NumContextualBoolArguments = 0); 3416 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 3417 SourceLocation OpLoc, ArrayRef<Expr *> Args, 3418 OverloadCandidateSet& CandidateSet); 3419 void AddArgumentDependentLookupCandidates(DeclarationName Name, 3420 SourceLocation Loc, 3421 ArrayRef<Expr *> Args, 3422 TemplateArgumentListInfo *ExplicitTemplateArgs, 3423 OverloadCandidateSet& CandidateSet, 3424 bool PartialOverloading = false); 3425 3426 // Emit as a 'note' the specific overload candidate 3427 void NoteOverloadCandidate( 3428 NamedDecl *Found, FunctionDecl *Fn, 3429 OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(), 3430 QualType DestType = QualType(), bool TakingAddress = false); 3431 3432 // Emit as a series of 'note's all template and non-templates identified by 3433 // the expression Expr 3434 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(), 3435 bool TakingAddress = false); 3436 3437 /// Check the enable_if expressions on the given function. Returns the first 3438 /// failing attribute, or NULL if they were all successful. 3439 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, 3440 ArrayRef<Expr *> Args, 3441 bool MissingImplicitThis = false); 3442 3443 /// Find the failed Boolean condition within a given Boolean 3444 /// constant expression, and describe it with a string. 3445 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond); 3446 3447 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any 3448 /// non-ArgDependent DiagnoseIfAttrs. 3449 /// 3450 /// Argument-dependent diagnose_if attributes should be checked each time a 3451 /// function is used as a direct callee of a function call. 3452 /// 3453 /// Returns true if any errors were emitted. 3454 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 3455 const Expr *ThisArg, 3456 ArrayRef<const Expr *> Args, 3457 SourceLocation Loc); 3458 3459 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any 3460 /// ArgDependent DiagnoseIfAttrs. 3461 /// 3462 /// Argument-independent diagnose_if attributes should be checked on every use 3463 /// of a function. 3464 /// 3465 /// Returns true if any errors were emitted. 3466 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 3467 SourceLocation Loc); 3468 3469 /// Returns whether the given function's address can be taken or not, 3470 /// optionally emitting a diagnostic if the address can't be taken. 3471 /// 3472 /// Returns false if taking the address of the function is illegal. 3473 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 3474 bool Complain = false, 3475 SourceLocation Loc = SourceLocation()); 3476 3477 // [PossiblyAFunctionType] --> [Return] 3478 // NonFunctionType --> NonFunctionType 3479 // R (A) --> R(A) 3480 // R (*)(A) --> R (A) 3481 // R (&)(A) --> R (A) 3482 // R (S::*)(A) --> R (A) 3483 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); 3484 3485 FunctionDecl * 3486 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 3487 QualType TargetType, 3488 bool Complain, 3489 DeclAccessPair &Found, 3490 bool *pHadMultipleCandidates = nullptr); 3491 3492 FunctionDecl * 3493 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult); 3494 3495 bool resolveAndFixAddressOfSingleOverloadCandidate( 3496 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false); 3497 3498 FunctionDecl * 3499 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 3500 bool Complain = false, 3501 DeclAccessPair *Found = nullptr); 3502 3503 bool ResolveAndFixSingleFunctionTemplateSpecialization( 3504 ExprResult &SrcExpr, 3505 bool DoFunctionPointerConverion = false, 3506 bool Complain = false, 3507 SourceRange OpRangeForComplaining = SourceRange(), 3508 QualType DestTypeForComplaining = QualType(), 3509 unsigned DiagIDForComplaining = 0); 3510 3511 3512 Expr *FixOverloadedFunctionReference(Expr *E, 3513 DeclAccessPair FoundDecl, 3514 FunctionDecl *Fn); 3515 ExprResult FixOverloadedFunctionReference(ExprResult, 3516 DeclAccessPair FoundDecl, 3517 FunctionDecl *Fn); 3518 3519 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 3520 ArrayRef<Expr *> Args, 3521 OverloadCandidateSet &CandidateSet, 3522 bool PartialOverloading = false); 3523 3524 // An enum used to represent the different possible results of building a 3525 // range-based for loop. 3526 enum ForRangeStatus { 3527 FRS_Success, 3528 FRS_NoViableFunction, 3529 FRS_DiagnosticIssued 3530 }; 3531 3532 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, 3533 SourceLocation RangeLoc, 3534 const DeclarationNameInfo &NameInfo, 3535 LookupResult &MemberLookup, 3536 OverloadCandidateSet *CandidateSet, 3537 Expr *Range, ExprResult *CallExpr); 3538 3539 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, 3540 UnresolvedLookupExpr *ULE, 3541 SourceLocation LParenLoc, 3542 MultiExprArg Args, 3543 SourceLocation RParenLoc, 3544 Expr *ExecConfig, 3545 bool AllowTypoCorrection=true, 3546 bool CalleesAddressIsTaken=false); 3547 3548 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, 3549 MultiExprArg Args, SourceLocation RParenLoc, 3550 OverloadCandidateSet *CandidateSet, 3551 ExprResult *Result); 3552 3553 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, 3554 UnaryOperatorKind Opc, 3555 const UnresolvedSetImpl &Fns, 3556 Expr *input, bool RequiresADL = true); 3557 3558 void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 3559 OverloadedOperatorKind Op, 3560 const UnresolvedSetImpl &Fns, 3561 ArrayRef<Expr *> Args, bool RequiresADL = true); 3562 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, 3563 BinaryOperatorKind Opc, 3564 const UnresolvedSetImpl &Fns, 3565 Expr *LHS, Expr *RHS, 3566 bool RequiresADL = true, 3567 bool AllowRewrittenCandidates = true, 3568 FunctionDecl *DefaultedFn = nullptr); 3569 ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, 3570 const UnresolvedSetImpl &Fns, 3571 Expr *LHS, Expr *RHS, 3572 FunctionDecl *DefaultedFn); 3573 3574 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 3575 SourceLocation RLoc, 3576 Expr *Base,Expr *Idx); 3577 3578 ExprResult 3579 BuildCallToMemberFunction(Scope *S, Expr *MemExpr, 3580 SourceLocation LParenLoc, 3581 MultiExprArg Args, 3582 SourceLocation RParenLoc); 3583 ExprResult 3584 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, 3585 MultiExprArg Args, 3586 SourceLocation RParenLoc); 3587 3588 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, 3589 SourceLocation OpLoc, 3590 bool *NoArrowOperatorFound = nullptr); 3591 3592 /// CheckCallReturnType - Checks that a call expression's return type is 3593 /// complete. Returns true on failure. The location passed in is the location 3594 /// that best represents the call. 3595 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 3596 CallExpr *CE, FunctionDecl *FD); 3597 3598 /// Helpers for dealing with blocks and functions. 3599 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 3600 bool CheckParameterNames); 3601 void CheckCXXDefaultArguments(FunctionDecl *FD); 3602 void CheckExtraCXXDefaultArguments(Declarator &D); 3603 Scope *getNonFieldDeclScope(Scope *S); 3604 3605 /// \name Name lookup 3606 /// 3607 /// These routines provide name lookup that is used during semantic 3608 /// analysis to resolve the various kinds of names (identifiers, 3609 /// overloaded operator names, constructor names, etc.) into zero or 3610 /// more declarations within a particular scope. The major entry 3611 /// points are LookupName, which performs unqualified name lookup, 3612 /// and LookupQualifiedName, which performs qualified name lookup. 3613 /// 3614 /// All name lookup is performed based on some specific criteria, 3615 /// which specify what names will be visible to name lookup and how 3616 /// far name lookup should work. These criteria are important both 3617 /// for capturing language semantics (certain lookups will ignore 3618 /// certain names, for example) and for performance, since name 3619 /// lookup is often a bottleneck in the compilation of C++. Name 3620 /// lookup criteria is specified via the LookupCriteria enumeration. 3621 /// 3622 /// The results of name lookup can vary based on the kind of name 3623 /// lookup performed, the current language, and the translation 3624 /// unit. In C, for example, name lookup will either return nothing 3625 /// (no entity found) or a single declaration. In C++, name lookup 3626 /// can additionally refer to a set of overloaded functions or 3627 /// result in an ambiguity. All of the possible results of name 3628 /// lookup are captured by the LookupResult class, which provides 3629 /// the ability to distinguish among them. 3630 //@{ 3631 3632 /// Describes the kind of name lookup to perform. 3633 enum LookupNameKind { 3634 /// Ordinary name lookup, which finds ordinary names (functions, 3635 /// variables, typedefs, etc.) in C and most kinds of names 3636 /// (functions, variables, members, types, etc.) in C++. 3637 LookupOrdinaryName = 0, 3638 /// Tag name lookup, which finds the names of enums, classes, 3639 /// structs, and unions. 3640 LookupTagName, 3641 /// Label name lookup. 3642 LookupLabel, 3643 /// Member name lookup, which finds the names of 3644 /// class/struct/union members. 3645 LookupMemberName, 3646 /// Look up of an operator name (e.g., operator+) for use with 3647 /// operator overloading. This lookup is similar to ordinary name 3648 /// lookup, but will ignore any declarations that are class members. 3649 LookupOperatorName, 3650 /// Look up a name following ~ in a destructor name. This is an ordinary 3651 /// lookup, but prefers tags to typedefs. 3652 LookupDestructorName, 3653 /// Look up of a name that precedes the '::' scope resolution 3654 /// operator in C++. This lookup completely ignores operator, object, 3655 /// function, and enumerator names (C++ [basic.lookup.qual]p1). 3656 LookupNestedNameSpecifierName, 3657 /// Look up a namespace name within a C++ using directive or 3658 /// namespace alias definition, ignoring non-namespace names (C++ 3659 /// [basic.lookup.udir]p1). 3660 LookupNamespaceName, 3661 /// Look up all declarations in a scope with the given name, 3662 /// including resolved using declarations. This is appropriate 3663 /// for checking redeclarations for a using declaration. 3664 LookupUsingDeclName, 3665 /// Look up an ordinary name that is going to be redeclared as a 3666 /// name with linkage. This lookup ignores any declarations that 3667 /// are outside of the current scope unless they have linkage. See 3668 /// C99 6.2.2p4-5 and C++ [basic.link]p6. 3669 LookupRedeclarationWithLinkage, 3670 /// Look up a friend of a local class. This lookup does not look 3671 /// outside the innermost non-class scope. See C++11 [class.friend]p11. 3672 LookupLocalFriendName, 3673 /// Look up the name of an Objective-C protocol. 3674 LookupObjCProtocolName, 3675 /// Look up implicit 'self' parameter of an objective-c method. 3676 LookupObjCImplicitSelfParam, 3677 /// Look up the name of an OpenMP user-defined reduction operation. 3678 LookupOMPReductionName, 3679 /// Look up the name of an OpenMP user-defined mapper. 3680 LookupOMPMapperName, 3681 /// Look up any declaration with any name. 3682 LookupAnyName 3683 }; 3684 3685 /// Specifies whether (or how) name lookup is being performed for a 3686 /// redeclaration (vs. a reference). 3687 enum RedeclarationKind { 3688 /// The lookup is a reference to this name that is not for the 3689 /// purpose of redeclaring the name. 3690 NotForRedeclaration = 0, 3691 /// The lookup results will be used for redeclaration of a name, 3692 /// if an entity by that name already exists and is visible. 3693 ForVisibleRedeclaration, 3694 /// The lookup results will be used for redeclaration of a name 3695 /// with external linkage; non-visible lookup results with external linkage 3696 /// may also be found. 3697 ForExternalRedeclaration 3698 }; 3699 forRedeclarationInCurContext()3700 RedeclarationKind forRedeclarationInCurContext() { 3701 // A declaration with an owning module for linkage can never link against 3702 // anything that is not visible. We don't need to check linkage here; if 3703 // the context has internal linkage, redeclaration lookup won't find things 3704 // from other TUs, and we can't safely compute linkage yet in general. 3705 if (cast<Decl>(CurContext) 3706 ->getOwningModuleForLinkage(/*IgnoreLinkage*/true)) 3707 return ForVisibleRedeclaration; 3708 return ForExternalRedeclaration; 3709 } 3710 3711 /// The possible outcomes of name lookup for a literal operator. 3712 enum LiteralOperatorLookupResult { 3713 /// The lookup resulted in an error. 3714 LOLR_Error, 3715 /// The lookup found no match but no diagnostic was issued. 3716 LOLR_ErrorNoDiagnostic, 3717 /// The lookup found a single 'cooked' literal operator, which 3718 /// expects a normal literal to be built and passed to it. 3719 LOLR_Cooked, 3720 /// The lookup found a single 'raw' literal operator, which expects 3721 /// a string literal containing the spelling of the literal token. 3722 LOLR_Raw, 3723 /// The lookup found an overload set of literal operator templates, 3724 /// which expect the characters of the spelling of the literal token to be 3725 /// passed as a non-type template argument pack. 3726 LOLR_Template, 3727 /// The lookup found an overload set of literal operator templates, 3728 /// which expect the character type and characters of the spelling of the 3729 /// string literal token to be passed as template arguments. 3730 LOLR_StringTemplate 3731 }; 3732 3733 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, 3734 CXXSpecialMember SM, 3735 bool ConstArg, 3736 bool VolatileArg, 3737 bool RValueThis, 3738 bool ConstThis, 3739 bool VolatileThis); 3740 3741 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator; 3742 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)> 3743 TypoRecoveryCallback; 3744 3745 private: 3746 bool CppLookupName(LookupResult &R, Scope *S); 3747 3748 struct TypoExprState { 3749 std::unique_ptr<TypoCorrectionConsumer> Consumer; 3750 TypoDiagnosticGenerator DiagHandler; 3751 TypoRecoveryCallback RecoveryHandler; 3752 TypoExprState(); 3753 TypoExprState(TypoExprState &&other) noexcept; 3754 TypoExprState &operator=(TypoExprState &&other) noexcept; 3755 }; 3756 3757 /// The set of unhandled TypoExprs and their associated state. 3758 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos; 3759 3760 /// Creates a new TypoExpr AST node. 3761 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, 3762 TypoDiagnosticGenerator TDG, 3763 TypoRecoveryCallback TRC, SourceLocation TypoLoc); 3764 3765 // The set of known/encountered (unique, canonicalized) NamespaceDecls. 3766 // 3767 // The boolean value will be true to indicate that the namespace was loaded 3768 // from an AST/PCH file, or false otherwise. 3769 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces; 3770 3771 /// Whether we have already loaded known namespaces from an extenal 3772 /// source. 3773 bool LoadedExternalKnownNamespaces; 3774 3775 /// Helper for CorrectTypo and CorrectTypoDelayed used to create and 3776 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction 3777 /// should be skipped entirely. 3778 std::unique_ptr<TypoCorrectionConsumer> 3779 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo, 3780 Sema::LookupNameKind LookupKind, Scope *S, 3781 CXXScopeSpec *SS, 3782 CorrectionCandidateCallback &CCC, 3783 DeclContext *MemberContext, bool EnteringContext, 3784 const ObjCObjectPointerType *OPT, 3785 bool ErrorRecovery); 3786 3787 public: 3788 const TypoExprState &getTypoExprState(TypoExpr *TE) const; 3789 3790 /// Clears the state of the given TypoExpr. 3791 void clearDelayedTypo(TypoExpr *TE); 3792 3793 /// Look up a name, looking for a single declaration. Return 3794 /// null if the results were absent, ambiguous, or overloaded. 3795 /// 3796 /// It is preferable to use the elaborated form and explicitly handle 3797 /// ambiguity and overloaded. 3798 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, 3799 SourceLocation Loc, 3800 LookupNameKind NameKind, 3801 RedeclarationKind Redecl 3802 = NotForRedeclaration); 3803 bool LookupBuiltin(LookupResult &R); 3804 bool LookupName(LookupResult &R, Scope *S, 3805 bool AllowBuiltinCreation = false); 3806 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 3807 bool InUnqualifiedLookup = false); 3808 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 3809 CXXScopeSpec &SS); 3810 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 3811 bool AllowBuiltinCreation = false, 3812 bool EnteringContext = false); 3813 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, 3814 RedeclarationKind Redecl 3815 = NotForRedeclaration); 3816 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class); 3817 3818 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, 3819 QualType T1, QualType T2, 3820 UnresolvedSetImpl &Functions); 3821 3822 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, 3823 SourceLocation GnuLabelLoc = SourceLocation()); 3824 3825 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); 3826 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); 3827 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, 3828 unsigned Quals); 3829 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, 3830 bool RValueThis, unsigned ThisQuals); 3831 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, 3832 unsigned Quals); 3833 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, 3834 bool RValueThis, unsigned ThisQuals); 3835 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); 3836 3837 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id); 3838 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, 3839 ArrayRef<QualType> ArgTys, 3840 bool AllowRaw, 3841 bool AllowTemplate, 3842 bool AllowStringTemplate, 3843 bool DiagnoseMissing); 3844 bool isKnownName(StringRef name); 3845 3846 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs. 3847 enum class FunctionEmissionStatus { 3848 Emitted, 3849 CUDADiscarded, // Discarded due to CUDA/HIP hostness 3850 OMPDiscarded, // Discarded due to OpenMP hostness 3851 TemplateDiscarded, // Discarded due to uninstantiated templates 3852 Unknown, 3853 }; 3854 FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl, 3855 bool Final = false); 3856 3857 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check. 3858 bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee); 3859 3860 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, 3861 ArrayRef<Expr *> Args, ADLResult &Functions); 3862 3863 void LookupVisibleDecls(Scope *S, LookupNameKind Kind, 3864 VisibleDeclConsumer &Consumer, 3865 bool IncludeGlobalScope = true, 3866 bool LoadExternal = true); 3867 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, 3868 VisibleDeclConsumer &Consumer, 3869 bool IncludeGlobalScope = true, 3870 bool IncludeDependentBases = false, 3871 bool LoadExternal = true); 3872 3873 enum CorrectTypoKind { 3874 CTK_NonError, // CorrectTypo used in a non error recovery situation. 3875 CTK_ErrorRecovery // CorrectTypo used in normal error recovery. 3876 }; 3877 3878 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, 3879 Sema::LookupNameKind LookupKind, 3880 Scope *S, CXXScopeSpec *SS, 3881 CorrectionCandidateCallback &CCC, 3882 CorrectTypoKind Mode, 3883 DeclContext *MemberContext = nullptr, 3884 bool EnteringContext = false, 3885 const ObjCObjectPointerType *OPT = nullptr, 3886 bool RecordFailure = true); 3887 3888 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo, 3889 Sema::LookupNameKind LookupKind, Scope *S, 3890 CXXScopeSpec *SS, 3891 CorrectionCandidateCallback &CCC, 3892 TypoDiagnosticGenerator TDG, 3893 TypoRecoveryCallback TRC, CorrectTypoKind Mode, 3894 DeclContext *MemberContext = nullptr, 3895 bool EnteringContext = false, 3896 const ObjCObjectPointerType *OPT = nullptr); 3897 3898 /// Process any TypoExprs in the given Expr and its children, 3899 /// generating diagnostics as appropriate and returning a new Expr if there 3900 /// were typos that were all successfully corrected and ExprError if one or 3901 /// more typos could not be corrected. 3902 /// 3903 /// \param E The Expr to check for TypoExprs. 3904 /// 3905 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its 3906 /// initializer. 3907 /// 3908 /// \param RecoverUncorrectedTypos If true, when typo correction fails, it 3909 /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs. 3910 /// 3911 /// \param Filter A function applied to a newly rebuilt Expr to determine if 3912 /// it is an acceptable/usable result from a single combination of typo 3913 /// corrections. As long as the filter returns ExprError, different 3914 /// combinations of corrections will be tried until all are exhausted. 3915 ExprResult CorrectDelayedTyposInExpr( 3916 Expr *E, VarDecl *InitDecl = nullptr, 3917 bool RecoverUncorrectedTypos = false, 3918 llvm::function_ref<ExprResult(Expr *)> Filter = 3919 [](Expr *E) -> ExprResult { return E; }); 3920 3921 ExprResult CorrectDelayedTyposInExpr( 3922 ExprResult ER, VarDecl *InitDecl = nullptr, 3923 bool RecoverUncorrectedTypos = false, 3924 llvm::function_ref<ExprResult(Expr *)> Filter = 3925 [](Expr *E) -> ExprResult { return E; }) { 3926 return ER.isInvalid() 3927 ? ER 3928 : CorrectDelayedTyposInExpr(ER.get(), InitDecl, 3929 RecoverUncorrectedTypos, Filter); 3930 } 3931 3932 void diagnoseTypo(const TypoCorrection &Correction, 3933 const PartialDiagnostic &TypoDiag, 3934 bool ErrorRecovery = true); 3935 3936 void diagnoseTypo(const TypoCorrection &Correction, 3937 const PartialDiagnostic &TypoDiag, 3938 const PartialDiagnostic &PrevNote, 3939 bool ErrorRecovery = true); 3940 3941 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F); 3942 3943 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, 3944 ArrayRef<Expr *> Args, 3945 AssociatedNamespaceSet &AssociatedNamespaces, 3946 AssociatedClassSet &AssociatedClasses); 3947 3948 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 3949 bool ConsiderLinkage, bool AllowInlineNamespace); 3950 3951 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old); 3952 3953 void DiagnoseAmbiguousLookup(LookupResult &Result); 3954 //@} 3955 3956 /// Attempts to produce a RecoveryExpr after some AST node cannot be created. 3957 ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 3958 ArrayRef<Expr *> SubExprs, 3959 QualType T = QualType()); 3960 3961 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, 3962 SourceLocation IdLoc, 3963 bool TypoCorrection = false); 3964 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 3965 Scope *S, bool ForRedeclaration, 3966 SourceLocation Loc); 3967 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, 3968 Scope *S); 3969 void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 3970 FunctionDecl *FD); 3971 void AddKnownFunctionAttributes(FunctionDecl *FD); 3972 3973 // More parsing and symbol table subroutines. 3974 3975 void ProcessPragmaWeak(Scope *S, Decl *D); 3976 // Decl attributes - this routine is the top level dispatcher. 3977 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); 3978 // Helper for delayed processing of attributes. 3979 void ProcessDeclAttributeDelayed(Decl *D, 3980 const ParsedAttributesView &AttrList); 3981 void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL, 3982 bool IncludeCXX11Attributes = true); 3983 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, 3984 const ParsedAttributesView &AttrList); 3985 3986 void checkUnusedDeclAttributes(Declarator &D); 3987 3988 /// Determine if type T is a valid subject for a nonnull and similar 3989 /// attributes. By default, we look through references (the behavior used by 3990 /// nonnull), but if the second parameter is true, then we treat a reference 3991 /// type as valid. 3992 bool isValidPointerAttrType(QualType T, bool RefOkay = false); 3993 3994 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value); 3995 bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, 3996 const FunctionDecl *FD = nullptr); 3997 bool CheckAttrTarget(const ParsedAttr &CurrAttr); 3998 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr); 3999 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum, 4000 StringRef &Str, 4001 SourceLocation *ArgLocation = nullptr); 4002 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str); 4003 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str); 4004 bool checkMSInheritanceAttrOnDefinition( 4005 CXXRecordDecl *RD, SourceRange Range, bool BestCase, 4006 MSInheritanceModel SemanticSpelling); 4007 4008 void CheckAlignasUnderalignment(Decl *D); 4009 4010 /// Adjust the calling convention of a method to be the ABI default if it 4011 /// wasn't specified explicitly. This handles method types formed from 4012 /// function type typedefs and typename template arguments. 4013 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, 4014 SourceLocation Loc); 4015 4016 // Check if there is an explicit attribute, but only look through parens. 4017 // The intent is to look for an attribute on the current declarator, but not 4018 // one that came from a typedef. 4019 bool hasExplicitCallingConv(QualType T); 4020 4021 /// Get the outermost AttributedType node that sets a calling convention. 4022 /// Valid types should not have multiple attributes with different CCs. 4023 const AttributedType *getCallingConvAttributedType(QualType T) const; 4024 4025 /// Stmt attributes - this routine is the top level dispatcher. 4026 StmtResult ProcessStmtAttributes(Stmt *Stmt, 4027 const ParsedAttributesView &Attrs, 4028 SourceRange Range); 4029 4030 void WarnConflictingTypedMethods(ObjCMethodDecl *Method, 4031 ObjCMethodDecl *MethodDecl, 4032 bool IsProtocolMethodDecl); 4033 4034 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, 4035 ObjCMethodDecl *Overridden, 4036 bool IsProtocolMethodDecl); 4037 4038 /// WarnExactTypedMethods - This routine issues a warning if method 4039 /// implementation declaration matches exactly that of its declaration. 4040 void WarnExactTypedMethods(ObjCMethodDecl *Method, 4041 ObjCMethodDecl *MethodDecl, 4042 bool IsProtocolMethodDecl); 4043 4044 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet; 4045 4046 /// CheckImplementationIvars - This routine checks if the instance variables 4047 /// listed in the implelementation match those listed in the interface. 4048 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, 4049 ObjCIvarDecl **Fields, unsigned nIvars, 4050 SourceLocation Loc); 4051 4052 /// ImplMethodsVsClassMethods - This is main routine to warn if any method 4053 /// remains unimplemented in the class or category \@implementation. 4054 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, 4055 ObjCContainerDecl* IDecl, 4056 bool IncompleteImpl = false); 4057 4058 /// DiagnoseUnimplementedProperties - This routine warns on those properties 4059 /// which must be implemented by this implementation. 4060 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, 4061 ObjCContainerDecl *CDecl, 4062 bool SynthesizeProperties); 4063 4064 /// Diagnose any null-resettable synthesized setters. 4065 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl); 4066 4067 /// DefaultSynthesizeProperties - This routine default synthesizes all 4068 /// properties which must be synthesized in the class's \@implementation. 4069 void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl, 4070 ObjCInterfaceDecl *IDecl, 4071 SourceLocation AtEnd); 4072 void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd); 4073 4074 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is 4075 /// an ivar synthesized for 'Method' and 'Method' is a property accessor 4076 /// declared in class 'IFace'. 4077 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, 4078 ObjCMethodDecl *Method, ObjCIvarDecl *IV); 4079 4080 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which 4081 /// backs the property is not used in the property's accessor. 4082 void DiagnoseUnusedBackingIvarInAccessor(Scope *S, 4083 const ObjCImplementationDecl *ImplD); 4084 4085 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and 4086 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL. 4087 /// It also returns ivar's property on success. 4088 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, 4089 const ObjCPropertyDecl *&PDecl) const; 4090 4091 /// Called by ActOnProperty to handle \@property declarations in 4092 /// class extensions. 4093 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S, 4094 SourceLocation AtLoc, 4095 SourceLocation LParenLoc, 4096 FieldDeclarator &FD, 4097 Selector GetterSel, 4098 SourceLocation GetterNameLoc, 4099 Selector SetterSel, 4100 SourceLocation SetterNameLoc, 4101 const bool isReadWrite, 4102 unsigned &Attributes, 4103 const unsigned AttributesAsWritten, 4104 QualType T, 4105 TypeSourceInfo *TSI, 4106 tok::ObjCKeywordKind MethodImplKind); 4107 4108 /// Called by ActOnProperty and HandlePropertyInClassExtension to 4109 /// handle creating the ObjcPropertyDecl for a category or \@interface. 4110 ObjCPropertyDecl *CreatePropertyDecl(Scope *S, 4111 ObjCContainerDecl *CDecl, 4112 SourceLocation AtLoc, 4113 SourceLocation LParenLoc, 4114 FieldDeclarator &FD, 4115 Selector GetterSel, 4116 SourceLocation GetterNameLoc, 4117 Selector SetterSel, 4118 SourceLocation SetterNameLoc, 4119 const bool isReadWrite, 4120 const unsigned Attributes, 4121 const unsigned AttributesAsWritten, 4122 QualType T, 4123 TypeSourceInfo *TSI, 4124 tok::ObjCKeywordKind MethodImplKind, 4125 DeclContext *lexicalDC = nullptr); 4126 4127 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via 4128 /// warning) when atomic property has one but not the other user-declared 4129 /// setter or getter. 4130 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, 4131 ObjCInterfaceDecl* IDecl); 4132 4133 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); 4134 4135 void DiagnoseMissingDesignatedInitOverrides( 4136 const ObjCImplementationDecl *ImplD, 4137 const ObjCInterfaceDecl *IFD); 4138 4139 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); 4140 4141 enum MethodMatchStrategy { 4142 MMS_loose, 4143 MMS_strict 4144 }; 4145 4146 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns 4147 /// true, or false, accordingly. 4148 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, 4149 const ObjCMethodDecl *PrevMethod, 4150 MethodMatchStrategy strategy = MMS_strict); 4151 4152 /// MatchAllMethodDeclarations - Check methods declaraed in interface or 4153 /// or protocol against those declared in their implementations. 4154 void MatchAllMethodDeclarations(const SelectorSet &InsMap, 4155 const SelectorSet &ClsMap, 4156 SelectorSet &InsMapSeen, 4157 SelectorSet &ClsMapSeen, 4158 ObjCImplDecl* IMPDecl, 4159 ObjCContainerDecl* IDecl, 4160 bool &IncompleteImpl, 4161 bool ImmediateClass, 4162 bool WarnCategoryMethodImpl=false); 4163 4164 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in 4165 /// category matches with those implemented in its primary class and 4166 /// warns each time an exact match is found. 4167 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); 4168 4169 /// Add the given method to the list of globally-known methods. 4170 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); 4171 4172 /// Returns default addr space for method qualifiers. 4173 LangAS getDefaultCXXMethodAddrSpace() const; 4174 4175 private: 4176 /// AddMethodToGlobalPool - Add an instance or factory method to the global 4177 /// pool. See descriptoin of AddInstanceMethodToGlobalPool. 4178 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); 4179 4180 /// LookupMethodInGlobalPool - Returns the instance or factory method and 4181 /// optionally warns if there are multiple signatures. 4182 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, 4183 bool receiverIdOrClass, 4184 bool instance); 4185 4186 public: 4187 /// - Returns instance or factory methods in global method pool for 4188 /// given selector. It checks the desired kind first, if none is found, and 4189 /// parameter checkTheOther is set, it then checks the other kind. If no such 4190 /// method or only one method is found, function returns false; otherwise, it 4191 /// returns true. 4192 bool 4193 CollectMultipleMethodsInGlobalPool(Selector Sel, 4194 SmallVectorImpl<ObjCMethodDecl*>& Methods, 4195 bool InstanceFirst, bool CheckTheOther, 4196 const ObjCObjectType *TypeBound = nullptr); 4197 4198 bool 4199 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, 4200 SourceRange R, bool receiverIdOrClass, 4201 SmallVectorImpl<ObjCMethodDecl*>& Methods); 4202 4203 void 4204 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, 4205 Selector Sel, SourceRange R, 4206 bool receiverIdOrClass); 4207 4208 private: 4209 /// - Returns a selector which best matches given argument list or 4210 /// nullptr if none could be found 4211 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args, 4212 bool IsInstance, 4213 SmallVectorImpl<ObjCMethodDecl*>& Methods); 4214 4215 4216 /// Record the typo correction failure and return an empty correction. 4217 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc, 4218 bool RecordFailure = true) { 4219 if (RecordFailure) 4220 TypoCorrectionFailures[Typo].insert(TypoLoc); 4221 return TypoCorrection(); 4222 } 4223 4224 public: 4225 /// AddInstanceMethodToGlobalPool - All instance methods in a translation 4226 /// unit are added to a global pool. This allows us to efficiently associate 4227 /// a selector with a method declaraation for purposes of typechecking 4228 /// messages sent to "id" (where the class of the object is unknown). 4229 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 4230 AddMethodToGlobalPool(Method, impl, /*instance*/true); 4231 } 4232 4233 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. 4234 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 4235 AddMethodToGlobalPool(Method, impl, /*instance*/false); 4236 } 4237 4238 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global 4239 /// pool. 4240 void AddAnyMethodToGlobalPool(Decl *D); 4241 4242 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if 4243 /// there are multiple signatures. 4244 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, 4245 bool receiverIdOrClass=false) { 4246 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 4247 /*instance*/true); 4248 } 4249 4250 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if 4251 /// there are multiple signatures. 4252 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, 4253 bool receiverIdOrClass=false) { 4254 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 4255 /*instance*/false); 4256 } 4257 4258 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel, 4259 QualType ObjectType=QualType()); 4260 /// LookupImplementedMethodInGlobalPool - Returns the method which has an 4261 /// implementation. 4262 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); 4263 4264 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require 4265 /// initialization. 4266 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, 4267 SmallVectorImpl<ObjCIvarDecl*> &Ivars); 4268 4269 //===--------------------------------------------------------------------===// 4270 // Statement Parsing Callbacks: SemaStmt.cpp. 4271 public: 4272 class FullExprArg { 4273 public: FullExprArg()4274 FullExprArg() : E(nullptr) { } FullExprArg(Sema & actions)4275 FullExprArg(Sema &actions) : E(nullptr) { } 4276 release()4277 ExprResult release() { 4278 return E; 4279 } 4280 get()4281 Expr *get() const { return E; } 4282 4283 Expr *operator->() { 4284 return E; 4285 } 4286 4287 private: 4288 // FIXME: No need to make the entire Sema class a friend when it's just 4289 // Sema::MakeFullExpr that needs access to the constructor below. 4290 friend class Sema; 4291 FullExprArg(Expr * expr)4292 explicit FullExprArg(Expr *expr) : E(expr) {} 4293 4294 Expr *E; 4295 }; 4296 MakeFullExpr(Expr * Arg)4297 FullExprArg MakeFullExpr(Expr *Arg) { 4298 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation()); 4299 } MakeFullExpr(Expr * Arg,SourceLocation CC)4300 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { 4301 return FullExprArg( 4302 ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get()); 4303 } MakeFullDiscardedValueExpr(Expr * Arg)4304 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { 4305 ExprResult FE = 4306 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), 4307 /*DiscardedValue*/ true); 4308 return FullExprArg(FE.get()); 4309 } 4310 4311 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true); 4312 StmtResult ActOnExprStmtError(); 4313 4314 StmtResult ActOnNullStmt(SourceLocation SemiLoc, 4315 bool HasLeadingEmptyMacro = false); 4316 4317 void ActOnStartOfCompoundStmt(bool IsStmtExpr); 4318 void ActOnFinishOfCompoundStmt(); 4319 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, 4320 ArrayRef<Stmt *> Elts, bool isStmtExpr); 4321 4322 /// A RAII object to enter scope of a compound statement. 4323 class CompoundScopeRAII { 4324 public: S(S)4325 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) { 4326 S.ActOnStartOfCompoundStmt(IsStmtExpr); 4327 } 4328 ~CompoundScopeRAII()4329 ~CompoundScopeRAII() { 4330 S.ActOnFinishOfCompoundStmt(); 4331 } 4332 4333 private: 4334 Sema &S; 4335 }; 4336 4337 /// An RAII helper that pops function a function scope on exit. 4338 struct FunctionScopeRAII { 4339 Sema &S; 4340 bool Active; FunctionScopeRAIIFunctionScopeRAII4341 FunctionScopeRAII(Sema &S) : S(S), Active(true) {} ~FunctionScopeRAIIFunctionScopeRAII4342 ~FunctionScopeRAII() { 4343 if (Active) 4344 S.PopFunctionScopeInfo(); 4345 } disableFunctionScopeRAII4346 void disable() { Active = false; } 4347 }; 4348 4349 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, 4350 SourceLocation StartLoc, 4351 SourceLocation EndLoc); 4352 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); 4353 StmtResult ActOnForEachLValueExpr(Expr *E); 4354 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val); 4355 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS, 4356 SourceLocation DotDotDotLoc, ExprResult RHS, 4357 SourceLocation ColonLoc); 4358 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); 4359 4360 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, 4361 SourceLocation ColonLoc, 4362 Stmt *SubStmt, Scope *CurScope); 4363 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, 4364 SourceLocation ColonLoc, Stmt *SubStmt); 4365 4366 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc, 4367 ArrayRef<const Attr*> Attrs, 4368 Stmt *SubStmt); 4369 4370 class ConditionResult; 4371 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, 4372 Stmt *InitStmt, 4373 ConditionResult Cond, Stmt *ThenVal, 4374 SourceLocation ElseLoc, Stmt *ElseVal); 4375 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr, 4376 Stmt *InitStmt, 4377 ConditionResult Cond, Stmt *ThenVal, 4378 SourceLocation ElseLoc, Stmt *ElseVal); 4379 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, 4380 Stmt *InitStmt, 4381 ConditionResult Cond); 4382 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, 4383 Stmt *Switch, Stmt *Body); 4384 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc, 4385 ConditionResult Cond, SourceLocation RParenLoc, 4386 Stmt *Body); 4387 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 4388 SourceLocation WhileLoc, SourceLocation CondLParen, 4389 Expr *Cond, SourceLocation CondRParen); 4390 4391 StmtResult ActOnForStmt(SourceLocation ForLoc, 4392 SourceLocation LParenLoc, 4393 Stmt *First, 4394 ConditionResult Second, 4395 FullExprArg Third, 4396 SourceLocation RParenLoc, 4397 Stmt *Body); 4398 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, 4399 Expr *collection); 4400 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, 4401 Stmt *First, Expr *collection, 4402 SourceLocation RParenLoc); 4403 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body); 4404 4405 enum BuildForRangeKind { 4406 /// Initial building of a for-range statement. 4407 BFRK_Build, 4408 /// Instantiation or recovery rebuild of a for-range statement. Don't 4409 /// attempt any typo-correction. 4410 BFRK_Rebuild, 4411 /// Determining whether a for-range statement could be built. Avoid any 4412 /// unnecessary or irreversible actions. 4413 BFRK_Check 4414 }; 4415 4416 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, 4417 SourceLocation CoawaitLoc, 4418 Stmt *InitStmt, 4419 Stmt *LoopVar, 4420 SourceLocation ColonLoc, Expr *Collection, 4421 SourceLocation RParenLoc, 4422 BuildForRangeKind Kind); 4423 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, 4424 SourceLocation CoawaitLoc, 4425 Stmt *InitStmt, 4426 SourceLocation ColonLoc, 4427 Stmt *RangeDecl, Stmt *Begin, Stmt *End, 4428 Expr *Cond, Expr *Inc, 4429 Stmt *LoopVarDecl, 4430 SourceLocation RParenLoc, 4431 BuildForRangeKind Kind); 4432 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); 4433 4434 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, 4435 SourceLocation LabelLoc, 4436 LabelDecl *TheDecl); 4437 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, 4438 SourceLocation StarLoc, 4439 Expr *DestExp); 4440 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); 4441 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); 4442 4443 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, 4444 CapturedRegionKind Kind, unsigned NumParams); 4445 typedef std::pair<StringRef, QualType> CapturedParamNameType; 4446 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, 4447 CapturedRegionKind Kind, 4448 ArrayRef<CapturedParamNameType> Params, 4449 unsigned OpenMPCaptureLevel = 0); 4450 StmtResult ActOnCapturedRegionEnd(Stmt *S); 4451 void ActOnCapturedRegionError(); 4452 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, 4453 SourceLocation Loc, 4454 unsigned NumParams); 4455 4456 enum CopyElisionSemanticsKind { 4457 CES_Strict = 0, 4458 CES_AllowParameters = 1, 4459 CES_AllowDifferentTypes = 2, 4460 CES_AllowExceptionVariables = 4, 4461 CES_FormerDefault = (CES_AllowParameters), 4462 CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes), 4463 CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes | 4464 CES_AllowExceptionVariables), 4465 }; 4466 4467 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E, 4468 CopyElisionSemanticsKind CESK); 4469 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD, 4470 CopyElisionSemanticsKind CESK); 4471 4472 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, 4473 Scope *CurScope); 4474 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); 4475 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); 4476 4477 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, 4478 bool IsVolatile, unsigned NumOutputs, 4479 unsigned NumInputs, IdentifierInfo **Names, 4480 MultiExprArg Constraints, MultiExprArg Exprs, 4481 Expr *AsmString, MultiExprArg Clobbers, 4482 unsigned NumLabels, 4483 SourceLocation RParenLoc); 4484 4485 void FillInlineAsmIdentifierInfo(Expr *Res, 4486 llvm::InlineAsmIdentifierInfo &Info); 4487 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, 4488 SourceLocation TemplateKWLoc, 4489 UnqualifiedId &Id, 4490 bool IsUnevaluatedContext); 4491 bool LookupInlineAsmField(StringRef Base, StringRef Member, 4492 unsigned &Offset, SourceLocation AsmLoc); 4493 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, 4494 SourceLocation AsmLoc); 4495 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, 4496 ArrayRef<Token> AsmToks, 4497 StringRef AsmString, 4498 unsigned NumOutputs, unsigned NumInputs, 4499 ArrayRef<StringRef> Constraints, 4500 ArrayRef<StringRef> Clobbers, 4501 ArrayRef<Expr*> Exprs, 4502 SourceLocation EndLoc); 4503 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName, 4504 SourceLocation Location, 4505 bool AlwaysCreate); 4506 4507 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, 4508 SourceLocation StartLoc, 4509 SourceLocation IdLoc, IdentifierInfo *Id, 4510 bool Invalid = false); 4511 4512 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); 4513 4514 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, 4515 Decl *Parm, Stmt *Body); 4516 4517 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); 4518 4519 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 4520 MultiStmtArg Catch, Stmt *Finally); 4521 4522 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); 4523 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 4524 Scope *CurScope); 4525 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, 4526 Expr *operand); 4527 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, 4528 Expr *SynchExpr, 4529 Stmt *SynchBody); 4530 4531 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); 4532 4533 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, 4534 SourceLocation StartLoc, 4535 SourceLocation IdLoc, 4536 IdentifierInfo *Id); 4537 4538 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); 4539 4540 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, 4541 Decl *ExDecl, Stmt *HandlerBlock); 4542 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 4543 ArrayRef<Stmt *> Handlers); 4544 4545 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? 4546 SourceLocation TryLoc, Stmt *TryBlock, 4547 Stmt *Handler); 4548 StmtResult ActOnSEHExceptBlock(SourceLocation Loc, 4549 Expr *FilterExpr, 4550 Stmt *Block); 4551 void ActOnStartSEHFinallyBlock(); 4552 void ActOnAbortSEHFinallyBlock(); 4553 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block); 4554 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope); 4555 4556 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); 4557 4558 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; 4559 4560 /// If it's a file scoped decl that must warn if not used, keep track 4561 /// of it. 4562 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); 4563 4564 /// DiagnoseUnusedExprResult - If the statement passed in is an expression 4565 /// whose result is unused, warn. 4566 void DiagnoseUnusedExprResult(const Stmt *S); 4567 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D); 4568 void DiagnoseUnusedDecl(const NamedDecl *ND); 4569 4570 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null 4571 /// statement as a \p Body, and it is located on the same line. 4572 /// 4573 /// This helps prevent bugs due to typos, such as: 4574 /// if (condition); 4575 /// do_stuff(); 4576 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 4577 const Stmt *Body, 4578 unsigned DiagID); 4579 4580 /// Warn if a for/while loop statement \p S, which is followed by 4581 /// \p PossibleBody, has a suspicious null statement as a body. 4582 void DiagnoseEmptyLoopBody(const Stmt *S, 4583 const Stmt *PossibleBody); 4584 4585 /// Warn if a value is moved to itself. 4586 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 4587 SourceLocation OpLoc); 4588 4589 /// Warn if we're implicitly casting from a _Nullable pointer type to a 4590 /// _Nonnull one. 4591 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, 4592 SourceLocation Loc); 4593 4594 /// Warn when implicitly casting 0 to nullptr. 4595 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E); 4596 PushParsingDeclaration(sema::DelayedDiagnosticPool & pool)4597 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { 4598 return DelayedDiagnostics.push(pool); 4599 } 4600 void PopParsingDeclaration(ParsingDeclState state, Decl *decl); 4601 4602 typedef ProcessingContextState ParsingClassState; PushParsingClass()4603 ParsingClassState PushParsingClass() { 4604 ParsingClassDepth++; 4605 return DelayedDiagnostics.pushUndelayed(); 4606 } PopParsingClass(ParsingClassState state)4607 void PopParsingClass(ParsingClassState state) { 4608 ParsingClassDepth--; 4609 DelayedDiagnostics.popUndelayed(state); 4610 } 4611 4612 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); 4613 4614 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 4615 const ObjCInterfaceDecl *UnknownObjCClass, 4616 bool ObjCPropertyAccess, 4617 bool AvoidPartialAvailabilityChecks = false, 4618 ObjCInterfaceDecl *ClassReceiver = nullptr); 4619 4620 bool makeUnavailableInSystemHeader(SourceLocation loc, 4621 UnavailableAttr::ImplicitReason reason); 4622 4623 /// Issue any -Wunguarded-availability warnings in \c FD 4624 void DiagnoseUnguardedAvailabilityViolations(Decl *FD); 4625 4626 void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 4627 4628 //===--------------------------------------------------------------------===// 4629 // Expression Parsing Callbacks: SemaExpr.cpp. 4630 4631 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid); 4632 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 4633 const ObjCInterfaceDecl *UnknownObjCClass = nullptr, 4634 bool ObjCPropertyAccess = false, 4635 bool AvoidPartialAvailabilityChecks = false, 4636 ObjCInterfaceDecl *ClassReciever = nullptr); 4637 void NoteDeletedFunction(FunctionDecl *FD); 4638 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD); 4639 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, 4640 ObjCMethodDecl *Getter, 4641 SourceLocation Loc); 4642 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 4643 ArrayRef<Expr *> Args); 4644 4645 void PushExpressionEvaluationContext( 4646 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, 4647 ExpressionEvaluationContextRecord::ExpressionKind Type = 4648 ExpressionEvaluationContextRecord::EK_Other); 4649 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; 4650 void PushExpressionEvaluationContext( 4651 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 4652 ExpressionEvaluationContextRecord::ExpressionKind Type = 4653 ExpressionEvaluationContextRecord::EK_Other); 4654 void PopExpressionEvaluationContext(); 4655 4656 void DiscardCleanupsInEvaluationContext(); 4657 4658 ExprResult TransformToPotentiallyEvaluated(Expr *E); 4659 ExprResult HandleExprEvaluationContextForTypeof(Expr *E); 4660 4661 ExprResult CheckUnevaluatedOperand(Expr *E); 4662 void CheckUnusedVolatileAssignment(Expr *E); 4663 4664 ExprResult ActOnConstantExpression(ExprResult Res); 4665 4666 // Functions for marking a declaration referenced. These functions also 4667 // contain the relevant logic for marking if a reference to a function or 4668 // variable is an odr-use (in the C++11 sense). There are separate variants 4669 // for expressions referring to a decl; these exist because odr-use marking 4670 // needs to be delayed for some constant variables when we build one of the 4671 // named expressions. 4672 // 4673 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and 4674 // should usually be true. This only needs to be set to false if the lack of 4675 // odr-use cannot be determined from the current context (for instance, 4676 // because the name denotes a virtual function and was written without an 4677 // explicit nested-name-specifier). 4678 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse); 4679 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 4680 bool MightBeOdrUse = true); 4681 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); 4682 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr); 4683 void MarkMemberReferenced(MemberExpr *E); 4684 void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E); 4685 void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc, 4686 unsigned CapturingScopeIndex); 4687 4688 ExprResult CheckLValueToRValueConversionOperand(Expr *E); 4689 void CleanupVarDeclMarking(); 4690 4691 enum TryCaptureKind { 4692 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef 4693 }; 4694 4695 /// Try to capture the given variable. 4696 /// 4697 /// \param Var The variable to capture. 4698 /// 4699 /// \param Loc The location at which the capture occurs. 4700 /// 4701 /// \param Kind The kind of capture, which may be implicit (for either a 4702 /// block or a lambda), or explicit by-value or by-reference (for a lambda). 4703 /// 4704 /// \param EllipsisLoc The location of the ellipsis, if one is provided in 4705 /// an explicit lambda capture. 4706 /// 4707 /// \param BuildAndDiagnose Whether we are actually supposed to add the 4708 /// captures or diagnose errors. If false, this routine merely check whether 4709 /// the capture can occur without performing the capture itself or complaining 4710 /// if the variable cannot be captured. 4711 /// 4712 /// \param CaptureType Will be set to the type of the field used to capture 4713 /// this variable in the innermost block or lambda. Only valid when the 4714 /// variable can be captured. 4715 /// 4716 /// \param DeclRefType Will be set to the type of a reference to the capture 4717 /// from within the current scope. Only valid when the variable can be 4718 /// captured. 4719 /// 4720 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index 4721 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. 4722 /// This is useful when enclosing lambdas must speculatively capture 4723 /// variables that may or may not be used in certain specializations of 4724 /// a nested generic lambda. 4725 /// 4726 /// \returns true if an error occurred (i.e., the variable cannot be 4727 /// captured) and false if the capture succeeded. 4728 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, 4729 SourceLocation EllipsisLoc, bool BuildAndDiagnose, 4730 QualType &CaptureType, 4731 QualType &DeclRefType, 4732 const unsigned *const FunctionScopeIndexToStopAt); 4733 4734 /// Try to capture the given variable. 4735 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 4736 TryCaptureKind Kind = TryCapture_Implicit, 4737 SourceLocation EllipsisLoc = SourceLocation()); 4738 4739 /// Checks if the variable must be captured. 4740 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc); 4741 4742 /// Given a variable, determine the type that a reference to that 4743 /// variable will have in the given scope. 4744 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); 4745 4746 /// Mark all of the declarations referenced within a particular AST node as 4747 /// referenced. Used when template instantiation instantiates a non-dependent 4748 /// type -- entities referenced by the type are now referenced. 4749 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); 4750 void MarkDeclarationsReferencedInExpr(Expr *E, 4751 bool SkipLocalVariables = false); 4752 4753 /// Try to recover by turning the given expression into a 4754 /// call. Returns true if recovery was attempted or an error was 4755 /// emitted; this may also leave the ExprResult invalid. 4756 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, 4757 bool ForceComplain = false, 4758 bool (*IsPlausibleResult)(QualType) = nullptr); 4759 4760 /// Figure out if an expression could be turned into a call. 4761 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, 4762 UnresolvedSetImpl &NonTemplateOverloads); 4763 4764 /// Try to convert an expression \p E to type \p Ty. Returns the result of the 4765 /// conversion. 4766 ExprResult tryConvertExprToType(Expr *E, QualType Ty); 4767 4768 /// Conditionally issue a diagnostic based on the current 4769 /// evaluation context. 4770 /// 4771 /// \param Statement If Statement is non-null, delay reporting the 4772 /// diagnostic until the function body is parsed, and then do a basic 4773 /// reachability analysis to determine if the statement is reachable. 4774 /// If it is unreachable, the diagnostic will not be emitted. 4775 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 4776 const PartialDiagnostic &PD); 4777 /// Similar, but diagnostic is only produced if all the specified statements 4778 /// are reachable. 4779 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 4780 const PartialDiagnostic &PD); 4781 4782 // Primary Expressions. 4783 SourceRange getExprRange(Expr *E) const; 4784 4785 ExprResult ActOnIdExpression( 4786 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 4787 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, 4788 CorrectionCandidateCallback *CCC = nullptr, 4789 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr); 4790 4791 void DecomposeUnqualifiedId(const UnqualifiedId &Id, 4792 TemplateArgumentListInfo &Buffer, 4793 DeclarationNameInfo &NameInfo, 4794 const TemplateArgumentListInfo *&TemplateArgs); 4795 4796 bool 4797 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 4798 CorrectionCandidateCallback &CCC, 4799 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, 4800 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr); 4801 4802 DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 4803 IdentifierInfo *II); 4804 ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV); 4805 4806 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, 4807 IdentifierInfo *II, 4808 bool AllowBuiltinCreation=false); 4809 4810 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, 4811 SourceLocation TemplateKWLoc, 4812 const DeclarationNameInfo &NameInfo, 4813 bool isAddressOfOperand, 4814 const TemplateArgumentListInfo *TemplateArgs); 4815 4816 /// If \p D cannot be odr-used in the current expression evaluation context, 4817 /// return a reason explaining why. Otherwise, return NOUR_None. 4818 NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D); 4819 4820 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 4821 SourceLocation Loc, 4822 const CXXScopeSpec *SS = nullptr); 4823 DeclRefExpr * 4824 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 4825 const DeclarationNameInfo &NameInfo, 4826 const CXXScopeSpec *SS = nullptr, 4827 NamedDecl *FoundD = nullptr, 4828 SourceLocation TemplateKWLoc = SourceLocation(), 4829 const TemplateArgumentListInfo *TemplateArgs = nullptr); 4830 DeclRefExpr * 4831 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 4832 const DeclarationNameInfo &NameInfo, 4833 NestedNameSpecifierLoc NNS, 4834 NamedDecl *FoundD = nullptr, 4835 SourceLocation TemplateKWLoc = SourceLocation(), 4836 const TemplateArgumentListInfo *TemplateArgs = nullptr); 4837 4838 ExprResult 4839 BuildAnonymousStructUnionMemberReference( 4840 const CXXScopeSpec &SS, 4841 SourceLocation nameLoc, 4842 IndirectFieldDecl *indirectField, 4843 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none), 4844 Expr *baseObjectExpr = nullptr, 4845 SourceLocation opLoc = SourceLocation()); 4846 4847 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, 4848 SourceLocation TemplateKWLoc, 4849 LookupResult &R, 4850 const TemplateArgumentListInfo *TemplateArgs, 4851 const Scope *S); 4852 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, 4853 SourceLocation TemplateKWLoc, 4854 LookupResult &R, 4855 const TemplateArgumentListInfo *TemplateArgs, 4856 bool IsDefiniteInstance, 4857 const Scope *S); 4858 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, 4859 const LookupResult &R, 4860 bool HasTrailingLParen); 4861 4862 ExprResult 4863 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 4864 const DeclarationNameInfo &NameInfo, 4865 bool IsAddressOfOperand, const Scope *S, 4866 TypeSourceInfo **RecoveryTSI = nullptr); 4867 4868 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, 4869 SourceLocation TemplateKWLoc, 4870 const DeclarationNameInfo &NameInfo, 4871 const TemplateArgumentListInfo *TemplateArgs); 4872 4873 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, 4874 LookupResult &R, 4875 bool NeedsADL, 4876 bool AcceptInvalidDecl = false); 4877 ExprResult BuildDeclarationNameExpr( 4878 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 4879 NamedDecl *FoundD = nullptr, 4880 const TemplateArgumentListInfo *TemplateArgs = nullptr, 4881 bool AcceptInvalidDecl = false); 4882 4883 ExprResult BuildLiteralOperatorCall(LookupResult &R, 4884 DeclarationNameInfo &SuffixInfo, 4885 ArrayRef<Expr *> Args, 4886 SourceLocation LitEndLoc, 4887 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); 4888 4889 ExprResult BuildPredefinedExpr(SourceLocation Loc, 4890 PredefinedExpr::IdentKind IK); 4891 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); 4892 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); 4893 4894 ExprResult BuildUniqueStableName(SourceLocation Loc, TypeSourceInfo *Operand); 4895 ExprResult BuildUniqueStableName(SourceLocation Loc, Expr *E); 4896 ExprResult ActOnUniqueStableNameExpr(SourceLocation OpLoc, 4897 SourceLocation LParen, 4898 SourceLocation RParen, ParsedType Ty); 4899 ExprResult ActOnUniqueStableNameExpr(SourceLocation OpLoc, 4900 SourceLocation LParen, 4901 SourceLocation RParen, Expr *E); 4902 4903 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc); 4904 4905 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr); 4906 ExprResult ActOnCharacterConstant(const Token &Tok, 4907 Scope *UDLScope = nullptr); 4908 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); 4909 ExprResult ActOnNoChangeBoundsExpr(SourceLocation L, SourceLocation R, 4910 Expr *E); 4911 ExprResult ActOnParenListExpr(SourceLocation L, 4912 SourceLocation R, 4913 MultiExprArg Val); 4914 4915 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 4916 /// fragments (e.g. "foo" "bar" L"baz"). 4917 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks, 4918 Scope *UDLScope = nullptr); 4919 4920 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, 4921 SourceLocation DefaultLoc, 4922 SourceLocation RParenLoc, 4923 Expr *ControllingExpr, 4924 ArrayRef<ParsedType> ArgTypes, 4925 ArrayRef<Expr *> ArgExprs); 4926 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, 4927 SourceLocation DefaultLoc, 4928 SourceLocation RParenLoc, 4929 Expr *ControllingExpr, 4930 ArrayRef<TypeSourceInfo *> Types, 4931 ArrayRef<Expr *> Exprs); 4932 4933 // Binary/Unary Operators. 'Tok' is the token for the operator. 4934 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 4935 Expr *InputExpr); 4936 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, 4937 UnaryOperatorKind Opc, Expr *Input); 4938 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 4939 tok::TokenKind Op, Expr *Input); 4940 4941 bool isQualifiedMemberAccess(Expr *E); 4942 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc); 4943 4944 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4945 SourceLocation OpLoc, 4946 UnaryExprOrTypeTrait ExprKind, 4947 SourceRange R); 4948 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4949 UnaryExprOrTypeTrait ExprKind); 4950 ExprResult 4951 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4952 UnaryExprOrTypeTrait ExprKind, 4953 bool IsType, void *TyOrEx, 4954 SourceRange ArgRange); 4955 4956 ExprResult CheckPlaceholderExpr(Expr *E); 4957 bool CheckVecStepExpr(Expr *E); 4958 4959 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); 4960 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, 4961 SourceRange ExprRange, 4962 UnaryExprOrTypeTrait ExprKind); 4963 ExprResult ActOnSizeofParameterPackExpr(Scope *S, 4964 SourceLocation OpLoc, 4965 IdentifierInfo &Name, 4966 SourceLocation NameLoc, 4967 SourceLocation RParenLoc); 4968 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4969 tok::TokenKind Kind, Expr *Input); 4970 4971 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, 4972 Expr *Idx, SourceLocation RLoc); 4973 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4974 Expr *Idx, SourceLocation RLoc); 4975 4976 ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4977 Expr *ColumnIdx, 4978 SourceLocation RBLoc); 4979 4980 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4981 Expr *LowerBound, 4982 SourceLocation ColonLocFirst, 4983 SourceLocation ColonLocSecond, 4984 Expr *Length, Expr *Stride, 4985 SourceLocation RBLoc); 4986 ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 4987 SourceLocation RParenLoc, 4988 ArrayRef<Expr *> Dims, 4989 ArrayRef<SourceRange> Brackets); 4990 4991 /// Data structure for iterator expression. 4992 struct OMPIteratorData { 4993 IdentifierInfo *DeclIdent = nullptr; 4994 SourceLocation DeclIdentLoc; 4995 ParsedType Type; 4996 OMPIteratorExpr::IteratorRange Range; 4997 SourceLocation AssignLoc; 4998 SourceLocation ColonLoc; 4999 SourceLocation SecColonLoc; 5000 }; 5001 5002 ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5003 SourceLocation LLoc, SourceLocation RLoc, 5004 ArrayRef<OMPIteratorData> Data); 5005 5006 // This struct is for use by ActOnMemberAccess to allow 5007 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after 5008 // changing the access operator from a '.' to a '->' (to see if that is the 5009 // change needed to fix an error about an unknown member, e.g. when the class 5010 // defines a custom operator->). 5011 struct ActOnMemberAccessExtraArgs { 5012 Scope *S; 5013 UnqualifiedId &Id; 5014 Decl *ObjCImpDecl; 5015 }; 5016 5017 ExprResult BuildMemberReferenceExpr( 5018 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, 5019 CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 5020 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, 5021 const TemplateArgumentListInfo *TemplateArgs, 5022 const Scope *S, 5023 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); 5024 5025 ExprResult 5026 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, 5027 bool IsArrow, const CXXScopeSpec &SS, 5028 SourceLocation TemplateKWLoc, 5029 NamedDecl *FirstQualifierInScope, LookupResult &R, 5030 const TemplateArgumentListInfo *TemplateArgs, 5031 const Scope *S, 5032 bool SuppressQualifierCheck = false, 5033 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); 5034 5035 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, 5036 SourceLocation OpLoc, 5037 const CXXScopeSpec &SS, FieldDecl *Field, 5038 DeclAccessPair FoundDecl, 5039 const DeclarationNameInfo &MemberNameInfo); 5040 5041 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); 5042 5043 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, 5044 const CXXScopeSpec &SS, 5045 const LookupResult &R); 5046 5047 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, 5048 bool IsArrow, SourceLocation OpLoc, 5049 const CXXScopeSpec &SS, 5050 SourceLocation TemplateKWLoc, 5051 NamedDecl *FirstQualifierInScope, 5052 const DeclarationNameInfo &NameInfo, 5053 const TemplateArgumentListInfo *TemplateArgs); 5054 5055 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, 5056 SourceLocation OpLoc, 5057 tok::TokenKind OpKind, 5058 CXXScopeSpec &SS, 5059 SourceLocation TemplateKWLoc, 5060 UnqualifiedId &Member, 5061 Decl *ObjCImpDecl); 5062 5063 MemberExpr * 5064 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, 5065 const CXXScopeSpec *SS, SourceLocation TemplateKWLoc, 5066 ValueDecl *Member, DeclAccessPair FoundDecl, 5067 bool HadMultipleCandidates, 5068 const DeclarationNameInfo &MemberNameInfo, QualType Ty, 5069 ExprValueKind VK, ExprObjectKind OK, 5070 const TemplateArgumentListInfo *TemplateArgs = nullptr); 5071 MemberExpr * 5072 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, 5073 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, 5074 ValueDecl *Member, DeclAccessPair FoundDecl, 5075 bool HadMultipleCandidates, 5076 const DeclarationNameInfo &MemberNameInfo, QualType Ty, 5077 ExprValueKind VK, ExprObjectKind OK, 5078 const TemplateArgumentListInfo *TemplateArgs = nullptr); 5079 5080 void ActOnDefaultCtorInitializers(Decl *CDtorDecl); 5081 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5082 FunctionDecl *FDecl, 5083 const FunctionProtoType *Proto, 5084 ArrayRef<Expr *> Args, 5085 SourceLocation RParenLoc, 5086 bool ExecConfig = false); 5087 void CheckStaticArrayArgument(SourceLocation CallLoc, 5088 ParmVarDecl *Param, 5089 const Expr *ArgExpr); 5090 5091 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5092 /// This provides the location of the left/right parens and a list of comma 5093 /// locations. 5094 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 5095 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5096 Expr *ExecConfig = nullptr); 5097 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 5098 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5099 Expr *ExecConfig = nullptr, 5100 bool IsExecConfig = false); 5101 enum class AtomicArgumentOrder { API, AST }; 5102 ExprResult 5103 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 5104 SourceLocation RParenLoc, MultiExprArg Args, 5105 AtomicExpr::AtomicOp Op, 5106 AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API); 5107 ExprResult 5108 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, 5109 ArrayRef<Expr *> Arg, SourceLocation RParenLoc, 5110 Expr *Config = nullptr, bool IsExecConfig = false, 5111 ADLCallKind UsesADL = ADLCallKind::NotADL); 5112 5113 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 5114 MultiExprArg ExecConfig, 5115 SourceLocation GGGLoc); 5116 5117 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5118 Declarator &D, ParsedType &Ty, 5119 SourceLocation RParenLoc, Expr *CastExpr); 5120 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, 5121 TypeSourceInfo *Ty, 5122 SourceLocation RParenLoc, 5123 Expr *Op); 5124 CastKind PrepareScalarCast(ExprResult &src, QualType destType); 5125 5126 /// Build an altivec or OpenCL literal. 5127 ExprResult BuildVectorLiteral(SourceLocation LParenLoc, 5128 SourceLocation RParenLoc, Expr *E, 5129 TypeSourceInfo *TInfo); 5130 5131 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); 5132 5133 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, 5134 ParsedType Ty, 5135 SourceLocation RParenLoc, 5136 Expr *InitExpr); 5137 5138 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, 5139 TypeSourceInfo *TInfo, 5140 SourceLocation RParenLoc, 5141 Expr *LiteralExpr); 5142 5143 ExprResult ActOnInitList(SourceLocation LBraceLoc, 5144 MultiExprArg InitArgList, 5145 SourceLocation RBraceLoc); 5146 5147 ExprResult BuildInitList(SourceLocation LBraceLoc, 5148 MultiExprArg InitArgList, 5149 SourceLocation RBraceLoc); 5150 5151 ExprResult ActOnDesignatedInitializer(Designation &Desig, 5152 SourceLocation EqualOrColonLoc, 5153 bool GNUSyntax, 5154 ExprResult Init); 5155 5156 private: 5157 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind); 5158 5159 public: 5160 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, 5161 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); 5162 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, 5163 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); 5164 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, 5165 Expr *LHSExpr, Expr *RHSExpr); 5166 5167 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc); 5168 5169 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 5170 /// in the case of a the GNU conditional expr extension. 5171 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, 5172 SourceLocation ColonLoc, 5173 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); 5174 5175 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 5176 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 5177 LabelDecl *TheDecl); 5178 5179 void ActOnStartStmtExpr(); 5180 ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 5181 SourceLocation RPLoc); 5182 ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 5183 SourceLocation RPLoc, unsigned TemplateDepth); 5184 // Handle the final expression in a statement expression. 5185 ExprResult ActOnStmtExprResult(ExprResult E); 5186 void ActOnStmtExprError(); 5187 5188 // __builtin_offsetof(type, identifier(.identifier|[expr])*) 5189 struct OffsetOfComponent { 5190 SourceLocation LocStart, LocEnd; 5191 bool isBrackets; // true if [expr], false if .ident 5192 union { 5193 IdentifierInfo *IdentInfo; 5194 Expr *E; 5195 } U; 5196 }; 5197 5198 /// __builtin_offsetof(type, a.b[123][456].c) 5199 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 5200 TypeSourceInfo *TInfo, 5201 ArrayRef<OffsetOfComponent> Components, 5202 SourceLocation RParenLoc); 5203 ExprResult ActOnBuiltinOffsetOf(Scope *S, 5204 SourceLocation BuiltinLoc, 5205 SourceLocation TypeLoc, 5206 ParsedType ParsedArgTy, 5207 ArrayRef<OffsetOfComponent> Components, 5208 SourceLocation RParenLoc); 5209 5210 // __builtin_choose_expr(constExpr, expr1, expr2) 5211 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, 5212 Expr *CondExpr, Expr *LHSExpr, 5213 Expr *RHSExpr, SourceLocation RPLoc); 5214 5215 // __builtin_va_arg(expr, type) 5216 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 5217 SourceLocation RPLoc); 5218 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, 5219 TypeSourceInfo *TInfo, SourceLocation RPLoc); 5220 5221 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(), 5222 // __builtin_COLUMN() 5223 ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 5224 SourceLocation BuiltinLoc, 5225 SourceLocation RPLoc); 5226 5227 // Build a potentially resolved SourceLocExpr. 5228 ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 5229 SourceLocation BuiltinLoc, SourceLocation RPLoc, 5230 DeclContext *ParentContext); 5231 5232 // __null 5233 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); 5234 5235 bool CheckCaseExpression(Expr *E); 5236 5237 /// Describes the result of an "if-exists" condition check. 5238 enum IfExistsResult { 5239 /// The symbol exists. 5240 IER_Exists, 5241 5242 /// The symbol does not exist. 5243 IER_DoesNotExist, 5244 5245 /// The name is a dependent name, so the results will differ 5246 /// from one instantiation to the next. 5247 IER_Dependent, 5248 5249 /// An error occurred. 5250 IER_Error 5251 }; 5252 5253 IfExistsResult 5254 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, 5255 const DeclarationNameInfo &TargetNameInfo); 5256 5257 IfExistsResult 5258 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, 5259 bool IsIfExists, CXXScopeSpec &SS, 5260 UnqualifiedId &Name); 5261 5262 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, 5263 bool IsIfExists, 5264 NestedNameSpecifierLoc QualifierLoc, 5265 DeclarationNameInfo NameInfo, 5266 Stmt *Nested); 5267 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, 5268 bool IsIfExists, 5269 CXXScopeSpec &SS, UnqualifiedId &Name, 5270 Stmt *Nested); 5271 5272 //===------------------------- "Block" Extension ------------------------===// 5273 5274 /// ActOnBlockStart - This callback is invoked when a block literal is 5275 /// started. 5276 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); 5277 5278 /// ActOnBlockArguments - This callback allows processing of block arguments. 5279 /// If there are no arguments, this is still invoked. 5280 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 5281 Scope *CurScope); 5282 5283 /// ActOnBlockError - If there is an error parsing a block, this callback 5284 /// is invoked to pop the information about the block from the action impl. 5285 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); 5286 5287 /// ActOnBlockStmtExpr - This is called when the body of a block statement 5288 /// literal was successfully completed. ^(int x){...} 5289 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, 5290 Scope *CurScope); 5291 5292 //===---------------------------- Clang Extensions ----------------------===// 5293 5294 /// __builtin_convertvector(...) 5295 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5296 SourceLocation BuiltinLoc, 5297 SourceLocation RParenLoc); 5298 5299 //===---------------------------- OpenCL Features -----------------------===// 5300 5301 /// __builtin_astype(...) 5302 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5303 SourceLocation BuiltinLoc, 5304 SourceLocation RParenLoc); 5305 5306 //===---------------------------- C++ Features --------------------------===// 5307 5308 // Act on C++ namespaces 5309 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, 5310 SourceLocation NamespaceLoc, 5311 SourceLocation IdentLoc, IdentifierInfo *Ident, 5312 SourceLocation LBrace, 5313 const ParsedAttributesView &AttrList, 5314 UsingDirectiveDecl *&UsingDecl); 5315 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); 5316 5317 NamespaceDecl *getStdNamespace() const; 5318 NamespaceDecl *getOrCreateStdNamespace(); 5319 5320 NamespaceDecl *lookupStdExperimentalNamespace(); 5321 5322 CXXRecordDecl *getStdBadAlloc() const; 5323 EnumDecl *getStdAlignValT() const; 5324 5325 private: 5326 // A cache representing if we've fully checked the various comparison category 5327 // types stored in ASTContext. The bit-index corresponds to the integer value 5328 // of a ComparisonCategoryType enumerator. 5329 llvm::SmallBitVector FullyCheckedComparisonCategories; 5330 5331 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 5332 CXXScopeSpec &SS, 5333 ParsedType TemplateTypeTy, 5334 IdentifierInfo *MemberOrBase); 5335 5336 public: 5337 enum class ComparisonCategoryUsage { 5338 /// The '<=>' operator was used in an expression and a builtin operator 5339 /// was selected. 5340 OperatorInExpression, 5341 /// A defaulted 'operator<=>' needed the comparison category. This 5342 /// typically only applies to 'std::strong_ordering', due to the implicit 5343 /// fallback return value. 5344 DefaultedOperator, 5345 }; 5346 5347 /// Lookup the specified comparison category types in the standard 5348 /// library, an check the VarDecls possibly returned by the operator<=> 5349 /// builtins for that type. 5350 /// 5351 /// \return The type of the comparison category type corresponding to the 5352 /// specified Kind, or a null type if an error occurs 5353 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, 5354 SourceLocation Loc, 5355 ComparisonCategoryUsage Usage); 5356 5357 /// Tests whether Ty is an instance of std::initializer_list and, if 5358 /// it is and Element is not NULL, assigns the element type to Element. 5359 bool isStdInitializerList(QualType Ty, QualType *Element); 5360 5361 /// Looks for the std::initializer_list template and instantiates it 5362 /// with Element, or emits an error if it's not found. 5363 /// 5364 /// \returns The instantiated template, or null on error. 5365 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); 5366 5367 /// Determine whether Ctor is an initializer-list constructor, as 5368 /// defined in [dcl.init.list]p2. 5369 bool isInitListConstructor(const FunctionDecl *Ctor); 5370 5371 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, 5372 SourceLocation NamespcLoc, CXXScopeSpec &SS, 5373 SourceLocation IdentLoc, 5374 IdentifierInfo *NamespcName, 5375 const ParsedAttributesView &AttrList); 5376 5377 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); 5378 5379 Decl *ActOnNamespaceAliasDef(Scope *CurScope, 5380 SourceLocation NamespaceLoc, 5381 SourceLocation AliasLoc, 5382 IdentifierInfo *Alias, 5383 CXXScopeSpec &SS, 5384 SourceLocation IdentLoc, 5385 IdentifierInfo *Ident); 5386 5387 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); 5388 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, 5389 const LookupResult &PreviousDecls, 5390 UsingShadowDecl *&PrevShadow); 5391 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD, 5392 NamedDecl *Target, 5393 UsingShadowDecl *PrevDecl); 5394 5395 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 5396 bool HasTypenameKeyword, 5397 const CXXScopeSpec &SS, 5398 SourceLocation NameLoc, 5399 const LookupResult &Previous); 5400 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, 5401 bool HasTypename, 5402 const CXXScopeSpec &SS, 5403 const DeclarationNameInfo &NameInfo, 5404 SourceLocation NameLoc); 5405 5406 NamedDecl *BuildUsingDeclaration( 5407 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 5408 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 5409 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 5410 const ParsedAttributesView &AttrList, bool IsInstantiation); 5411 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 5412 ArrayRef<NamedDecl *> Expansions); 5413 5414 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); 5415 5416 /// Given a derived-class using shadow declaration for a constructor and the 5417 /// correspnding base class constructor, find or create the implicit 5418 /// synthesized derived class constructor to use for this initialization. 5419 CXXConstructorDecl * 5420 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, 5421 ConstructorUsingShadowDecl *DerivedShadow); 5422 5423 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, 5424 SourceLocation UsingLoc, 5425 SourceLocation TypenameLoc, CXXScopeSpec &SS, 5426 UnqualifiedId &Name, SourceLocation EllipsisLoc, 5427 const ParsedAttributesView &AttrList); 5428 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, 5429 MultiTemplateParamsArg TemplateParams, 5430 SourceLocation UsingLoc, UnqualifiedId &Name, 5431 const ParsedAttributesView &AttrList, 5432 TypeResult Type, Decl *DeclFromDeclSpec); 5433 5434 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 5435 /// including handling of its default argument expressions. 5436 /// 5437 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind 5438 ExprResult 5439 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 5440 NamedDecl *FoundDecl, 5441 CXXConstructorDecl *Constructor, MultiExprArg Exprs, 5442 bool HadMultipleCandidates, bool IsListInitialization, 5443 bool IsStdInitListInitialization, 5444 bool RequiresZeroInit, unsigned ConstructKind, 5445 SourceRange ParenRange); 5446 5447 /// Build a CXXConstructExpr whose constructor has already been resolved if 5448 /// it denotes an inherited constructor. 5449 ExprResult 5450 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 5451 CXXConstructorDecl *Constructor, bool Elidable, 5452 MultiExprArg Exprs, 5453 bool HadMultipleCandidates, bool IsListInitialization, 5454 bool IsStdInitListInitialization, 5455 bool RequiresZeroInit, unsigned ConstructKind, 5456 SourceRange ParenRange); 5457 5458 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if 5459 // the constructor can be elidable? 5460 ExprResult 5461 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 5462 NamedDecl *FoundDecl, 5463 CXXConstructorDecl *Constructor, bool Elidable, 5464 MultiExprArg Exprs, bool HadMultipleCandidates, 5465 bool IsListInitialization, 5466 bool IsStdInitListInitialization, bool RequiresZeroInit, 5467 unsigned ConstructKind, SourceRange ParenRange); 5468 5469 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field); 5470 5471 5472 /// Instantiate or parse a C++ default argument expression as necessary. 5473 /// Return true on error. 5474 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5475 ParmVarDecl *Param); 5476 5477 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating 5478 /// the default expr if needed. 5479 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5480 FunctionDecl *FD, 5481 ParmVarDecl *Param); 5482 5483 /// FinalizeVarWithDestructor - Prepare for calling destructor on the 5484 /// constructed variable. 5485 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); 5486 5487 /// Helper class that collects exception specifications for 5488 /// implicitly-declared special member functions. 5489 class ImplicitExceptionSpecification { 5490 // Pointer to allow copying 5491 Sema *Self; 5492 // We order exception specifications thus: 5493 // noexcept is the most restrictive, but is only used in C++11. 5494 // throw() comes next. 5495 // Then a throw(collected exceptions) 5496 // Finally no specification, which is expressed as noexcept(false). 5497 // throw(...) is used instead if any called function uses it. 5498 ExceptionSpecificationType ComputedEST; 5499 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; 5500 SmallVector<QualType, 4> Exceptions; 5501 ClearExceptions()5502 void ClearExceptions() { 5503 ExceptionsSeen.clear(); 5504 Exceptions.clear(); 5505 } 5506 5507 public: ImplicitExceptionSpecification(Sema & Self)5508 explicit ImplicitExceptionSpecification(Sema &Self) 5509 : Self(&Self), ComputedEST(EST_BasicNoexcept) { 5510 if (!Self.getLangOpts().CPlusPlus11) 5511 ComputedEST = EST_DynamicNone; 5512 } 5513 5514 /// Get the computed exception specification type. getExceptionSpecType()5515 ExceptionSpecificationType getExceptionSpecType() const { 5516 assert(!isComputedNoexcept(ComputedEST) && 5517 "noexcept(expr) should not be a possible result"); 5518 return ComputedEST; 5519 } 5520 5521 /// The number of exceptions in the exception specification. size()5522 unsigned size() const { return Exceptions.size(); } 5523 5524 /// The set of exceptions in the exception specification. data()5525 const QualType *data() const { return Exceptions.data(); } 5526 5527 /// Integrate another called method into the collected data. 5528 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); 5529 5530 /// Integrate an invoked expression into the collected data. CalledExpr(Expr * E)5531 void CalledExpr(Expr *E) { CalledStmt(E); } 5532 5533 /// Integrate an invoked statement into the collected data. 5534 void CalledStmt(Stmt *S); 5535 5536 /// Overwrite an EPI's exception specification with this 5537 /// computed exception specification. getExceptionSpec()5538 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const { 5539 FunctionProtoType::ExceptionSpecInfo ESI; 5540 ESI.Type = getExceptionSpecType(); 5541 if (ESI.Type == EST_Dynamic) { 5542 ESI.Exceptions = Exceptions; 5543 } else if (ESI.Type == EST_None) { 5544 /// C++11 [except.spec]p14: 5545 /// The exception-specification is noexcept(false) if the set of 5546 /// potential exceptions of the special member function contains "any" 5547 ESI.Type = EST_NoexceptFalse; 5548 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(), 5549 tok::kw_false).get(); 5550 } 5551 return ESI; 5552 } 5553 }; 5554 5555 /// Determine what sort of exception specification a defaulted 5556 /// copy constructor of a class will have. 5557 ImplicitExceptionSpecification 5558 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 5559 CXXMethodDecl *MD); 5560 5561 /// Determine what sort of exception specification a defaulted 5562 /// default constructor of a class will have, and whether the parameter 5563 /// will be const. 5564 ImplicitExceptionSpecification 5565 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD); 5566 5567 /// Determine what sort of exception specification a defaulted 5568 /// copy assignment operator of a class will have, and whether the 5569 /// parameter will be const. 5570 ImplicitExceptionSpecification 5571 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD); 5572 5573 /// Determine what sort of exception specification a defaulted move 5574 /// constructor of a class will have. 5575 ImplicitExceptionSpecification 5576 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD); 5577 5578 /// Determine what sort of exception specification a defaulted move 5579 /// assignment operator of a class will have. 5580 ImplicitExceptionSpecification 5581 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD); 5582 5583 /// Determine what sort of exception specification a defaulted 5584 /// destructor of a class will have. 5585 ImplicitExceptionSpecification 5586 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD); 5587 5588 /// Determine what sort of exception specification an inheriting 5589 /// constructor of a class will have. 5590 ImplicitExceptionSpecification 5591 ComputeInheritingCtorExceptionSpec(SourceLocation Loc, 5592 CXXConstructorDecl *CD); 5593 5594 /// Evaluate the implicit exception specification for a defaulted 5595 /// special member function. 5596 void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD); 5597 5598 /// Check the given noexcept-specifier, convert its expression, and compute 5599 /// the appropriate ExceptionSpecificationType. 5600 ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr, 5601 ExceptionSpecificationType &EST); 5602 5603 /// Check the given exception-specification and update the 5604 /// exception specification information with the results. 5605 void checkExceptionSpecification(bool IsTopLevel, 5606 ExceptionSpecificationType EST, 5607 ArrayRef<ParsedType> DynamicExceptions, 5608 ArrayRef<SourceRange> DynamicExceptionRanges, 5609 Expr *NoexceptExpr, 5610 SmallVectorImpl<QualType> &Exceptions, 5611 FunctionProtoType::ExceptionSpecInfo &ESI); 5612 5613 /// Determine if we're in a case where we need to (incorrectly) eagerly 5614 /// parse an exception specification to work around a libstdc++ bug. 5615 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D); 5616 5617 /// Add an exception-specification to the given member function 5618 /// (or member function template). The exception-specification was parsed 5619 /// after the method itself was declared. 5620 void actOnDelayedExceptionSpecification(Decl *Method, 5621 ExceptionSpecificationType EST, 5622 SourceRange SpecificationRange, 5623 ArrayRef<ParsedType> DynamicExceptions, 5624 ArrayRef<SourceRange> DynamicExceptionRanges, 5625 Expr *NoexceptExpr); 5626 5627 class InheritedConstructorInfo; 5628 5629 /// Determine if a special member function should have a deleted 5630 /// definition when it is defaulted. 5631 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5632 InheritedConstructorInfo *ICI = nullptr, 5633 bool Diagnose = false); 5634 5635 /// Produce notes explaining why a defaulted function was defined as deleted. 5636 void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD); 5637 5638 /// Declare the implicit default constructor for the given class. 5639 /// 5640 /// \param ClassDecl The class declaration into which the implicit 5641 /// default constructor will be added. 5642 /// 5643 /// \returns The implicitly-declared default constructor. 5644 CXXConstructorDecl *DeclareImplicitDefaultConstructor( 5645 CXXRecordDecl *ClassDecl); 5646 5647 /// DefineImplicitDefaultConstructor - Checks for feasibility of 5648 /// defining this constructor as the default constructor. 5649 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 5650 CXXConstructorDecl *Constructor); 5651 5652 /// Declare the implicit destructor for the given class. 5653 /// 5654 /// \param ClassDecl The class declaration into which the implicit 5655 /// destructor will be added. 5656 /// 5657 /// \returns The implicitly-declared destructor. 5658 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); 5659 5660 /// DefineImplicitDestructor - Checks for feasibility of 5661 /// defining this destructor as the default destructor. 5662 void DefineImplicitDestructor(SourceLocation CurrentLocation, 5663 CXXDestructorDecl *Destructor); 5664 5665 /// Build an exception spec for destructors that don't have one. 5666 /// 5667 /// C++11 says that user-defined destructors with no exception spec get one 5668 /// that looks as if the destructor was implicitly declared. 5669 void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor); 5670 5671 /// Define the specified inheriting constructor. 5672 void DefineInheritingConstructor(SourceLocation UseLoc, 5673 CXXConstructorDecl *Constructor); 5674 5675 /// Declare the implicit copy constructor for the given class. 5676 /// 5677 /// \param ClassDecl The class declaration into which the implicit 5678 /// copy constructor will be added. 5679 /// 5680 /// \returns The implicitly-declared copy constructor. 5681 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); 5682 5683 /// DefineImplicitCopyConstructor - Checks for feasibility of 5684 /// defining this constructor as the copy constructor. 5685 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 5686 CXXConstructorDecl *Constructor); 5687 5688 /// Declare the implicit move constructor for the given class. 5689 /// 5690 /// \param ClassDecl The Class declaration into which the implicit 5691 /// move constructor will be added. 5692 /// 5693 /// \returns The implicitly-declared move constructor, or NULL if it wasn't 5694 /// declared. 5695 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); 5696 5697 /// DefineImplicitMoveConstructor - Checks for feasibility of 5698 /// defining this constructor as the move constructor. 5699 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 5700 CXXConstructorDecl *Constructor); 5701 5702 /// Declare the implicit copy assignment operator for the given class. 5703 /// 5704 /// \param ClassDecl The class declaration into which the implicit 5705 /// copy assignment operator will be added. 5706 /// 5707 /// \returns The implicitly-declared copy assignment operator. 5708 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); 5709 5710 /// Defines an implicitly-declared copy assignment operator. 5711 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 5712 CXXMethodDecl *MethodDecl); 5713 5714 /// Declare the implicit move assignment operator for the given class. 5715 /// 5716 /// \param ClassDecl The Class declaration into which the implicit 5717 /// move assignment operator will be added. 5718 /// 5719 /// \returns The implicitly-declared move assignment operator, or NULL if it 5720 /// wasn't declared. 5721 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); 5722 5723 /// Defines an implicitly-declared move assignment operator. 5724 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 5725 CXXMethodDecl *MethodDecl); 5726 5727 /// Force the declaration of any implicitly-declared members of this 5728 /// class. 5729 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); 5730 5731 /// Check a completed declaration of an implicit special member. 5732 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD); 5733 5734 /// Determine whether the given function is an implicitly-deleted 5735 /// special member function. 5736 bool isImplicitlyDeleted(FunctionDecl *FD); 5737 5738 /// Check whether 'this' shows up in the type of a static member 5739 /// function after the (naturally empty) cv-qualifier-seq would be. 5740 /// 5741 /// \returns true if an error occurred. 5742 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); 5743 5744 /// Whether this' shows up in the exception specification of a static 5745 /// member function. 5746 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); 5747 5748 /// Check whether 'this' shows up in the attributes of the given 5749 /// static member function. 5750 /// 5751 /// \returns true if an error occurred. 5752 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); 5753 5754 /// MaybeBindToTemporary - If the passed in expression has a record type with 5755 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise 5756 /// it simply returns the passed in expression. 5757 ExprResult MaybeBindToTemporary(Expr *E); 5758 5759 /// Wrap the expression in a ConstantExpr if it is a potential immediate 5760 /// invocation. 5761 ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl); 5762 5763 bool CompleteConstructorCall(CXXConstructorDecl *Constructor, 5764 MultiExprArg ArgsPtr, 5765 SourceLocation Loc, 5766 SmallVectorImpl<Expr*> &ConvertedArgs, 5767 bool AllowExplicit = false, 5768 bool IsListInitialization = false); 5769 5770 ParsedType getInheritingConstructorName(CXXScopeSpec &SS, 5771 SourceLocation NameLoc, 5772 IdentifierInfo &Name); 5773 5774 ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc, 5775 Scope *S, CXXScopeSpec &SS, 5776 bool EnteringContext); 5777 ParsedType getDestructorName(SourceLocation TildeLoc, 5778 IdentifierInfo &II, SourceLocation NameLoc, 5779 Scope *S, CXXScopeSpec &SS, 5780 ParsedType ObjectType, 5781 bool EnteringContext); 5782 5783 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, 5784 ParsedType ObjectType); 5785 5786 // Checks that reinterpret casts don't have undefined behavior. 5787 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, 5788 bool IsDereference, SourceRange Range); 5789 5790 /// ActOnCXXNamedCast - Parse 5791 /// {dynamic,static,reinterpret,const,addrspace}_cast's. 5792 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, 5793 tok::TokenKind Kind, 5794 SourceLocation LAngleBracketLoc, 5795 Declarator &D, 5796 SourceLocation RAngleBracketLoc, 5797 SourceLocation LParenLoc, 5798 Expr *E, 5799 SourceLocation RParenLoc); 5800 5801 ExprResult BuildCXXNamedCast(SourceLocation OpLoc, 5802 tok::TokenKind Kind, 5803 TypeSourceInfo *Ty, 5804 Expr *E, 5805 SourceRange AngleBrackets, 5806 SourceRange Parens); 5807 5808 ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl, 5809 ExprResult Operand, 5810 SourceLocation RParenLoc); 5811 5812 ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI, 5813 Expr *Operand, SourceLocation RParenLoc); 5814 5815 ExprResult BuildCXXTypeId(QualType TypeInfoType, 5816 SourceLocation TypeidLoc, 5817 TypeSourceInfo *Operand, 5818 SourceLocation RParenLoc); 5819 ExprResult BuildCXXTypeId(QualType TypeInfoType, 5820 SourceLocation TypeidLoc, 5821 Expr *Operand, 5822 SourceLocation RParenLoc); 5823 5824 /// ActOnCXXTypeid - Parse typeid( something ). 5825 ExprResult ActOnCXXTypeid(SourceLocation OpLoc, 5826 SourceLocation LParenLoc, bool isType, 5827 void *TyOrExpr, 5828 SourceLocation RParenLoc); 5829 5830 ExprResult BuildCXXUuidof(QualType TypeInfoType, 5831 SourceLocation TypeidLoc, 5832 TypeSourceInfo *Operand, 5833 SourceLocation RParenLoc); 5834 ExprResult BuildCXXUuidof(QualType TypeInfoType, 5835 SourceLocation TypeidLoc, 5836 Expr *Operand, 5837 SourceLocation RParenLoc); 5838 5839 /// ActOnCXXUuidof - Parse __uuidof( something ). 5840 ExprResult ActOnCXXUuidof(SourceLocation OpLoc, 5841 SourceLocation LParenLoc, bool isType, 5842 void *TyOrExpr, 5843 SourceLocation RParenLoc); 5844 5845 /// Handle a C++1z fold-expression: ( expr op ... op expr ). 5846 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS, 5847 tok::TokenKind Operator, 5848 SourceLocation EllipsisLoc, Expr *RHS, 5849 SourceLocation RParenLoc); 5850 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS, 5851 BinaryOperatorKind Operator, 5852 SourceLocation EllipsisLoc, Expr *RHS, 5853 SourceLocation RParenLoc, 5854 Optional<unsigned> NumExpansions); 5855 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, 5856 BinaryOperatorKind Operator); 5857 5858 //// ActOnCXXThis - Parse 'this' pointer. 5859 ExprResult ActOnCXXThis(SourceLocation loc); 5860 5861 /// Build a CXXThisExpr and mark it referenced in the current context. 5862 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit); 5863 void MarkThisReferenced(CXXThisExpr *This); 5864 5865 /// Try to retrieve the type of the 'this' pointer. 5866 /// 5867 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. 5868 QualType getCurrentThisType(); 5869 5870 /// When non-NULL, the C++ 'this' expression is allowed despite the 5871 /// current context not being a non-static member function. In such cases, 5872 /// this provides the type used for 'this'. 5873 QualType CXXThisTypeOverride; 5874 5875 /// RAII object used to temporarily allow the C++ 'this' expression 5876 /// to be used, with the given qualifiers on the current class type. 5877 class CXXThisScopeRAII { 5878 Sema &S; 5879 QualType OldCXXThisTypeOverride; 5880 bool Enabled; 5881 5882 public: 5883 /// Introduce a new scope where 'this' may be allowed (when enabled), 5884 /// using the given declaration (which is either a class template or a 5885 /// class) along with the given qualifiers. 5886 /// along with the qualifiers placed on '*this'. 5887 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, 5888 bool Enabled = true); 5889 5890 ~CXXThisScopeRAII(); 5891 }; 5892 5893 /// Make sure the value of 'this' is actually available in the current 5894 /// context, if it is a potentially evaluated context. 5895 /// 5896 /// \param Loc The location at which the capture of 'this' occurs. 5897 /// 5898 /// \param Explicit Whether 'this' is explicitly captured in a lambda 5899 /// capture list. 5900 /// 5901 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index 5902 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. 5903 /// This is useful when enclosing lambdas must speculatively capture 5904 /// 'this' that may or may not be used in certain specializations of 5905 /// a nested generic lambda (depending on whether the name resolves to 5906 /// a non-static member function or a static function). 5907 /// \return returns 'true' if failed, 'false' if success. 5908 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false, 5909 bool BuildAndDiagnose = true, 5910 const unsigned *const FunctionScopeIndexToStopAt = nullptr, 5911 bool ByCopy = false); 5912 5913 /// Determine whether the given type is the type of *this that is used 5914 /// outside of the body of a member function for a type that is currently 5915 /// being defined. 5916 bool isThisOutsideMemberFunctionBody(QualType BaseType); 5917 5918 /// ActOnCXXBoolLiteral - Parse {true,false} literals. 5919 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 5920 5921 5922 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 5923 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 5924 5925 ExprResult 5926 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs, 5927 SourceLocation AtLoc, SourceLocation RParen); 5928 5929 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 5930 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); 5931 5932 //// ActOnCXXThrow - Parse throw expressions. 5933 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); 5934 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, 5935 bool IsThrownVarInScope); 5936 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E); 5937 5938 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 5939 /// Can be interpreted either as function-style casting ("int(x)") 5940 /// or class type construction ("ClassType(x,y,z)") 5941 /// or creation of a value-initialized type ("int()"). 5942 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, 5943 SourceLocation LParenOrBraceLoc, 5944 MultiExprArg Exprs, 5945 SourceLocation RParenOrBraceLoc, 5946 bool ListInitialization); 5947 5948 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, 5949 SourceLocation LParenLoc, 5950 MultiExprArg Exprs, 5951 SourceLocation RParenLoc, 5952 bool ListInitialization); 5953 5954 /// ActOnCXXNew - Parsed a C++ 'new' expression. 5955 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 5956 SourceLocation PlacementLParen, 5957 MultiExprArg PlacementArgs, 5958 SourceLocation PlacementRParen, 5959 SourceRange TypeIdParens, Declarator &D, 5960 Expr *Initializer); 5961 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, 5962 SourceLocation PlacementLParen, 5963 MultiExprArg PlacementArgs, 5964 SourceLocation PlacementRParen, 5965 SourceRange TypeIdParens, 5966 QualType AllocType, 5967 TypeSourceInfo *AllocTypeInfo, 5968 Optional<Expr *> ArraySize, 5969 SourceRange DirectInitRange, 5970 Expr *Initializer); 5971 5972 /// Determine whether \p FD is an aligned allocation or deallocation 5973 /// function that is unavailable. 5974 bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const; 5975 5976 /// Produce diagnostics if \p FD is an aligned allocation or deallocation 5977 /// function that is unavailable. 5978 void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, 5979 SourceLocation Loc); 5980 5981 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, 5982 SourceRange R); 5983 5984 /// The scope in which to find allocation functions. 5985 enum AllocationFunctionScope { 5986 /// Only look for allocation functions in the global scope. 5987 AFS_Global, 5988 /// Only look for allocation functions in the scope of the 5989 /// allocated class. 5990 AFS_Class, 5991 /// Look for allocation functions in both the global scope 5992 /// and in the scope of the allocated class. 5993 AFS_Both 5994 }; 5995 5996 /// Finds the overloads of operator new and delete that are appropriate 5997 /// for the allocation. 5998 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 5999 AllocationFunctionScope NewScope, 6000 AllocationFunctionScope DeleteScope, 6001 QualType AllocType, bool IsArray, 6002 bool &PassAlignment, MultiExprArg PlaceArgs, 6003 FunctionDecl *&OperatorNew, 6004 FunctionDecl *&OperatorDelete, 6005 bool Diagnose = true); 6006 void DeclareGlobalNewDelete(); 6007 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, 6008 ArrayRef<QualType> Params); 6009 6010 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 6011 DeclarationName Name, FunctionDecl* &Operator, 6012 bool Diagnose = true); 6013 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc, 6014 bool CanProvideSize, 6015 bool Overaligned, 6016 DeclarationName Name); 6017 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc, 6018 CXXRecordDecl *RD); 6019 6020 /// ActOnCXXDelete - Parsed a C++ 'delete' expression 6021 ExprResult ActOnCXXDelete(SourceLocation StartLoc, 6022 bool UseGlobal, bool ArrayForm, 6023 Expr *Operand); 6024 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, 6025 bool IsDelete, bool CallCanBeVirtual, 6026 bool WarnOnNonAbstractTypes, 6027 SourceLocation DtorLoc); 6028 6029 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, 6030 Expr *Operand, SourceLocation RParen); 6031 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 6032 SourceLocation RParen); 6033 6034 /// Parsed one of the type trait support pseudo-functions. 6035 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 6036 ArrayRef<ParsedType> Args, 6037 SourceLocation RParenLoc); 6038 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 6039 ArrayRef<TypeSourceInfo *> Args, 6040 SourceLocation RParenLoc); 6041 6042 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support 6043 /// pseudo-functions. 6044 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, 6045 SourceLocation KWLoc, 6046 ParsedType LhsTy, 6047 Expr *DimExpr, 6048 SourceLocation RParen); 6049 6050 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, 6051 SourceLocation KWLoc, 6052 TypeSourceInfo *TSInfo, 6053 Expr *DimExpr, 6054 SourceLocation RParen); 6055 6056 /// ActOnExpressionTrait - Parsed one of the unary type trait support 6057 /// pseudo-functions. 6058 ExprResult ActOnExpressionTrait(ExpressionTrait OET, 6059 SourceLocation KWLoc, 6060 Expr *Queried, 6061 SourceLocation RParen); 6062 6063 ExprResult BuildExpressionTrait(ExpressionTrait OET, 6064 SourceLocation KWLoc, 6065 Expr *Queried, 6066 SourceLocation RParen); 6067 6068 ExprResult ActOnStartCXXMemberReference(Scope *S, 6069 Expr *Base, 6070 SourceLocation OpLoc, 6071 tok::TokenKind OpKind, 6072 ParsedType &ObjectType, 6073 bool &MayBePseudoDestructor); 6074 6075 ExprResult BuildPseudoDestructorExpr(Expr *Base, 6076 SourceLocation OpLoc, 6077 tok::TokenKind OpKind, 6078 const CXXScopeSpec &SS, 6079 TypeSourceInfo *ScopeType, 6080 SourceLocation CCLoc, 6081 SourceLocation TildeLoc, 6082 PseudoDestructorTypeStorage DestroyedType); 6083 6084 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 6085 SourceLocation OpLoc, 6086 tok::TokenKind OpKind, 6087 CXXScopeSpec &SS, 6088 UnqualifiedId &FirstTypeName, 6089 SourceLocation CCLoc, 6090 SourceLocation TildeLoc, 6091 UnqualifiedId &SecondTypeName); 6092 6093 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 6094 SourceLocation OpLoc, 6095 tok::TokenKind OpKind, 6096 SourceLocation TildeLoc, 6097 const DeclSpec& DS); 6098 6099 /// MaybeCreateExprWithCleanups - If the current full-expression 6100 /// requires any cleanups, surround it with a ExprWithCleanups node. 6101 /// Otherwise, just returns the passed-in expression. 6102 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); 6103 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); 6104 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); 6105 6106 MaterializeTemporaryExpr * 6107 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, 6108 bool BoundToLvalueReference); 6109 ActOnFinishFullExpr(Expr * Expr,bool DiscardedValue)6110 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) { 6111 return ActOnFinishFullExpr( 6112 Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue); 6113 } 6114 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, 6115 bool DiscardedValue, bool IsConstexpr = false); 6116 StmtResult ActOnFinishFullStmt(Stmt *Stmt); 6117 6118 // Marks SS invalid if it represents an incomplete type. 6119 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); 6120 6121 DeclContext *computeDeclContext(QualType T); 6122 DeclContext *computeDeclContext(const CXXScopeSpec &SS, 6123 bool EnteringContext = false); 6124 bool isDependentScopeSpecifier(const CXXScopeSpec &SS); 6125 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); 6126 6127 /// The parser has parsed a global nested-name-specifier '::'. 6128 /// 6129 /// \param CCLoc The location of the '::'. 6130 /// 6131 /// \param SS The nested-name-specifier, which will be updated in-place 6132 /// to reflect the parsed nested-name-specifier. 6133 /// 6134 /// \returns true if an error occurred, false otherwise. 6135 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS); 6136 6137 /// The parser has parsed a '__super' nested-name-specifier. 6138 /// 6139 /// \param SuperLoc The location of the '__super' keyword. 6140 /// 6141 /// \param ColonColonLoc The location of the '::'. 6142 /// 6143 /// \param SS The nested-name-specifier, which will be updated in-place 6144 /// to reflect the parsed nested-name-specifier. 6145 /// 6146 /// \returns true if an error occurred, false otherwise. 6147 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, 6148 SourceLocation ColonColonLoc, CXXScopeSpec &SS); 6149 6150 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, 6151 bool *CanCorrect = nullptr); 6152 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); 6153 6154 /// Keeps information about an identifier in a nested-name-spec. 6155 /// 6156 struct NestedNameSpecInfo { 6157 /// The type of the object, if we're parsing nested-name-specifier in 6158 /// a member access expression. 6159 ParsedType ObjectType; 6160 6161 /// The identifier preceding the '::'. 6162 IdentifierInfo *Identifier; 6163 6164 /// The location of the identifier. 6165 SourceLocation IdentifierLoc; 6166 6167 /// The location of the '::'. 6168 SourceLocation CCLoc; 6169 6170 /// Creates info object for the most typical case. 6171 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, 6172 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType()) ObjectTypeNestedNameSpecInfo6173 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc), 6174 CCLoc(ColonColonLoc) { 6175 } 6176 NestedNameSpecInfoNestedNameSpecInfo6177 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, 6178 SourceLocation ColonColonLoc, QualType ObjectType) 6179 : ObjectType(ParsedType::make(ObjectType)), Identifier(II), 6180 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { 6181 } 6182 }; 6183 6184 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, 6185 NestedNameSpecInfo &IdInfo); 6186 6187 bool BuildCXXNestedNameSpecifier(Scope *S, 6188 NestedNameSpecInfo &IdInfo, 6189 bool EnteringContext, 6190 CXXScopeSpec &SS, 6191 NamedDecl *ScopeLookupResult, 6192 bool ErrorRecoveryLookup, 6193 bool *IsCorrectedToColon = nullptr, 6194 bool OnlyNamespace = false); 6195 6196 /// The parser has parsed a nested-name-specifier 'identifier::'. 6197 /// 6198 /// \param S The scope in which this nested-name-specifier occurs. 6199 /// 6200 /// \param IdInfo Parser information about an identifier in the 6201 /// nested-name-spec. 6202 /// 6203 /// \param EnteringContext Whether we're entering the context nominated by 6204 /// this nested-name-specifier. 6205 /// 6206 /// \param SS The nested-name-specifier, which is both an input 6207 /// parameter (the nested-name-specifier before this type) and an 6208 /// output parameter (containing the full nested-name-specifier, 6209 /// including this new type). 6210 /// 6211 /// \param ErrorRecoveryLookup If true, then this method is called to improve 6212 /// error recovery. In this case do not emit error message. 6213 /// 6214 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':' 6215 /// are allowed. The bool value pointed by this parameter is set to 'true' 6216 /// if the identifier is treated as if it was followed by ':', not '::'. 6217 /// 6218 /// \param OnlyNamespace If true, only considers namespaces in lookup. 6219 /// 6220 /// \returns true if an error occurred, false otherwise. 6221 bool ActOnCXXNestedNameSpecifier(Scope *S, 6222 NestedNameSpecInfo &IdInfo, 6223 bool EnteringContext, 6224 CXXScopeSpec &SS, 6225 bool ErrorRecoveryLookup = false, 6226 bool *IsCorrectedToColon = nullptr, 6227 bool OnlyNamespace = false); 6228 6229 ExprResult ActOnDecltypeExpression(Expr *E); 6230 6231 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, 6232 const DeclSpec &DS, 6233 SourceLocation ColonColonLoc); 6234 6235 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, 6236 NestedNameSpecInfo &IdInfo, 6237 bool EnteringContext); 6238 6239 /// The parser has parsed a nested-name-specifier 6240 /// 'template[opt] template-name < template-args >::'. 6241 /// 6242 /// \param S The scope in which this nested-name-specifier occurs. 6243 /// 6244 /// \param SS The nested-name-specifier, which is both an input 6245 /// parameter (the nested-name-specifier before this type) and an 6246 /// output parameter (containing the full nested-name-specifier, 6247 /// including this new type). 6248 /// 6249 /// \param TemplateKWLoc the location of the 'template' keyword, if any. 6250 /// \param TemplateName the template name. 6251 /// \param TemplateNameLoc The location of the template name. 6252 /// \param LAngleLoc The location of the opening angle bracket ('<'). 6253 /// \param TemplateArgs The template arguments. 6254 /// \param RAngleLoc The location of the closing angle bracket ('>'). 6255 /// \param CCLoc The location of the '::'. 6256 /// 6257 /// \param EnteringContext Whether we're entering the context of the 6258 /// nested-name-specifier. 6259 /// 6260 /// 6261 /// \returns true if an error occurred, false otherwise. 6262 bool ActOnCXXNestedNameSpecifier(Scope *S, 6263 CXXScopeSpec &SS, 6264 SourceLocation TemplateKWLoc, 6265 TemplateTy TemplateName, 6266 SourceLocation TemplateNameLoc, 6267 SourceLocation LAngleLoc, 6268 ASTTemplateArgsPtr TemplateArgs, 6269 SourceLocation RAngleLoc, 6270 SourceLocation CCLoc, 6271 bool EnteringContext); 6272 6273 /// Given a C++ nested-name-specifier, produce an annotation value 6274 /// that the parser can use later to reconstruct the given 6275 /// nested-name-specifier. 6276 /// 6277 /// \param SS A nested-name-specifier. 6278 /// 6279 /// \returns A pointer containing all of the information in the 6280 /// nested-name-specifier \p SS. 6281 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); 6282 6283 /// Given an annotation pointer for a nested-name-specifier, restore 6284 /// the nested-name-specifier structure. 6285 /// 6286 /// \param Annotation The annotation pointer, produced by 6287 /// \c SaveNestedNameSpecifierAnnotation(). 6288 /// 6289 /// \param AnnotationRange The source range corresponding to the annotation. 6290 /// 6291 /// \param SS The nested-name-specifier that will be updated with the contents 6292 /// of the annotation pointer. 6293 void RestoreNestedNameSpecifierAnnotation(void *Annotation, 6294 SourceRange AnnotationRange, 6295 CXXScopeSpec &SS); 6296 6297 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 6298 6299 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global 6300 /// scope or nested-name-specifier) is parsed, part of a declarator-id. 6301 /// After this method is called, according to [C++ 3.4.3p3], names should be 6302 /// looked up in the declarator-id's scope, until the declarator is parsed and 6303 /// ActOnCXXExitDeclaratorScope is called. 6304 /// The 'SS' should be a non-empty valid CXXScopeSpec. 6305 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); 6306 6307 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously 6308 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same 6309 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. 6310 /// Used to indicate that names should revert to being looked up in the 6311 /// defining scope. 6312 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 6313 6314 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an 6315 /// initializer for the declaration 'Dcl'. 6316 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 6317 /// static data member of class X, names should be looked up in the scope of 6318 /// class X. 6319 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); 6320 6321 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 6322 /// initializer for the declaration 'Dcl'. 6323 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); 6324 6325 /// Create a new lambda closure type. 6326 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, 6327 TypeSourceInfo *Info, 6328 bool KnownDependent, 6329 LambdaCaptureDefault CaptureDefault); 6330 6331 /// Start the definition of a lambda expression. 6332 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class, 6333 SourceRange IntroducerRange, 6334 TypeSourceInfo *MethodType, 6335 SourceLocation EndLoc, 6336 ArrayRef<ParmVarDecl *> Params, 6337 ConstexprSpecKind ConstexprKind, 6338 Expr *TrailingRequiresClause); 6339 6340 /// Number lambda for linkage purposes if necessary. 6341 void handleLambdaNumbering( 6342 CXXRecordDecl *Class, CXXMethodDecl *Method, 6343 Optional<std::tuple<unsigned, bool, Decl *>> Mangling = None); 6344 6345 /// Endow the lambda scope info with the relevant properties. 6346 void buildLambdaScope(sema::LambdaScopeInfo *LSI, 6347 CXXMethodDecl *CallOperator, 6348 SourceRange IntroducerRange, 6349 LambdaCaptureDefault CaptureDefault, 6350 SourceLocation CaptureDefaultLoc, 6351 bool ExplicitParams, 6352 bool ExplicitResultType, 6353 bool Mutable); 6354 6355 /// Perform initialization analysis of the init-capture and perform 6356 /// any implicit conversions such as an lvalue-to-rvalue conversion if 6357 /// not being used to initialize a reference. actOnLambdaInitCaptureInitialization(SourceLocation Loc,bool ByRef,SourceLocation EllipsisLoc,IdentifierInfo * Id,LambdaCaptureInitKind InitKind,Expr * & Init)6358 ParsedType actOnLambdaInitCaptureInitialization( 6359 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, 6360 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) { 6361 return ParsedType::make(buildLambdaInitCaptureInitialization( 6362 Loc, ByRef, EllipsisLoc, None, Id, 6363 InitKind != LambdaCaptureInitKind::CopyInit, Init)); 6364 } 6365 QualType buildLambdaInitCaptureInitialization( 6366 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, 6367 Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit, 6368 Expr *&Init); 6369 6370 /// Create a dummy variable within the declcontext of the lambda's 6371 /// call operator, for name lookup purposes for a lambda init capture. 6372 /// 6373 /// CodeGen handles emission of lambda captures, ignoring these dummy 6374 /// variables appropriately. 6375 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc, 6376 QualType InitCaptureType, 6377 SourceLocation EllipsisLoc, 6378 IdentifierInfo *Id, 6379 unsigned InitStyle, Expr *Init); 6380 6381 /// Add an init-capture to a lambda scope. 6382 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var); 6383 6384 /// Note that we have finished the explicit captures for the 6385 /// given lambda. 6386 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); 6387 6388 /// \brief This is called after parsing the explicit template parameter list 6389 /// on a lambda (if it exists) in C++2a. 6390 void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc, 6391 ArrayRef<NamedDecl *> TParams, 6392 SourceLocation RAngleLoc); 6393 6394 /// Introduce the lambda parameters into scope. 6395 void addLambdaParameters( 6396 ArrayRef<LambdaIntroducer::LambdaCapture> Captures, 6397 CXXMethodDecl *CallOperator, Scope *CurScope); 6398 6399 /// Deduce a block or lambda's return type based on the return 6400 /// statements present in the body. 6401 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); 6402 6403 /// ActOnStartOfLambdaDefinition - This is called just before we start 6404 /// parsing the body of a lambda; it analyzes the explicit captures and 6405 /// arguments, and sets up various data-structures for the body of the 6406 /// lambda. 6407 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, 6408 Declarator &ParamInfo, Scope *CurScope); 6409 6410 /// ActOnLambdaError - If there is an error parsing a lambda, this callback 6411 /// is invoked to pop the information about the lambda. 6412 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, 6413 bool IsInstantiation = false); 6414 6415 /// ActOnLambdaExpr - This is called when the body of a lambda expression 6416 /// was successfully completed. 6417 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, 6418 Scope *CurScope); 6419 6420 /// Does copying/destroying the captured variable have side effects? 6421 bool CaptureHasSideEffects(const sema::Capture &From); 6422 6423 /// Diagnose if an explicit lambda capture is unused. Returns true if a 6424 /// diagnostic is emitted. 6425 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, 6426 const sema::Capture &From); 6427 6428 /// Build a FieldDecl suitable to hold the given capture. 6429 FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture); 6430 6431 /// Initialize the given capture with a suitable expression. 6432 ExprResult BuildCaptureInit(const sema::Capture &Capture, 6433 SourceLocation ImplicitCaptureLoc, 6434 bool IsOpenMPMapping = false); 6435 6436 /// Complete a lambda-expression having processed and attached the 6437 /// lambda body. 6438 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, 6439 sema::LambdaScopeInfo *LSI); 6440 6441 /// Get the return type to use for a lambda's conversion function(s) to 6442 /// function pointer type, given the type of the call operator. 6443 QualType 6444 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType); 6445 6446 /// Define the "body" of the conversion from a lambda object to a 6447 /// function pointer. 6448 /// 6449 /// This routine doesn't actually define a sensible body; rather, it fills 6450 /// in the initialization expression needed to copy the lambda object into 6451 /// the block, and IR generation actually generates the real body of the 6452 /// block pointer conversion. 6453 void DefineImplicitLambdaToFunctionPointerConversion( 6454 SourceLocation CurrentLoc, CXXConversionDecl *Conv); 6455 6456 /// Define the "body" of the conversion from a lambda object to a 6457 /// block pointer. 6458 /// 6459 /// This routine doesn't actually define a sensible body; rather, it fills 6460 /// in the initialization expression needed to copy the lambda object into 6461 /// the block, and IR generation actually generates the real body of the 6462 /// block pointer conversion. 6463 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, 6464 CXXConversionDecl *Conv); 6465 6466 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, 6467 SourceLocation ConvLocation, 6468 CXXConversionDecl *Conv, 6469 Expr *Src); 6470 6471 /// Check whether the given expression is a valid constraint expression. 6472 /// A diagnostic is emitted if it is not, false is returned, and 6473 /// PossibleNonPrimary will be set to true if the failure might be due to a 6474 /// non-primary expression being used as an atomic constraint. 6475 bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(), 6476 bool *PossibleNonPrimary = nullptr, 6477 bool IsTrailingRequiresClause = false); 6478 6479 private: 6480 /// Caches pairs of template-like decls whose associated constraints were 6481 /// checked for subsumption and whether or not the first's constraints did in 6482 /// fact subsume the second's. 6483 llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache; 6484 /// Caches the normalized associated constraints of declarations (concepts or 6485 /// constrained declarations). If an error occurred while normalizing the 6486 /// associated constraints of the template or concept, nullptr will be cached 6487 /// here. 6488 llvm::DenseMap<NamedDecl *, NormalizedConstraint *> 6489 NormalizationCache; 6490 6491 llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &> 6492 SatisfactionCache; 6493 6494 public: 6495 const NormalizedConstraint * 6496 getNormalizedAssociatedConstraints( 6497 NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints); 6498 6499 /// \brief Check whether the given declaration's associated constraints are 6500 /// at least as constrained than another declaration's according to the 6501 /// partial ordering of constraints. 6502 /// 6503 /// \param Result If no error occurred, receives the result of true if D1 is 6504 /// at least constrained than D2, and false otherwise. 6505 /// 6506 /// \returns true if an error occurred, false otherwise. 6507 bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1, 6508 NamedDecl *D2, ArrayRef<const Expr *> AC2, 6509 bool &Result); 6510 6511 /// If D1 was not at least as constrained as D2, but would've been if a pair 6512 /// of atomic constraints involved had been declared in a concept and not 6513 /// repeated in two separate places in code. 6514 /// \returns true if such a diagnostic was emitted, false otherwise. 6515 bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1, 6516 ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2); 6517 6518 /// \brief Check whether the given list of constraint expressions are 6519 /// satisfied (as if in a 'conjunction') given template arguments. 6520 /// \param Template the template-like entity that triggered the constraints 6521 /// check (either a concept or a constrained entity). 6522 /// \param ConstraintExprs a list of constraint expressions, treated as if 6523 /// they were 'AND'ed together. 6524 /// \param TemplateArgs the list of template arguments to substitute into the 6525 /// constraint expression. 6526 /// \param TemplateIDRange The source range of the template id that 6527 /// caused the constraints check. 6528 /// \param Satisfaction if true is returned, will contain details of the 6529 /// satisfaction, with enough information to diagnose an unsatisfied 6530 /// expression. 6531 /// \returns true if an error occurred and satisfaction could not be checked, 6532 /// false otherwise. 6533 bool CheckConstraintSatisfaction( 6534 const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs, 6535 ArrayRef<TemplateArgument> TemplateArgs, 6536 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction); 6537 6538 /// \brief Check whether the given non-dependent constraint expression is 6539 /// satisfied. Returns false and updates Satisfaction with the satisfaction 6540 /// verdict if successful, emits a diagnostic and returns true if an error 6541 /// occured and satisfaction could not be determined. 6542 /// 6543 /// \returns true if an error occurred, false otherwise. 6544 bool CheckConstraintSatisfaction(const Expr *ConstraintExpr, 6545 ConstraintSatisfaction &Satisfaction); 6546 6547 /// Check whether the given function decl's trailing requires clause is 6548 /// satisfied, if any. Returns false and updates Satisfaction with the 6549 /// satisfaction verdict if successful, emits a diagnostic and returns true if 6550 /// an error occured and satisfaction could not be determined. 6551 /// 6552 /// \returns true if an error occurred, false otherwise. 6553 bool CheckFunctionConstraints(const FunctionDecl *FD, 6554 ConstraintSatisfaction &Satisfaction, 6555 SourceLocation UsageLoc = SourceLocation()); 6556 6557 6558 /// \brief Ensure that the given template arguments satisfy the constraints 6559 /// associated with the given template, emitting a diagnostic if they do not. 6560 /// 6561 /// \param Template The template to which the template arguments are being 6562 /// provided. 6563 /// 6564 /// \param TemplateArgs The converted, canonicalized template arguments. 6565 /// 6566 /// \param TemplateIDRange The source range of the template id that 6567 /// caused the constraints check. 6568 /// 6569 /// \returns true if the constrains are not satisfied or could not be checked 6570 /// for satisfaction, false if the constraints are satisfied. 6571 bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, 6572 ArrayRef<TemplateArgument> TemplateArgs, 6573 SourceRange TemplateIDRange); 6574 6575 /// \brief Emit diagnostics explaining why a constraint expression was deemed 6576 /// unsatisfied. 6577 /// \param First whether this is the first time an unsatisfied constraint is 6578 /// diagnosed for this error. 6579 void 6580 DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, 6581 bool First = true); 6582 6583 /// \brief Emit diagnostics explaining why a constraint expression was deemed 6584 /// unsatisfied. 6585 void 6586 DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction, 6587 bool First = true); 6588 6589 /// \brief Emit diagnostics explaining why a constraint expression was deemed 6590 /// unsatisfied because it was ill-formed. 6591 void DiagnoseUnsatisfiedIllFormedConstraint(SourceLocation DiagnosticLocation, 6592 StringRef Diagnostic); 6593 6594 void DiagnoseRedeclarationConstraintMismatch(SourceLocation Old, 6595 SourceLocation New); 6596 6597 // ParseObjCStringLiteral - Parse Objective-C string literals. 6598 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, 6599 ArrayRef<Expr *> Strings); 6600 6601 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); 6602 6603 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the 6604 /// numeric literal expression. Type of the expression will be "NSNumber *" 6605 /// or "id" if NSNumber is unavailable. 6606 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); 6607 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, 6608 bool Value); 6609 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); 6610 6611 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the 6612 /// '@' prefixed parenthesized expression. The type of the expression will 6613 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type 6614 /// of ValueType, which is allowed to be a built-in numeric type, "char *", 6615 /// "const char *" or C structure with attribute 'objc_boxable'. 6616 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); 6617 6618 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, 6619 Expr *IndexExpr, 6620 ObjCMethodDecl *getterMethod, 6621 ObjCMethodDecl *setterMethod); 6622 6623 ExprResult BuildObjCDictionaryLiteral(SourceRange SR, 6624 MutableArrayRef<ObjCDictionaryElement> Elements); 6625 6626 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, 6627 TypeSourceInfo *EncodedTypeInfo, 6628 SourceLocation RParenLoc); 6629 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, 6630 CXXConversionDecl *Method, 6631 bool HadMultipleCandidates); 6632 6633 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, 6634 SourceLocation EncodeLoc, 6635 SourceLocation LParenLoc, 6636 ParsedType Ty, 6637 SourceLocation RParenLoc); 6638 6639 /// ParseObjCSelectorExpression - Build selector expression for \@selector 6640 ExprResult ParseObjCSelectorExpression(Selector Sel, 6641 SourceLocation AtLoc, 6642 SourceLocation SelLoc, 6643 SourceLocation LParenLoc, 6644 SourceLocation RParenLoc, 6645 bool WarnMultipleSelectors); 6646 6647 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol 6648 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, 6649 SourceLocation AtLoc, 6650 SourceLocation ProtoLoc, 6651 SourceLocation LParenLoc, 6652 SourceLocation ProtoIdLoc, 6653 SourceLocation RParenLoc); 6654 6655 //===--------------------------------------------------------------------===// 6656 // C++ Declarations 6657 // 6658 Decl *ActOnStartLinkageSpecification(Scope *S, 6659 SourceLocation ExternLoc, 6660 Expr *LangStr, 6661 SourceLocation LBraceLoc); 6662 Decl *ActOnFinishLinkageSpecification(Scope *S, 6663 Decl *LinkageSpec, 6664 SourceLocation RBraceLoc); 6665 6666 6667 //===--------------------------------------------------------------------===// 6668 // C++ Classes 6669 // 6670 CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS); 6671 bool isCurrentClassName(const IdentifierInfo &II, Scope *S, 6672 const CXXScopeSpec *SS = nullptr); 6673 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS); 6674 6675 bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 6676 SourceLocation ColonLoc, 6677 const ParsedAttributesView &Attrs); 6678 6679 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, 6680 Declarator &D, 6681 MultiTemplateParamsArg TemplateParameterLists, 6682 Expr *BitfieldWidth, const VirtSpecifiers &VS, 6683 InClassInitStyle InitStyle); 6684 6685 void ActOnStartCXXInClassMemberInitializer(); 6686 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, 6687 SourceLocation EqualLoc, 6688 Expr *Init); 6689 6690 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 6691 Scope *S, 6692 CXXScopeSpec &SS, 6693 IdentifierInfo *MemberOrBase, 6694 ParsedType TemplateTypeTy, 6695 const DeclSpec &DS, 6696 SourceLocation IdLoc, 6697 SourceLocation LParenLoc, 6698 ArrayRef<Expr *> Args, 6699 SourceLocation RParenLoc, 6700 SourceLocation EllipsisLoc); 6701 6702 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 6703 Scope *S, 6704 CXXScopeSpec &SS, 6705 IdentifierInfo *MemberOrBase, 6706 ParsedType TemplateTypeTy, 6707 const DeclSpec &DS, 6708 SourceLocation IdLoc, 6709 Expr *InitList, 6710 SourceLocation EllipsisLoc); 6711 6712 MemInitResult BuildMemInitializer(Decl *ConstructorD, 6713 Scope *S, 6714 CXXScopeSpec &SS, 6715 IdentifierInfo *MemberOrBase, 6716 ParsedType TemplateTypeTy, 6717 const DeclSpec &DS, 6718 SourceLocation IdLoc, 6719 Expr *Init, 6720 SourceLocation EllipsisLoc); 6721 6722 MemInitResult BuildMemberInitializer(ValueDecl *Member, 6723 Expr *Init, 6724 SourceLocation IdLoc); 6725 6726 MemInitResult BuildBaseInitializer(QualType BaseType, 6727 TypeSourceInfo *BaseTInfo, 6728 Expr *Init, 6729 CXXRecordDecl *ClassDecl, 6730 SourceLocation EllipsisLoc); 6731 6732 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, 6733 Expr *Init, 6734 CXXRecordDecl *ClassDecl); 6735 6736 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, 6737 CXXCtorInitializer *Initializer); 6738 6739 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 6740 ArrayRef<CXXCtorInitializer *> Initializers = None); 6741 6742 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); 6743 6744 6745 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, 6746 /// mark all the non-trivial destructors of its members and bases as 6747 /// referenced. 6748 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, 6749 CXXRecordDecl *Record); 6750 6751 /// Mark destructors of virtual bases of this class referenced. In the Itanium 6752 /// C++ ABI, this is done when emitting a destructor for any non-abstract 6753 /// class. In the Microsoft C++ ABI, this is done any time a class's 6754 /// destructor is referenced. 6755 void MarkVirtualBaseDestructorsReferenced( 6756 SourceLocation Location, CXXRecordDecl *ClassDecl, 6757 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr); 6758 6759 /// Do semantic checks to allow the complete destructor variant to be emitted 6760 /// when the destructor is defined in another translation unit. In the Itanium 6761 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they 6762 /// can be emitted in separate TUs. To emit the complete variant, run a subset 6763 /// of the checks performed when emitting a regular destructor. 6764 void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, 6765 CXXDestructorDecl *Dtor); 6766 6767 /// The list of classes whose vtables have been used within 6768 /// this translation unit, and the source locations at which the 6769 /// first use occurred. 6770 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; 6771 6772 /// The list of vtables that are required but have not yet been 6773 /// materialized. 6774 SmallVector<VTableUse, 16> VTableUses; 6775 6776 /// The set of classes whose vtables have been used within 6777 /// this translation unit, and a bit that will be true if the vtable is 6778 /// required to be emitted (otherwise, it should be emitted only if needed 6779 /// by code generation). 6780 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; 6781 6782 /// Load any externally-stored vtable uses. 6783 void LoadExternalVTableUses(); 6784 6785 /// Note that the vtable for the given class was used at the 6786 /// given location. 6787 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 6788 bool DefinitionRequired = false); 6789 6790 /// Mark the exception specifications of all virtual member functions 6791 /// in the given class as needed. 6792 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 6793 const CXXRecordDecl *RD); 6794 6795 /// MarkVirtualMembersReferenced - Will mark all members of the given 6796 /// CXXRecordDecl referenced. 6797 void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, 6798 bool ConstexprOnly = false); 6799 6800 /// Define all of the vtables that have been used in this 6801 /// translation unit and reference any virtual members used by those 6802 /// vtables. 6803 /// 6804 /// \returns true if any work was done, false otherwise. 6805 bool DefineUsedVTables(); 6806 6807 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); 6808 6809 void ActOnMemInitializers(Decl *ConstructorDecl, 6810 SourceLocation ColonLoc, 6811 ArrayRef<CXXCtorInitializer*> MemInits, 6812 bool AnyErrors); 6813 6814 /// Check class-level dllimport/dllexport attribute. The caller must 6815 /// ensure that referenceDLLExportedClassMethods is called some point later 6816 /// when all outer classes of Class are complete. 6817 void checkClassLevelDLLAttribute(CXXRecordDecl *Class); 6818 void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class); 6819 6820 void referenceDLLExportedClassMethods(); 6821 6822 void propagateDLLAttrToBaseClassTemplate( 6823 CXXRecordDecl *Class, Attr *ClassAttr, 6824 ClassTemplateSpecializationDecl *BaseTemplateSpec, 6825 SourceLocation BaseLoc); 6826 6827 /// Add gsl::Pointer attribute to std::container::iterator 6828 /// \param ND The declaration that introduces the name 6829 /// std::container::iterator. \param UnderlyingRecord The record named by ND. 6830 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord); 6831 6832 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types. 6833 void inferGslOwnerPointerAttribute(CXXRecordDecl *Record); 6834 6835 /// Add [[gsl::Pointer]] attributes for std:: types. 6836 void inferGslPointerAttribute(TypedefNameDecl *TD); 6837 6838 void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record); 6839 6840 /// Check that the C++ class annoated with "trivial_abi" satisfies all the 6841 /// conditions that are needed for the attribute to have an effect. 6842 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD); 6843 6844 void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, 6845 Decl *TagDecl, SourceLocation LBrac, 6846 SourceLocation RBrac, 6847 const ParsedAttributesView &AttrList); 6848 void ActOnFinishCXXMemberDecls(); 6849 void ActOnFinishCXXNonNestedClass(); 6850 6851 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param); 6852 unsigned ActOnReenterTemplateScope(Decl *Template, 6853 llvm::function_ref<Scope *()> EnterScope); 6854 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); 6855 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 6856 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); 6857 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); 6858 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 6859 void ActOnFinishDelayedMemberInitializers(Decl *Record); 6860 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, 6861 CachedTokens &Toks); 6862 void UnmarkAsLateParsedTemplate(FunctionDecl *FD); 6863 bool IsInsideALocalClassWithinATemplateFunction(); 6864 6865 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 6866 Expr *AssertExpr, 6867 Expr *AssertMessageExpr, 6868 SourceLocation RParenLoc); 6869 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 6870 Expr *AssertExpr, 6871 StringLiteral *AssertMessageExpr, 6872 SourceLocation RParenLoc, 6873 bool Failed); 6874 6875 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, 6876 SourceLocation FriendLoc, 6877 TypeSourceInfo *TSInfo); 6878 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 6879 MultiTemplateParamsArg TemplateParams); 6880 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, 6881 MultiTemplateParamsArg TemplateParams); 6882 6883 QualType CheckConstructorDeclarator(Declarator &D, QualType R, 6884 StorageClass& SC); 6885 void CheckConstructor(CXXConstructorDecl *Constructor); 6886 QualType CheckDestructorDeclarator(Declarator &D, QualType R, 6887 StorageClass& SC); 6888 bool CheckDestructor(CXXDestructorDecl *Destructor); 6889 void CheckConversionDeclarator(Declarator &D, QualType &R, 6890 StorageClass& SC); 6891 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); 6892 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 6893 StorageClass &SC); 6894 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD); 6895 6896 void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD); 6897 6898 bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 6899 CXXSpecialMember CSM); 6900 void CheckDelayedMemberExceptionSpecs(); 6901 6902 bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, 6903 DefaultedComparisonKind DCK); 6904 void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 6905 FunctionDecl *Spaceship); 6906 void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, 6907 DefaultedComparisonKind DCK); 6908 6909 //===--------------------------------------------------------------------===// 6910 // C++ Derived Classes 6911 // 6912 6913 /// ActOnBaseSpecifier - Parsed a base specifier 6914 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, 6915 SourceRange SpecifierRange, 6916 bool Virtual, AccessSpecifier Access, 6917 TypeSourceInfo *TInfo, 6918 SourceLocation EllipsisLoc); 6919 6920 BaseResult ActOnBaseSpecifier(Decl *classdecl, 6921 SourceRange SpecifierRange, 6922 ParsedAttributes &Attrs, 6923 bool Virtual, AccessSpecifier Access, 6924 ParsedType basetype, 6925 SourceLocation BaseLoc, 6926 SourceLocation EllipsisLoc); 6927 6928 bool AttachBaseSpecifiers(CXXRecordDecl *Class, 6929 MutableArrayRef<CXXBaseSpecifier *> Bases); 6930 void ActOnBaseSpecifiers(Decl *ClassDecl, 6931 MutableArrayRef<CXXBaseSpecifier *> Bases); 6932 6933 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base); 6934 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 6935 CXXBasePaths &Paths); 6936 6937 // FIXME: I don't like this name. 6938 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); 6939 6940 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 6941 SourceLocation Loc, SourceRange Range, 6942 CXXCastPath *BasePath = nullptr, 6943 bool IgnoreAccess = false); 6944 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 6945 unsigned InaccessibleBaseID, 6946 unsigned AmbiguousBaseConvID, 6947 SourceLocation Loc, SourceRange Range, 6948 DeclarationName Name, 6949 CXXCastPath *BasePath, 6950 bool IgnoreAccess = false); 6951 6952 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); 6953 6954 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 6955 const CXXMethodDecl *Old); 6956 6957 /// CheckOverridingFunctionReturnType - Checks whether the return types are 6958 /// covariant, according to C++ [class.virtual]p5. 6959 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 6960 const CXXMethodDecl *Old); 6961 6962 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception 6963 /// spec is a subset of base spec. 6964 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, 6965 const CXXMethodDecl *Old); 6966 6967 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); 6968 6969 /// CheckOverrideControl - Check C++11 override control semantics. 6970 void CheckOverrideControl(NamedDecl *D); 6971 6972 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was 6973 /// not used in the declaration of an overriding method. 6974 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent); 6975 6976 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function 6977 /// overrides a virtual member function marked 'final', according to 6978 /// C++11 [class.virtual]p4. 6979 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 6980 const CXXMethodDecl *Old); 6981 6982 6983 //===--------------------------------------------------------------------===// 6984 // C++ Access Control 6985 // 6986 6987 enum AccessResult { 6988 AR_accessible, 6989 AR_inaccessible, 6990 AR_dependent, 6991 AR_delayed 6992 }; 6993 6994 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, 6995 NamedDecl *PrevMemberDecl, 6996 AccessSpecifier LexicalAS); 6997 6998 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, 6999 DeclAccessPair FoundDecl); 7000 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, 7001 DeclAccessPair FoundDecl); 7002 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, 7003 SourceRange PlacementRange, 7004 CXXRecordDecl *NamingClass, 7005 DeclAccessPair FoundDecl, 7006 bool Diagnose = true); 7007 AccessResult CheckConstructorAccess(SourceLocation Loc, 7008 CXXConstructorDecl *D, 7009 DeclAccessPair FoundDecl, 7010 const InitializedEntity &Entity, 7011 bool IsCopyBindingRefToTemp = false); 7012 AccessResult CheckConstructorAccess(SourceLocation Loc, 7013 CXXConstructorDecl *D, 7014 DeclAccessPair FoundDecl, 7015 const InitializedEntity &Entity, 7016 const PartialDiagnostic &PDiag); 7017 AccessResult CheckDestructorAccess(SourceLocation Loc, 7018 CXXDestructorDecl *Dtor, 7019 const PartialDiagnostic &PDiag, 7020 QualType objectType = QualType()); 7021 AccessResult CheckFriendAccess(NamedDecl *D); 7022 AccessResult CheckMemberAccess(SourceLocation UseLoc, 7023 CXXRecordDecl *NamingClass, 7024 DeclAccessPair Found); 7025 AccessResult 7026 CheckStructuredBindingMemberAccess(SourceLocation UseLoc, 7027 CXXRecordDecl *DecomposedClass, 7028 DeclAccessPair Field); 7029 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, 7030 Expr *ObjectExpr, 7031 Expr *ArgExpr, 7032 DeclAccessPair FoundDecl); 7033 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, 7034 DeclAccessPair FoundDecl); 7035 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, 7036 QualType Base, QualType Derived, 7037 const CXXBasePath &Path, 7038 unsigned DiagID, 7039 bool ForceCheck = false, 7040 bool ForceUnprivileged = false); 7041 void CheckLookupAccess(const LookupResult &R); 7042 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass, 7043 QualType BaseType); 7044 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, 7045 DeclAccessPair Found, QualType ObjectType, 7046 SourceLocation Loc, 7047 const PartialDiagnostic &Diag); isMemberAccessibleForDeletion(CXXRecordDecl * NamingClass,DeclAccessPair Found,QualType ObjectType)7048 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, 7049 DeclAccessPair Found, 7050 QualType ObjectType) { 7051 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType, 7052 SourceLocation(), PDiag()); 7053 } 7054 7055 void HandleDependentAccessCheck(const DependentDiagnostic &DD, 7056 const MultiLevelTemplateArgumentList &TemplateArgs); 7057 void PerformDependentDiagnostics(const DeclContext *Pattern, 7058 const MultiLevelTemplateArgumentList &TemplateArgs); 7059 7060 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 7061 7062 /// When true, access checking violations are treated as SFINAE 7063 /// failures rather than hard errors. 7064 bool AccessCheckingSFINAE; 7065 7066 enum AbstractDiagSelID { 7067 AbstractNone = -1, 7068 AbstractReturnType, 7069 AbstractParamType, 7070 AbstractVariableType, 7071 AbstractFieldType, 7072 AbstractIvarType, 7073 AbstractSynthesizedIvarType, 7074 AbstractArrayType 7075 }; 7076 7077 bool isAbstractType(SourceLocation Loc, QualType T); 7078 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 7079 TypeDiagnoser &Diagnoser); 7080 template <typename... Ts> RequireNonAbstractType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)7081 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, 7082 const Ts &...Args) { 7083 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 7084 return RequireNonAbstractType(Loc, T, Diagnoser); 7085 } 7086 7087 void DiagnoseAbstractType(const CXXRecordDecl *RD); 7088 7089 //===--------------------------------------------------------------------===// 7090 // C++ Overloaded Operators [C++ 13.5] 7091 // 7092 7093 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); 7094 7095 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); 7096 7097 //===--------------------------------------------------------------------===// 7098 // C++ Templates [C++ 14] 7099 // 7100 void FilterAcceptableTemplateNames(LookupResult &R, 7101 bool AllowFunctionTemplates = true, 7102 bool AllowDependent = true); 7103 bool hasAnyAcceptableTemplateNames(LookupResult &R, 7104 bool AllowFunctionTemplates = true, 7105 bool AllowDependent = true, 7106 bool AllowNonTemplateFunctions = false); 7107 /// Try to interpret the lookup result D as a template-name. 7108 /// 7109 /// \param D A declaration found by name lookup. 7110 /// \param AllowFunctionTemplates Whether function templates should be 7111 /// considered valid results. 7112 /// \param AllowDependent Whether unresolved using declarations (that might 7113 /// name templates) should be considered valid results. 7114 NamedDecl *getAsTemplateNameDecl(NamedDecl *D, 7115 bool AllowFunctionTemplates = true, 7116 bool AllowDependent = true); 7117 7118 enum TemplateNameIsRequiredTag { TemplateNameIsRequired }; 7119 /// Whether and why a template name is required in this lookup. 7120 class RequiredTemplateKind { 7121 public: 7122 /// Template name is required if TemplateKWLoc is valid. 7123 RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation()) TemplateKW(TemplateKWLoc)7124 : TemplateKW(TemplateKWLoc) {} 7125 /// Template name is unconditionally required. RequiredTemplateKind(TemplateNameIsRequiredTag)7126 RequiredTemplateKind(TemplateNameIsRequiredTag) : TemplateKW() {} 7127 getTemplateKeywordLoc()7128 SourceLocation getTemplateKeywordLoc() const { 7129 return TemplateKW.getValueOr(SourceLocation()); 7130 } hasTemplateKeyword()7131 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } isRequired()7132 bool isRequired() const { return TemplateKW != SourceLocation(); } 7133 explicit operator bool() const { return isRequired(); } 7134 7135 private: 7136 llvm::Optional<SourceLocation> TemplateKW; 7137 }; 7138 7139 enum class AssumedTemplateKind { 7140 /// This is not assumed to be a template name. 7141 None, 7142 /// This is assumed to be a template name because lookup found nothing. 7143 FoundNothing, 7144 /// This is assumed to be a template name because lookup found one or more 7145 /// functions (but no function templates). 7146 FoundFunctions, 7147 }; 7148 bool LookupTemplateName( 7149 LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, 7150 bool EnteringContext, bool &MemberOfUnknownSpecialization, 7151 RequiredTemplateKind RequiredTemplate = SourceLocation(), 7152 AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true); 7153 7154 TemplateNameKind isTemplateName(Scope *S, 7155 CXXScopeSpec &SS, 7156 bool hasTemplateKeyword, 7157 const UnqualifiedId &Name, 7158 ParsedType ObjectType, 7159 bool EnteringContext, 7160 TemplateTy &Template, 7161 bool &MemberOfUnknownSpecialization, 7162 bool Disambiguation = false); 7163 7164 /// Try to resolve an undeclared template name as a type template. 7165 /// 7166 /// Sets II to the identifier corresponding to the template name, and updates 7167 /// Name to a corresponding (typo-corrected) type template name and TNK to 7168 /// the corresponding kind, if possible. 7169 void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, 7170 TemplateNameKind &TNK, 7171 SourceLocation NameLoc, 7172 IdentifierInfo *&II); 7173 7174 bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, 7175 SourceLocation NameLoc, 7176 bool Diagnose = true); 7177 7178 /// Determine whether a particular identifier might be the name in a C++1z 7179 /// deduction-guide declaration. 7180 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, 7181 SourceLocation NameLoc, 7182 ParsedTemplateTy *Template = nullptr); 7183 7184 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, 7185 SourceLocation IILoc, 7186 Scope *S, 7187 const CXXScopeSpec *SS, 7188 TemplateTy &SuggestedTemplate, 7189 TemplateNameKind &SuggestedKind); 7190 7191 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, 7192 NamedDecl *Instantiation, 7193 bool InstantiatedFromMember, 7194 const NamedDecl *Pattern, 7195 const NamedDecl *PatternDef, 7196 TemplateSpecializationKind TSK, 7197 bool Complain = true); 7198 7199 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); 7200 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); 7201 7202 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename, 7203 SourceLocation EllipsisLoc, 7204 SourceLocation KeyLoc, 7205 IdentifierInfo *ParamName, 7206 SourceLocation ParamNameLoc, 7207 unsigned Depth, unsigned Position, 7208 SourceLocation EqualLoc, 7209 ParsedType DefaultArg, bool HasTypeConstraint); 7210 7211 bool ActOnTypeConstraint(const CXXScopeSpec &SS, 7212 TemplateIdAnnotation *TypeConstraint, 7213 TemplateTypeParmDecl *ConstrainedParameter, 7214 SourceLocation EllipsisLoc); 7215 7216 bool AttachTypeConstraint(NestedNameSpecifierLoc NS, 7217 DeclarationNameInfo NameInfo, 7218 ConceptDecl *NamedConcept, 7219 const TemplateArgumentListInfo *TemplateArgs, 7220 TemplateTypeParmDecl *ConstrainedParameter, 7221 SourceLocation EllipsisLoc); 7222 7223 bool AttachTypeConstraint(AutoTypeLoc TL, 7224 NonTypeTemplateParmDecl *ConstrainedParameter, 7225 SourceLocation EllipsisLoc); 7226 7227 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, 7228 SourceLocation Loc); 7229 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); 7230 7231 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 7232 unsigned Depth, 7233 unsigned Position, 7234 SourceLocation EqualLoc, 7235 Expr *DefaultArg); 7236 NamedDecl *ActOnTemplateTemplateParameter(Scope *S, 7237 SourceLocation TmpLoc, 7238 TemplateParameterList *Params, 7239 SourceLocation EllipsisLoc, 7240 IdentifierInfo *ParamName, 7241 SourceLocation ParamNameLoc, 7242 unsigned Depth, 7243 unsigned Position, 7244 SourceLocation EqualLoc, 7245 ParsedTemplateArgument DefaultArg); 7246 7247 TemplateParameterList * 7248 ActOnTemplateParameterList(unsigned Depth, 7249 SourceLocation ExportLoc, 7250 SourceLocation TemplateLoc, 7251 SourceLocation LAngleLoc, 7252 ArrayRef<NamedDecl *> Params, 7253 SourceLocation RAngleLoc, 7254 Expr *RequiresClause); 7255 7256 /// The context in which we are checking a template parameter list. 7257 enum TemplateParamListContext { 7258 TPC_ClassTemplate, 7259 TPC_VarTemplate, 7260 TPC_FunctionTemplate, 7261 TPC_ClassTemplateMember, 7262 TPC_FriendClassTemplate, 7263 TPC_FriendFunctionTemplate, 7264 TPC_FriendFunctionTemplateDefinition, 7265 TPC_TypeAliasTemplate 7266 }; 7267 7268 bool CheckTemplateParameterList(TemplateParameterList *NewParams, 7269 TemplateParameterList *OldParams, 7270 TemplateParamListContext TPC, 7271 SkipBodyInfo *SkipBody = nullptr); 7272 TemplateParameterList *MatchTemplateParametersToScopeSpecifier( 7273 SourceLocation DeclStartLoc, SourceLocation DeclLoc, 7274 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, 7275 ArrayRef<TemplateParameterList *> ParamLists, 7276 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, 7277 bool SuppressDiagnostic = false); 7278 7279 DeclResult CheckClassTemplate( 7280 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, 7281 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, 7282 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, 7283 AccessSpecifier AS, SourceLocation ModulePrivateLoc, 7284 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, 7285 TemplateParameterList **OuterTemplateParamLists, 7286 SkipBodyInfo *SkipBody = nullptr); 7287 7288 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, 7289 QualType NTTPType, 7290 SourceLocation Loc); 7291 7292 /// Get a template argument mapping the given template parameter to itself, 7293 /// e.g. for X in \c template<int X>, this would return an expression template 7294 /// argument referencing X. 7295 TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param, 7296 SourceLocation Location); 7297 7298 void translateTemplateArguments(const ASTTemplateArgsPtr &In, 7299 TemplateArgumentListInfo &Out); 7300 7301 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType); 7302 7303 void NoteAllFoundTemplates(TemplateName Name); 7304 7305 QualType CheckTemplateIdType(TemplateName Template, 7306 SourceLocation TemplateLoc, 7307 TemplateArgumentListInfo &TemplateArgs); 7308 7309 TypeResult 7310 ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 7311 TemplateTy Template, IdentifierInfo *TemplateII, 7312 SourceLocation TemplateIILoc, SourceLocation LAngleLoc, 7313 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, 7314 bool IsCtorOrDtorName = false, bool IsClassName = false); 7315 7316 /// Parsed an elaborated-type-specifier that refers to a template-id, 7317 /// such as \c class T::template apply<U>. 7318 TypeResult ActOnTagTemplateIdType(TagUseKind TUK, 7319 TypeSpecifierType TagSpec, 7320 SourceLocation TagLoc, 7321 CXXScopeSpec &SS, 7322 SourceLocation TemplateKWLoc, 7323 TemplateTy TemplateD, 7324 SourceLocation TemplateLoc, 7325 SourceLocation LAngleLoc, 7326 ASTTemplateArgsPtr TemplateArgsIn, 7327 SourceLocation RAngleLoc); 7328 7329 DeclResult ActOnVarTemplateSpecialization( 7330 Scope *S, Declarator &D, TypeSourceInfo *DI, 7331 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, 7332 StorageClass SC, bool IsPartialSpecialization); 7333 7334 DeclResult CheckVarTemplateId(VarTemplateDecl *Template, 7335 SourceLocation TemplateLoc, 7336 SourceLocation TemplateNameLoc, 7337 const TemplateArgumentListInfo &TemplateArgs); 7338 7339 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, 7340 const DeclarationNameInfo &NameInfo, 7341 VarTemplateDecl *Template, 7342 SourceLocation TemplateLoc, 7343 const TemplateArgumentListInfo *TemplateArgs); 7344 7345 ExprResult 7346 CheckConceptTemplateId(const CXXScopeSpec &SS, 7347 SourceLocation TemplateKWLoc, 7348 const DeclarationNameInfo &ConceptNameInfo, 7349 NamedDecl *FoundDecl, ConceptDecl *NamedConcept, 7350 const TemplateArgumentListInfo *TemplateArgs); 7351 7352 void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc); 7353 7354 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, 7355 SourceLocation TemplateKWLoc, 7356 LookupResult &R, 7357 bool RequiresADL, 7358 const TemplateArgumentListInfo *TemplateArgs); 7359 7360 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, 7361 SourceLocation TemplateKWLoc, 7362 const DeclarationNameInfo &NameInfo, 7363 const TemplateArgumentListInfo *TemplateArgs); 7364 7365 TemplateNameKind ActOnTemplateName( 7366 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 7367 const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, 7368 TemplateTy &Template, bool AllowInjectedClassName = false); 7369 7370 DeclResult ActOnClassTemplateSpecialization( 7371 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, 7372 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, 7373 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, 7374 MultiTemplateParamsArg TemplateParameterLists, 7375 SkipBodyInfo *SkipBody = nullptr); 7376 7377 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, 7378 TemplateDecl *PrimaryTemplate, 7379 unsigned NumExplicitArgs, 7380 ArrayRef<TemplateArgument> Args); 7381 void CheckTemplatePartialSpecialization( 7382 ClassTemplatePartialSpecializationDecl *Partial); 7383 void CheckTemplatePartialSpecialization( 7384 VarTemplatePartialSpecializationDecl *Partial); 7385 7386 Decl *ActOnTemplateDeclarator(Scope *S, 7387 MultiTemplateParamsArg TemplateParameterLists, 7388 Declarator &D); 7389 7390 bool 7391 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, 7392 TemplateSpecializationKind NewTSK, 7393 NamedDecl *PrevDecl, 7394 TemplateSpecializationKind PrevTSK, 7395 SourceLocation PrevPtOfInstantiation, 7396 bool &SuppressNew); 7397 7398 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, 7399 const TemplateArgumentListInfo &ExplicitTemplateArgs, 7400 LookupResult &Previous); 7401 7402 bool CheckFunctionTemplateSpecialization( 7403 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, 7404 LookupResult &Previous, bool QualifiedFriend = false); 7405 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); 7406 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous); 7407 7408 DeclResult ActOnExplicitInstantiation( 7409 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, 7410 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, 7411 TemplateTy Template, SourceLocation TemplateNameLoc, 7412 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, 7413 SourceLocation RAngleLoc, const ParsedAttributesView &Attr); 7414 7415 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, 7416 SourceLocation TemplateLoc, 7417 unsigned TagSpec, SourceLocation KWLoc, 7418 CXXScopeSpec &SS, IdentifierInfo *Name, 7419 SourceLocation NameLoc, 7420 const ParsedAttributesView &Attr); 7421 7422 DeclResult ActOnExplicitInstantiation(Scope *S, 7423 SourceLocation ExternLoc, 7424 SourceLocation TemplateLoc, 7425 Declarator &D); 7426 7427 TemplateArgumentLoc 7428 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, 7429 SourceLocation TemplateLoc, 7430 SourceLocation RAngleLoc, 7431 Decl *Param, 7432 SmallVectorImpl<TemplateArgument> 7433 &Converted, 7434 bool &HasDefaultArg); 7435 7436 /// Specifies the context in which a particular template 7437 /// argument is being checked. 7438 enum CheckTemplateArgumentKind { 7439 /// The template argument was specified in the code or was 7440 /// instantiated with some deduced template arguments. 7441 CTAK_Specified, 7442 7443 /// The template argument was deduced via template argument 7444 /// deduction. 7445 CTAK_Deduced, 7446 7447 /// The template argument was deduced from an array bound 7448 /// via template argument deduction. 7449 CTAK_DeducedFromArrayBound 7450 }; 7451 7452 bool CheckTemplateArgument(NamedDecl *Param, 7453 TemplateArgumentLoc &Arg, 7454 NamedDecl *Template, 7455 SourceLocation TemplateLoc, 7456 SourceLocation RAngleLoc, 7457 unsigned ArgumentPackIndex, 7458 SmallVectorImpl<TemplateArgument> &Converted, 7459 CheckTemplateArgumentKind CTAK = CTAK_Specified); 7460 7461 /// Check that the given template arguments can be be provided to 7462 /// the given template, converting the arguments along the way. 7463 /// 7464 /// \param Template The template to which the template arguments are being 7465 /// provided. 7466 /// 7467 /// \param TemplateLoc The location of the template name in the source. 7468 /// 7469 /// \param TemplateArgs The list of template arguments. If the template is 7470 /// a template template parameter, this function may extend the set of 7471 /// template arguments to also include substituted, defaulted template 7472 /// arguments. 7473 /// 7474 /// \param PartialTemplateArgs True if the list of template arguments is 7475 /// intentionally partial, e.g., because we're checking just the initial 7476 /// set of template arguments. 7477 /// 7478 /// \param Converted Will receive the converted, canonicalized template 7479 /// arguments. 7480 /// 7481 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to 7482 /// contain the converted forms of the template arguments as written. 7483 /// Otherwise, \p TemplateArgs will not be modified. 7484 /// 7485 /// \param ConstraintsNotSatisfied If provided, and an error occured, will 7486 /// receive true if the cause for the error is the associated constraints of 7487 /// the template not being satisfied by the template arguments. 7488 /// 7489 /// \returns true if an error occurred, false otherwise. 7490 bool CheckTemplateArgumentList(TemplateDecl *Template, 7491 SourceLocation TemplateLoc, 7492 TemplateArgumentListInfo &TemplateArgs, 7493 bool PartialTemplateArgs, 7494 SmallVectorImpl<TemplateArgument> &Converted, 7495 bool UpdateArgsWithConversions = true, 7496 bool *ConstraintsNotSatisfied = nullptr); 7497 7498 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, 7499 TemplateArgumentLoc &Arg, 7500 SmallVectorImpl<TemplateArgument> &Converted); 7501 7502 bool CheckTemplateArgument(TemplateTypeParmDecl *Param, 7503 TypeSourceInfo *Arg); 7504 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 7505 QualType InstantiatedParamType, Expr *Arg, 7506 TemplateArgument &Converted, 7507 CheckTemplateArgumentKind CTAK = CTAK_Specified); 7508 bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, 7509 TemplateParameterList *Params, 7510 TemplateArgumentLoc &Arg); 7511 7512 ExprResult 7513 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, 7514 QualType ParamType, 7515 SourceLocation Loc); 7516 ExprResult 7517 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, 7518 SourceLocation Loc); 7519 7520 /// Enumeration describing how template parameter lists are compared 7521 /// for equality. 7522 enum TemplateParameterListEqualKind { 7523 /// We are matching the template parameter lists of two templates 7524 /// that might be redeclarations. 7525 /// 7526 /// \code 7527 /// template<typename T> struct X; 7528 /// template<typename T> struct X; 7529 /// \endcode 7530 TPL_TemplateMatch, 7531 7532 /// We are matching the template parameter lists of two template 7533 /// template parameters as part of matching the template parameter lists 7534 /// of two templates that might be redeclarations. 7535 /// 7536 /// \code 7537 /// template<template<int I> class TT> struct X; 7538 /// template<template<int Value> class Other> struct X; 7539 /// \endcode 7540 TPL_TemplateTemplateParmMatch, 7541 7542 /// We are matching the template parameter lists of a template 7543 /// template argument against the template parameter lists of a template 7544 /// template parameter. 7545 /// 7546 /// \code 7547 /// template<template<int Value> class Metafun> struct X; 7548 /// template<int Value> struct integer_c; 7549 /// X<integer_c> xic; 7550 /// \endcode 7551 TPL_TemplateTemplateArgumentMatch 7552 }; 7553 7554 bool TemplateParameterListsAreEqual(TemplateParameterList *New, 7555 TemplateParameterList *Old, 7556 bool Complain, 7557 TemplateParameterListEqualKind Kind, 7558 SourceLocation TemplateArgLoc 7559 = SourceLocation()); 7560 7561 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); 7562 7563 /// Called when the parser has parsed a C++ typename 7564 /// specifier, e.g., "typename T::type". 7565 /// 7566 /// \param S The scope in which this typename type occurs. 7567 /// \param TypenameLoc the location of the 'typename' keyword 7568 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 7569 /// \param II the identifier we're retrieving (e.g., 'type' in the example). 7570 /// \param IdLoc the location of the identifier. 7571 TypeResult 7572 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 7573 const CXXScopeSpec &SS, const IdentifierInfo &II, 7574 SourceLocation IdLoc); 7575 7576 /// Called when the parser has parsed a C++ typename 7577 /// specifier that ends in a template-id, e.g., 7578 /// "typename MetaFun::template apply<T1, T2>". 7579 /// 7580 /// \param S The scope in which this typename type occurs. 7581 /// \param TypenameLoc the location of the 'typename' keyword 7582 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 7583 /// \param TemplateLoc the location of the 'template' keyword, if any. 7584 /// \param TemplateName The template name. 7585 /// \param TemplateII The identifier used to name the template. 7586 /// \param TemplateIILoc The location of the template name. 7587 /// \param LAngleLoc The location of the opening angle bracket ('<'). 7588 /// \param TemplateArgs The template arguments. 7589 /// \param RAngleLoc The location of the closing angle bracket ('>'). 7590 TypeResult 7591 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 7592 const CXXScopeSpec &SS, 7593 SourceLocation TemplateLoc, 7594 TemplateTy TemplateName, 7595 IdentifierInfo *TemplateII, 7596 SourceLocation TemplateIILoc, 7597 SourceLocation LAngleLoc, 7598 ASTTemplateArgsPtr TemplateArgs, 7599 SourceLocation RAngleLoc); 7600 7601 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, 7602 SourceLocation KeywordLoc, 7603 NestedNameSpecifierLoc QualifierLoc, 7604 const IdentifierInfo &II, 7605 SourceLocation IILoc, 7606 TypeSourceInfo **TSI, 7607 bool DeducedTSTContext); 7608 7609 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, 7610 SourceLocation KeywordLoc, 7611 NestedNameSpecifierLoc QualifierLoc, 7612 const IdentifierInfo &II, 7613 SourceLocation IILoc, 7614 bool DeducedTSTContext = true); 7615 7616 7617 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, 7618 SourceLocation Loc, 7619 DeclarationName Name); 7620 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); 7621 7622 ExprResult RebuildExprInCurrentInstantiation(Expr *E); 7623 bool RebuildTemplateParamsInCurrentInstantiation( 7624 TemplateParameterList *Params); 7625 7626 std::string 7627 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 7628 const TemplateArgumentList &Args); 7629 7630 std::string 7631 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 7632 const TemplateArgument *Args, 7633 unsigned NumArgs); 7634 7635 //===--------------------------------------------------------------------===// 7636 // C++ Concepts 7637 //===--------------------------------------------------------------------===// 7638 Decl *ActOnConceptDefinition( 7639 Scope *S, MultiTemplateParamsArg TemplateParameterLists, 7640 IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr); 7641 7642 RequiresExprBodyDecl * 7643 ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, 7644 ArrayRef<ParmVarDecl *> LocalParameters, 7645 Scope *BodyScope); 7646 void ActOnFinishRequiresExpr(); 7647 concepts::Requirement *ActOnSimpleRequirement(Expr *E); 7648 concepts::Requirement *ActOnTypeRequirement( 7649 SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc, 7650 IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId); 7651 concepts::Requirement *ActOnCompoundRequirement(Expr *E, 7652 SourceLocation NoexceptLoc); 7653 concepts::Requirement * 7654 ActOnCompoundRequirement( 7655 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS, 7656 TemplateIdAnnotation *TypeConstraint, unsigned Depth); 7657 concepts::Requirement *ActOnNestedRequirement(Expr *Constraint); 7658 concepts::ExprRequirement * 7659 BuildExprRequirement( 7660 Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc, 7661 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); 7662 concepts::ExprRequirement * 7663 BuildExprRequirement( 7664 concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag, 7665 bool IsSatisfied, SourceLocation NoexceptLoc, 7666 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); 7667 concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type); 7668 concepts::TypeRequirement * 7669 BuildTypeRequirement( 7670 concepts::Requirement::SubstitutionDiagnostic *SubstDiag); 7671 concepts::NestedRequirement *BuildNestedRequirement(Expr *E); 7672 concepts::NestedRequirement * 7673 BuildNestedRequirement( 7674 concepts::Requirement::SubstitutionDiagnostic *SubstDiag); 7675 ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc, 7676 RequiresExprBodyDecl *Body, 7677 ArrayRef<ParmVarDecl *> LocalParameters, 7678 ArrayRef<concepts::Requirement *> Requirements, 7679 SourceLocation ClosingBraceLoc); 7680 7681 //===--------------------------------------------------------------------===// 7682 // C++ Variadic Templates (C++0x [temp.variadic]) 7683 //===--------------------------------------------------------------------===// 7684 7685 /// Determine whether an unexpanded parameter pack might be permitted in this 7686 /// location. Useful for error recovery. 7687 bool isUnexpandedParameterPackPermitted(); 7688 7689 /// The context in which an unexpanded parameter pack is 7690 /// being diagnosed. 7691 /// 7692 /// Note that the values of this enumeration line up with the first 7693 /// argument to the \c err_unexpanded_parameter_pack diagnostic. 7694 enum UnexpandedParameterPackContext { 7695 /// An arbitrary expression. 7696 UPPC_Expression = 0, 7697 7698 /// The base type of a class type. 7699 UPPC_BaseType, 7700 7701 /// The type of an arbitrary declaration. 7702 UPPC_DeclarationType, 7703 7704 /// The type of a data member. 7705 UPPC_DataMemberType, 7706 7707 /// The size of a bit-field. 7708 UPPC_BitFieldWidth, 7709 7710 /// The expression in a static assertion. 7711 UPPC_StaticAssertExpression, 7712 7713 /// The fixed underlying type of an enumeration. 7714 UPPC_FixedUnderlyingType, 7715 7716 /// The enumerator value. 7717 UPPC_EnumeratorValue, 7718 7719 /// A using declaration. 7720 UPPC_UsingDeclaration, 7721 7722 /// A friend declaration. 7723 UPPC_FriendDeclaration, 7724 7725 /// A declaration qualifier. 7726 UPPC_DeclarationQualifier, 7727 7728 /// An initializer. 7729 UPPC_Initializer, 7730 7731 /// A default argument. 7732 UPPC_DefaultArgument, 7733 7734 /// The type of a non-type template parameter. 7735 UPPC_NonTypeTemplateParameterType, 7736 7737 /// The type of an exception. 7738 UPPC_ExceptionType, 7739 7740 /// Partial specialization. 7741 UPPC_PartialSpecialization, 7742 7743 /// Microsoft __if_exists. 7744 UPPC_IfExists, 7745 7746 /// Microsoft __if_not_exists. 7747 UPPC_IfNotExists, 7748 7749 /// Lambda expression. 7750 UPPC_Lambda, 7751 7752 /// Block expression, 7753 UPPC_Block, 7754 7755 /// A type constraint, 7756 UPPC_TypeConstraint 7757 }; 7758 7759 /// Diagnose unexpanded parameter packs. 7760 /// 7761 /// \param Loc The location at which we should emit the diagnostic. 7762 /// 7763 /// \param UPPC The context in which we are diagnosing unexpanded 7764 /// parameter packs. 7765 /// 7766 /// \param Unexpanded the set of unexpanded parameter packs. 7767 /// 7768 /// \returns true if an error occurred, false otherwise. 7769 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, 7770 UnexpandedParameterPackContext UPPC, 7771 ArrayRef<UnexpandedParameterPack> Unexpanded); 7772 7773 /// If the given type contains an unexpanded parameter pack, 7774 /// diagnose the error. 7775 /// 7776 /// \param Loc The source location where a diagnostc should be emitted. 7777 /// 7778 /// \param T The type that is being checked for unexpanded parameter 7779 /// packs. 7780 /// 7781 /// \returns true if an error occurred, false otherwise. 7782 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, 7783 UnexpandedParameterPackContext UPPC); 7784 7785 /// If the given expression contains an unexpanded parameter 7786 /// pack, diagnose the error. 7787 /// 7788 /// \param E The expression that is being checked for unexpanded 7789 /// parameter packs. 7790 /// 7791 /// \returns true if an error occurred, false otherwise. 7792 bool DiagnoseUnexpandedParameterPack(Expr *E, 7793 UnexpandedParameterPackContext UPPC = UPPC_Expression); 7794 7795 /// If the given nested-name-specifier contains an unexpanded 7796 /// parameter pack, diagnose the error. 7797 /// 7798 /// \param SS The nested-name-specifier that is being checked for 7799 /// unexpanded parameter packs. 7800 /// 7801 /// \returns true if an error occurred, false otherwise. 7802 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, 7803 UnexpandedParameterPackContext UPPC); 7804 7805 /// If the given name contains an unexpanded parameter pack, 7806 /// diagnose the error. 7807 /// 7808 /// \param NameInfo The name (with source location information) that 7809 /// is being checked for unexpanded parameter packs. 7810 /// 7811 /// \returns true if an error occurred, false otherwise. 7812 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, 7813 UnexpandedParameterPackContext UPPC); 7814 7815 /// If the given template name contains an unexpanded parameter pack, 7816 /// diagnose the error. 7817 /// 7818 /// \param Loc The location of the template name. 7819 /// 7820 /// \param Template The template name that is being checked for unexpanded 7821 /// parameter packs. 7822 /// 7823 /// \returns true if an error occurred, false otherwise. 7824 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, 7825 TemplateName Template, 7826 UnexpandedParameterPackContext UPPC); 7827 7828 /// If the given template argument contains an unexpanded parameter 7829 /// pack, diagnose the error. 7830 /// 7831 /// \param Arg The template argument that is being checked for unexpanded 7832 /// parameter packs. 7833 /// 7834 /// \returns true if an error occurred, false otherwise. 7835 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, 7836 UnexpandedParameterPackContext UPPC); 7837 7838 /// Collect the set of unexpanded parameter packs within the given 7839 /// template argument. 7840 /// 7841 /// \param Arg The template argument that will be traversed to find 7842 /// unexpanded parameter packs. 7843 void collectUnexpandedParameterPacks(TemplateArgument Arg, 7844 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 7845 7846 /// Collect the set of unexpanded parameter packs within the given 7847 /// template argument. 7848 /// 7849 /// \param Arg The template argument that will be traversed to find 7850 /// unexpanded parameter packs. 7851 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, 7852 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 7853 7854 /// Collect the set of unexpanded parameter packs within the given 7855 /// type. 7856 /// 7857 /// \param T The type that will be traversed to find 7858 /// unexpanded parameter packs. 7859 void collectUnexpandedParameterPacks(QualType T, 7860 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 7861 7862 /// Collect the set of unexpanded parameter packs within the given 7863 /// type. 7864 /// 7865 /// \param TL The type that will be traversed to find 7866 /// unexpanded parameter packs. 7867 void collectUnexpandedParameterPacks(TypeLoc TL, 7868 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 7869 7870 /// Collect the set of unexpanded parameter packs within the given 7871 /// nested-name-specifier. 7872 /// 7873 /// \param NNS The nested-name-specifier that will be traversed to find 7874 /// unexpanded parameter packs. 7875 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS, 7876 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 7877 7878 /// Collect the set of unexpanded parameter packs within the given 7879 /// name. 7880 /// 7881 /// \param NameInfo The name that will be traversed to find 7882 /// unexpanded parameter packs. 7883 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, 7884 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 7885 7886 /// Invoked when parsing a template argument followed by an 7887 /// ellipsis, which creates a pack expansion. 7888 /// 7889 /// \param Arg The template argument preceding the ellipsis, which 7890 /// may already be invalid. 7891 /// 7892 /// \param EllipsisLoc The location of the ellipsis. 7893 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, 7894 SourceLocation EllipsisLoc); 7895 7896 /// Invoked when parsing a type followed by an ellipsis, which 7897 /// creates a pack expansion. 7898 /// 7899 /// \param Type The type preceding the ellipsis, which will become 7900 /// the pattern of the pack expansion. 7901 /// 7902 /// \param EllipsisLoc The location of the ellipsis. 7903 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); 7904 7905 /// Construct a pack expansion type from the pattern of the pack 7906 /// expansion. 7907 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, 7908 SourceLocation EllipsisLoc, 7909 Optional<unsigned> NumExpansions); 7910 7911 /// Construct a pack expansion type from the pattern of the pack 7912 /// expansion. 7913 QualType CheckPackExpansion(QualType Pattern, 7914 SourceRange PatternRange, 7915 SourceLocation EllipsisLoc, 7916 Optional<unsigned> NumExpansions); 7917 7918 /// Invoked when parsing an expression followed by an ellipsis, which 7919 /// creates a pack expansion. 7920 /// 7921 /// \param Pattern The expression preceding the ellipsis, which will become 7922 /// the pattern of the pack expansion. 7923 /// 7924 /// \param EllipsisLoc The location of the ellipsis. 7925 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); 7926 7927 /// Invoked when parsing an expression followed by an ellipsis, which 7928 /// creates a pack expansion. 7929 /// 7930 /// \param Pattern The expression preceding the ellipsis, which will become 7931 /// the pattern of the pack expansion. 7932 /// 7933 /// \param EllipsisLoc The location of the ellipsis. 7934 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, 7935 Optional<unsigned> NumExpansions); 7936 7937 /// Determine whether we could expand a pack expansion with the 7938 /// given set of parameter packs into separate arguments by repeatedly 7939 /// transforming the pattern. 7940 /// 7941 /// \param EllipsisLoc The location of the ellipsis that identifies the 7942 /// pack expansion. 7943 /// 7944 /// \param PatternRange The source range that covers the entire pattern of 7945 /// the pack expansion. 7946 /// 7947 /// \param Unexpanded The set of unexpanded parameter packs within the 7948 /// pattern. 7949 /// 7950 /// \param ShouldExpand Will be set to \c true if the transformer should 7951 /// expand the corresponding pack expansions into separate arguments. When 7952 /// set, \c NumExpansions must also be set. 7953 /// 7954 /// \param RetainExpansion Whether the caller should add an unexpanded 7955 /// pack expansion after all of the expanded arguments. This is used 7956 /// when extending explicitly-specified template argument packs per 7957 /// C++0x [temp.arg.explicit]p9. 7958 /// 7959 /// \param NumExpansions The number of separate arguments that will be in 7960 /// the expanded form of the corresponding pack expansion. This is both an 7961 /// input and an output parameter, which can be set by the caller if the 7962 /// number of expansions is known a priori (e.g., due to a prior substitution) 7963 /// and will be set by the callee when the number of expansions is known. 7964 /// The callee must set this value when \c ShouldExpand is \c true; it may 7965 /// set this value in other cases. 7966 /// 7967 /// \returns true if an error occurred (e.g., because the parameter packs 7968 /// are to be instantiated with arguments of different lengths), false 7969 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) 7970 /// must be set. 7971 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, 7972 SourceRange PatternRange, 7973 ArrayRef<UnexpandedParameterPack> Unexpanded, 7974 const MultiLevelTemplateArgumentList &TemplateArgs, 7975 bool &ShouldExpand, 7976 bool &RetainExpansion, 7977 Optional<unsigned> &NumExpansions); 7978 7979 /// Determine the number of arguments in the given pack expansion 7980 /// type. 7981 /// 7982 /// This routine assumes that the number of arguments in the expansion is 7983 /// consistent across all of the unexpanded parameter packs in its pattern. 7984 /// 7985 /// Returns an empty Optional if the type can't be expanded. 7986 Optional<unsigned> getNumArgumentsInExpansion(QualType T, 7987 const MultiLevelTemplateArgumentList &TemplateArgs); 7988 7989 /// Determine whether the given declarator contains any unexpanded 7990 /// parameter packs. 7991 /// 7992 /// This routine is used by the parser to disambiguate function declarators 7993 /// with an ellipsis prior to the ')', e.g., 7994 /// 7995 /// \code 7996 /// void f(T...); 7997 /// \endcode 7998 /// 7999 /// To determine whether we have an (unnamed) function parameter pack or 8000 /// a variadic function. 8001 /// 8002 /// \returns true if the declarator contains any unexpanded parameter packs, 8003 /// false otherwise. 8004 bool containsUnexpandedParameterPacks(Declarator &D); 8005 8006 /// Returns the pattern of the pack expansion for a template argument. 8007 /// 8008 /// \param OrigLoc The template argument to expand. 8009 /// 8010 /// \param Ellipsis Will be set to the location of the ellipsis. 8011 /// 8012 /// \param NumExpansions Will be set to the number of expansions that will 8013 /// be generated from this pack expansion, if known a priori. 8014 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( 8015 TemplateArgumentLoc OrigLoc, 8016 SourceLocation &Ellipsis, 8017 Optional<unsigned> &NumExpansions) const; 8018 8019 /// Given a template argument that contains an unexpanded parameter pack, but 8020 /// which has already been substituted, attempt to determine the number of 8021 /// elements that will be produced once this argument is fully-expanded. 8022 /// 8023 /// This is intended for use when transforming 'sizeof...(Arg)' in order to 8024 /// avoid actually expanding the pack where possible. 8025 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg); 8026 8027 //===--------------------------------------------------------------------===// 8028 // C++ Template Argument Deduction (C++ [temp.deduct]) 8029 //===--------------------------------------------------------------------===// 8030 8031 /// Adjust the type \p ArgFunctionType to match the calling convention, 8032 /// noreturn, and optionally the exception specification of \p FunctionType. 8033 /// Deduction often wants to ignore these properties when matching function 8034 /// types. 8035 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, 8036 bool AdjustExceptionSpec = false); 8037 8038 /// Describes the result of template argument deduction. 8039 /// 8040 /// The TemplateDeductionResult enumeration describes the result of 8041 /// template argument deduction, as returned from 8042 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo 8043 /// structure provides additional information about the results of 8044 /// template argument deduction, e.g., the deduced template argument 8045 /// list (if successful) or the specific template parameters or 8046 /// deduced arguments that were involved in the failure. 8047 enum TemplateDeductionResult { 8048 /// Template argument deduction was successful. 8049 TDK_Success = 0, 8050 /// The declaration was invalid; do nothing. 8051 TDK_Invalid, 8052 /// Template argument deduction exceeded the maximum template 8053 /// instantiation depth (which has already been diagnosed). 8054 TDK_InstantiationDepth, 8055 /// Template argument deduction did not deduce a value 8056 /// for every template parameter. 8057 TDK_Incomplete, 8058 /// Template argument deduction did not deduce a value for every 8059 /// expansion of an expanded template parameter pack. 8060 TDK_IncompletePack, 8061 /// Template argument deduction produced inconsistent 8062 /// deduced values for the given template parameter. 8063 TDK_Inconsistent, 8064 /// Template argument deduction failed due to inconsistent 8065 /// cv-qualifiers on a template parameter type that would 8066 /// otherwise be deduced, e.g., we tried to deduce T in "const T" 8067 /// but were given a non-const "X". 8068 TDK_Underqualified, 8069 /// Substitution of the deduced template argument values 8070 /// resulted in an error. 8071 TDK_SubstitutionFailure, 8072 /// After substituting deduced template arguments, a dependent 8073 /// parameter type did not match the corresponding argument. 8074 TDK_DeducedMismatch, 8075 /// After substituting deduced template arguments, an element of 8076 /// a dependent parameter type did not match the corresponding element 8077 /// of the corresponding argument (when deducing from an initializer list). 8078 TDK_DeducedMismatchNested, 8079 /// A non-depnedent component of the parameter did not match the 8080 /// corresponding component of the argument. 8081 TDK_NonDeducedMismatch, 8082 /// When performing template argument deduction for a function 8083 /// template, there were too many call arguments. 8084 TDK_TooManyArguments, 8085 /// When performing template argument deduction for a function 8086 /// template, there were too few call arguments. 8087 TDK_TooFewArguments, 8088 /// The explicitly-specified template arguments were not valid 8089 /// template arguments for the given template. 8090 TDK_InvalidExplicitArguments, 8091 /// Checking non-dependent argument conversions failed. 8092 TDK_NonDependentConversionFailure, 8093 /// The deduced arguments did not satisfy the constraints associated 8094 /// with the template. 8095 TDK_ConstraintsNotSatisfied, 8096 /// Deduction failed; that's all we know. 8097 TDK_MiscellaneousDeductionFailure, 8098 /// CUDA Target attributes do not match. 8099 TDK_CUDATargetMismatch 8100 }; 8101 8102 TemplateDeductionResult 8103 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, 8104 const TemplateArgumentList &TemplateArgs, 8105 sema::TemplateDeductionInfo &Info); 8106 8107 TemplateDeductionResult 8108 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, 8109 const TemplateArgumentList &TemplateArgs, 8110 sema::TemplateDeductionInfo &Info); 8111 8112 TemplateDeductionResult SubstituteExplicitTemplateArguments( 8113 FunctionTemplateDecl *FunctionTemplate, 8114 TemplateArgumentListInfo &ExplicitTemplateArgs, 8115 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 8116 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, 8117 sema::TemplateDeductionInfo &Info); 8118 8119 /// brief A function argument from which we performed template argument 8120 // deduction for a call. 8121 struct OriginalCallArg { OriginalCallArgOriginalCallArg8122 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, 8123 unsigned ArgIdx, QualType OriginalArgType) 8124 : OriginalParamType(OriginalParamType), 8125 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx), 8126 OriginalArgType(OriginalArgType) {} 8127 8128 QualType OriginalParamType; 8129 bool DecomposedParam; 8130 unsigned ArgIdx; 8131 QualType OriginalArgType; 8132 }; 8133 8134 TemplateDeductionResult FinishTemplateArgumentDeduction( 8135 FunctionTemplateDecl *FunctionTemplate, 8136 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 8137 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, 8138 sema::TemplateDeductionInfo &Info, 8139 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr, 8140 bool PartialOverloading = false, 8141 llvm::function_ref<bool()> CheckNonDependent = []{ return false; }); 8142 8143 TemplateDeductionResult DeduceTemplateArguments( 8144 FunctionTemplateDecl *FunctionTemplate, 8145 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 8146 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, 8147 bool PartialOverloading, 8148 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent); 8149 8150 TemplateDeductionResult 8151 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 8152 TemplateArgumentListInfo *ExplicitTemplateArgs, 8153 QualType ArgFunctionType, 8154 FunctionDecl *&Specialization, 8155 sema::TemplateDeductionInfo &Info, 8156 bool IsAddressOfFunction = false); 8157 8158 TemplateDeductionResult 8159 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 8160 QualType ToType, 8161 CXXConversionDecl *&Specialization, 8162 sema::TemplateDeductionInfo &Info); 8163 8164 TemplateDeductionResult 8165 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 8166 TemplateArgumentListInfo *ExplicitTemplateArgs, 8167 FunctionDecl *&Specialization, 8168 sema::TemplateDeductionInfo &Info, 8169 bool IsAddressOfFunction = false); 8170 8171 /// Substitute Replacement for \p auto in \p TypeWithAuto 8172 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); 8173 /// Substitute Replacement for auto in TypeWithAuto 8174 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, 8175 QualType Replacement); 8176 /// Completely replace the \c auto in \p TypeWithAuto by 8177 /// \p Replacement. This does not retain any \c auto type sugar. 8178 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement); 8179 8180 /// Result type of DeduceAutoType. 8181 enum DeduceAutoResult { 8182 DAR_Succeeded, 8183 DAR_Failed, 8184 DAR_FailedAlreadyDiagnosed 8185 }; 8186 8187 DeduceAutoResult 8188 DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result, 8189 Optional<unsigned> DependentDeductionDepth = None, 8190 bool IgnoreConstraints = false); 8191 DeduceAutoResult 8192 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result, 8193 Optional<unsigned> DependentDeductionDepth = None, 8194 bool IgnoreConstraints = false); 8195 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); 8196 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, 8197 bool Diagnose = true); 8198 8199 /// Declare implicit deduction guides for a class template if we've 8200 /// not already done so. 8201 void DeclareImplicitDeductionGuides(TemplateDecl *Template, 8202 SourceLocation Loc); 8203 8204 QualType DeduceTemplateSpecializationFromInitializer( 8205 TypeSourceInfo *TInfo, const InitializedEntity &Entity, 8206 const InitializationKind &Kind, MultiExprArg Init); 8207 8208 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, 8209 QualType Type, TypeSourceInfo *TSI, 8210 SourceRange Range, bool DirectInit, 8211 Expr *Init); 8212 8213 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const; 8214 8215 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, 8216 SourceLocation ReturnLoc, 8217 Expr *&RetExpr, AutoType *AT); 8218 8219 FunctionTemplateDecl *getMoreSpecializedTemplate( 8220 FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, 8221 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, 8222 unsigned NumCallArguments2, bool Reversed = false); 8223 UnresolvedSetIterator 8224 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, 8225 TemplateSpecCandidateSet &FailedCandidates, 8226 SourceLocation Loc, 8227 const PartialDiagnostic &NoneDiag, 8228 const PartialDiagnostic &AmbigDiag, 8229 const PartialDiagnostic &CandidateDiag, 8230 bool Complain = true, QualType TargetType = QualType()); 8231 8232 ClassTemplatePartialSpecializationDecl * 8233 getMoreSpecializedPartialSpecialization( 8234 ClassTemplatePartialSpecializationDecl *PS1, 8235 ClassTemplatePartialSpecializationDecl *PS2, 8236 SourceLocation Loc); 8237 8238 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, 8239 sema::TemplateDeductionInfo &Info); 8240 8241 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( 8242 VarTemplatePartialSpecializationDecl *PS1, 8243 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); 8244 8245 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T, 8246 sema::TemplateDeductionInfo &Info); 8247 8248 bool isTemplateTemplateParameterAtLeastAsSpecializedAs( 8249 TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc); 8250 8251 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, 8252 unsigned Depth, llvm::SmallBitVector &Used); 8253 8254 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, 8255 bool OnlyDeduced, 8256 unsigned Depth, 8257 llvm::SmallBitVector &Used); MarkDeducedTemplateParameters(const FunctionTemplateDecl * FunctionTemplate,llvm::SmallBitVector & Deduced)8258 void MarkDeducedTemplateParameters( 8259 const FunctionTemplateDecl *FunctionTemplate, 8260 llvm::SmallBitVector &Deduced) { 8261 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); 8262 } 8263 static void MarkDeducedTemplateParameters(ASTContext &Ctx, 8264 const FunctionTemplateDecl *FunctionTemplate, 8265 llvm::SmallBitVector &Deduced); 8266 8267 //===--------------------------------------------------------------------===// 8268 // C++ Template Instantiation 8269 // 8270 8271 MultiLevelTemplateArgumentList 8272 getTemplateInstantiationArgs(NamedDecl *D, 8273 const TemplateArgumentList *Innermost = nullptr, 8274 bool RelativeToPrimary = false, 8275 const FunctionDecl *Pattern = nullptr); 8276 8277 /// A context in which code is being synthesized (where a source location 8278 /// alone is not sufficient to identify the context). This covers template 8279 /// instantiation and various forms of implicitly-generated functions. 8280 struct CodeSynthesisContext { 8281 /// The kind of template instantiation we are performing 8282 enum SynthesisKind { 8283 /// We are instantiating a template declaration. The entity is 8284 /// the declaration we're instantiating (e.g., a CXXRecordDecl). 8285 TemplateInstantiation, 8286 8287 /// We are instantiating a default argument for a template 8288 /// parameter. The Entity is the template parameter whose argument is 8289 /// being instantiated, the Template is the template, and the 8290 /// TemplateArgs/NumTemplateArguments provide the template arguments as 8291 /// specified. 8292 DefaultTemplateArgumentInstantiation, 8293 8294 /// We are instantiating a default argument for a function. 8295 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs 8296 /// provides the template arguments as specified. 8297 DefaultFunctionArgumentInstantiation, 8298 8299 /// We are substituting explicit template arguments provided for 8300 /// a function template. The entity is a FunctionTemplateDecl. 8301 ExplicitTemplateArgumentSubstitution, 8302 8303 /// We are substituting template argument determined as part of 8304 /// template argument deduction for either a class template 8305 /// partial specialization or a function template. The 8306 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or 8307 /// a TemplateDecl. 8308 DeducedTemplateArgumentSubstitution, 8309 8310 /// We are substituting prior template arguments into a new 8311 /// template parameter. The template parameter itself is either a 8312 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. 8313 PriorTemplateArgumentSubstitution, 8314 8315 /// We are checking the validity of a default template argument that 8316 /// has been used when naming a template-id. 8317 DefaultTemplateArgumentChecking, 8318 8319 /// We are computing the exception specification for a defaulted special 8320 /// member function. 8321 ExceptionSpecEvaluation, 8322 8323 /// We are instantiating the exception specification for a function 8324 /// template which was deferred until it was needed. 8325 ExceptionSpecInstantiation, 8326 8327 /// We are instantiating a requirement of a requires expression. 8328 RequirementInstantiation, 8329 8330 /// We are checking the satisfaction of a nested requirement of a requires 8331 /// expression. 8332 NestedRequirementConstraintsCheck, 8333 8334 /// We are declaring an implicit special member function. 8335 DeclaringSpecialMember, 8336 8337 /// We are declaring an implicit 'operator==' for a defaulted 8338 /// 'operator<=>'. 8339 DeclaringImplicitEqualityComparison, 8340 8341 /// We are defining a synthesized function (such as a defaulted special 8342 /// member). 8343 DefiningSynthesizedFunction, 8344 8345 // We are checking the constraints associated with a constrained entity or 8346 // the constraint expression of a concept. This includes the checks that 8347 // atomic constraints have the type 'bool' and that they can be constant 8348 // evaluated. 8349 ConstraintsCheck, 8350 8351 // We are substituting template arguments into a constraint expression. 8352 ConstraintSubstitution, 8353 8354 // We are normalizing a constraint expression. 8355 ConstraintNormalization, 8356 8357 // We are substituting into the parameter mapping of an atomic constraint 8358 // during normalization. 8359 ParameterMappingSubstitution, 8360 8361 /// We are rewriting a comparison operator in terms of an operator<=>. 8362 RewritingOperatorAsSpaceship, 8363 8364 /// We are initializing a structured binding. 8365 InitializingStructuredBinding, 8366 8367 /// We are marking a class as __dllexport. 8368 MarkingClassDllexported, 8369 8370 /// Added for Template instantiation observation. 8371 /// Memoization means we are _not_ instantiating a template because 8372 /// it is already instantiated (but we entered a context where we 8373 /// would have had to if it was not already instantiated). 8374 Memoization 8375 } Kind; 8376 8377 /// Was the enclosing context a non-instantiation SFINAE context? 8378 bool SavedInNonInstantiationSFINAEContext; 8379 8380 /// The point of instantiation or synthesis within the source code. 8381 SourceLocation PointOfInstantiation; 8382 8383 /// The entity that is being synthesized. 8384 Decl *Entity; 8385 8386 /// The template (or partial specialization) in which we are 8387 /// performing the instantiation, for substitutions of prior template 8388 /// arguments. 8389 NamedDecl *Template; 8390 8391 /// The list of template arguments we are substituting, if they 8392 /// are not part of the entity. 8393 const TemplateArgument *TemplateArgs; 8394 8395 // FIXME: Wrap this union around more members, or perhaps store the 8396 // kind-specific members in the RAII object owning the context. 8397 union { 8398 /// The number of template arguments in TemplateArgs. 8399 unsigned NumTemplateArgs; 8400 8401 /// The special member being declared or defined. 8402 CXXSpecialMember SpecialMember; 8403 }; 8404 template_argumentsCodeSynthesisContext8405 ArrayRef<TemplateArgument> template_arguments() const { 8406 assert(Kind != DeclaringSpecialMember); 8407 return {TemplateArgs, NumTemplateArgs}; 8408 } 8409 8410 /// The template deduction info object associated with the 8411 /// substitution or checking of explicit or deduced template arguments. 8412 sema::TemplateDeductionInfo *DeductionInfo; 8413 8414 /// The source range that covers the construct that cause 8415 /// the instantiation, e.g., the template-id that causes a class 8416 /// template instantiation. 8417 SourceRange InstantiationRange; 8418 CodeSynthesisContextCodeSynthesisContext8419 CodeSynthesisContext() 8420 : Kind(TemplateInstantiation), 8421 SavedInNonInstantiationSFINAEContext(false), Entity(nullptr), 8422 Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0), 8423 DeductionInfo(nullptr) {} 8424 8425 /// Determines whether this template is an actual instantiation 8426 /// that should be counted toward the maximum instantiation depth. 8427 bool isInstantiationRecord() const; 8428 }; 8429 8430 /// List of active code synthesis contexts. 8431 /// 8432 /// This vector is treated as a stack. As synthesis of one entity requires 8433 /// synthesis of another, additional contexts are pushed onto the stack. 8434 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts; 8435 8436 /// Specializations whose definitions are currently being instantiated. 8437 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations; 8438 8439 /// Non-dependent types used in templates that have already been instantiated 8440 /// by some template instantiation. 8441 llvm::DenseSet<QualType> InstantiatedNonDependentTypes; 8442 8443 /// Extra modules inspected when performing a lookup during a template 8444 /// instantiation. Computed lazily. 8445 SmallVector<Module*, 16> CodeSynthesisContextLookupModules; 8446 8447 /// Cache of additional modules that should be used for name lookup 8448 /// within the current template instantiation. Computed lazily; use 8449 /// getLookupModules() to get a complete set. 8450 llvm::DenseSet<Module*> LookupModulesCache; 8451 8452 /// Get the set of additional modules that should be checked during 8453 /// name lookup. A module and its imports become visible when instanting a 8454 /// template defined within it. 8455 llvm::DenseSet<Module*> &getLookupModules(); 8456 8457 /// Map from the most recent declaration of a namespace to the most 8458 /// recent visible declaration of that namespace. 8459 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache; 8460 8461 /// Whether we are in a SFINAE context that is not associated with 8462 /// template instantiation. 8463 /// 8464 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside 8465 /// of a template instantiation or template argument deduction. 8466 bool InNonInstantiationSFINAEContext; 8467 8468 /// The number of \p CodeSynthesisContexts that are not template 8469 /// instantiations and, therefore, should not be counted as part of the 8470 /// instantiation depth. 8471 /// 8472 /// When the instantiation depth reaches the user-configurable limit 8473 /// \p LangOptions::InstantiationDepth we will abort instantiation. 8474 // FIXME: Should we have a similar limit for other forms of synthesis? 8475 unsigned NonInstantiationEntries; 8476 8477 /// The depth of the context stack at the point when the most recent 8478 /// error or warning was produced. 8479 /// 8480 /// This value is used to suppress printing of redundant context stacks 8481 /// when there are multiple errors or warnings in the same instantiation. 8482 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else. 8483 unsigned LastEmittedCodeSynthesisContextDepth = 0; 8484 8485 /// The template instantiation callbacks to trace or track 8486 /// instantiations (objects can be chained). 8487 /// 8488 /// This callbacks is used to print, trace or track template 8489 /// instantiations as they are being constructed. 8490 std::vector<std::unique_ptr<TemplateInstantiationCallback>> 8491 TemplateInstCallbacks; 8492 8493 /// The current index into pack expansion arguments that will be 8494 /// used for substitution of parameter packs. 8495 /// 8496 /// The pack expansion index will be -1 to indicate that parameter packs 8497 /// should be instantiated as themselves. Otherwise, the index specifies 8498 /// which argument within the parameter pack will be used for substitution. 8499 int ArgumentPackSubstitutionIndex; 8500 8501 /// RAII object used to change the argument pack substitution index 8502 /// within a \c Sema object. 8503 /// 8504 /// See \c ArgumentPackSubstitutionIndex for more information. 8505 class ArgumentPackSubstitutionIndexRAII { 8506 Sema &Self; 8507 int OldSubstitutionIndex; 8508 8509 public: ArgumentPackSubstitutionIndexRAII(Sema & Self,int NewSubstitutionIndex)8510 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) 8511 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { 8512 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; 8513 } 8514 ~ArgumentPackSubstitutionIndexRAII()8515 ~ArgumentPackSubstitutionIndexRAII() { 8516 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; 8517 } 8518 }; 8519 8520 friend class ArgumentPackSubstitutionRAII; 8521 8522 /// For each declaration that involved template argument deduction, the 8523 /// set of diagnostics that were suppressed during that template argument 8524 /// deduction. 8525 /// 8526 /// FIXME: Serialize this structure to the AST file. 8527 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > 8528 SuppressedDiagnosticsMap; 8529 SuppressedDiagnosticsMap SuppressedDiagnostics; 8530 8531 /// A stack object to be created when performing template 8532 /// instantiation. 8533 /// 8534 /// Construction of an object of type \c InstantiatingTemplate 8535 /// pushes the current instantiation onto the stack of active 8536 /// instantiations. If the size of this stack exceeds the maximum 8537 /// number of recursive template instantiations, construction 8538 /// produces an error and evaluates true. 8539 /// 8540 /// Destruction of this object will pop the named instantiation off 8541 /// the stack. 8542 struct InstantiatingTemplate { 8543 /// Note that we are instantiating a class template, 8544 /// function template, variable template, alias template, 8545 /// or a member thereof. 8546 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8547 Decl *Entity, 8548 SourceRange InstantiationRange = SourceRange()); 8549 8550 struct ExceptionSpecification {}; 8551 /// Note that we are instantiating an exception specification 8552 /// of a function template. 8553 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8554 FunctionDecl *Entity, ExceptionSpecification, 8555 SourceRange InstantiationRange = SourceRange()); 8556 8557 /// Note that we are instantiating a default argument in a 8558 /// template-id. 8559 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8560 TemplateParameter Param, TemplateDecl *Template, 8561 ArrayRef<TemplateArgument> TemplateArgs, 8562 SourceRange InstantiationRange = SourceRange()); 8563 8564 /// Note that we are substituting either explicitly-specified or 8565 /// deduced template arguments during function template argument deduction. 8566 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8567 FunctionTemplateDecl *FunctionTemplate, 8568 ArrayRef<TemplateArgument> TemplateArgs, 8569 CodeSynthesisContext::SynthesisKind Kind, 8570 sema::TemplateDeductionInfo &DeductionInfo, 8571 SourceRange InstantiationRange = SourceRange()); 8572 8573 /// Note that we are instantiating as part of template 8574 /// argument deduction for a class template declaration. 8575 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8576 TemplateDecl *Template, 8577 ArrayRef<TemplateArgument> TemplateArgs, 8578 sema::TemplateDeductionInfo &DeductionInfo, 8579 SourceRange InstantiationRange = SourceRange()); 8580 8581 /// Note that we are instantiating as part of template 8582 /// argument deduction for a class template partial 8583 /// specialization. 8584 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8585 ClassTemplatePartialSpecializationDecl *PartialSpec, 8586 ArrayRef<TemplateArgument> TemplateArgs, 8587 sema::TemplateDeductionInfo &DeductionInfo, 8588 SourceRange InstantiationRange = SourceRange()); 8589 8590 /// Note that we are instantiating as part of template 8591 /// argument deduction for a variable template partial 8592 /// specialization. 8593 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8594 VarTemplatePartialSpecializationDecl *PartialSpec, 8595 ArrayRef<TemplateArgument> TemplateArgs, 8596 sema::TemplateDeductionInfo &DeductionInfo, 8597 SourceRange InstantiationRange = SourceRange()); 8598 8599 /// Note that we are instantiating a default argument for a function 8600 /// parameter. 8601 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8602 ParmVarDecl *Param, 8603 ArrayRef<TemplateArgument> TemplateArgs, 8604 SourceRange InstantiationRange = SourceRange()); 8605 8606 /// Note that we are substituting prior template arguments into a 8607 /// non-type parameter. 8608 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8609 NamedDecl *Template, 8610 NonTypeTemplateParmDecl *Param, 8611 ArrayRef<TemplateArgument> TemplateArgs, 8612 SourceRange InstantiationRange); 8613 8614 /// Note that we are substituting prior template arguments into a 8615 /// template template parameter. 8616 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8617 NamedDecl *Template, 8618 TemplateTemplateParmDecl *Param, 8619 ArrayRef<TemplateArgument> TemplateArgs, 8620 SourceRange InstantiationRange); 8621 8622 /// Note that we are checking the default template argument 8623 /// against the template parameter for a given template-id. 8624 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8625 TemplateDecl *Template, 8626 NamedDecl *Param, 8627 ArrayRef<TemplateArgument> TemplateArgs, 8628 SourceRange InstantiationRange); 8629 8630 struct ConstraintsCheck {}; 8631 /// \brief Note that we are checking the constraints associated with some 8632 /// constrained entity (a concept declaration or a template with associated 8633 /// constraints). 8634 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8635 ConstraintsCheck, NamedDecl *Template, 8636 ArrayRef<TemplateArgument> TemplateArgs, 8637 SourceRange InstantiationRange); 8638 8639 struct ConstraintSubstitution {}; 8640 /// \brief Note that we are checking a constraint expression associated 8641 /// with a template declaration or as part of the satisfaction check of a 8642 /// concept. 8643 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8644 ConstraintSubstitution, NamedDecl *Template, 8645 sema::TemplateDeductionInfo &DeductionInfo, 8646 SourceRange InstantiationRange); 8647 8648 struct ConstraintNormalization {}; 8649 /// \brief Note that we are normalizing a constraint expression. 8650 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8651 ConstraintNormalization, NamedDecl *Template, 8652 SourceRange InstantiationRange); 8653 8654 struct ParameterMappingSubstitution {}; 8655 /// \brief Note that we are subtituting into the parameter mapping of an 8656 /// atomic constraint during constraint normalization. 8657 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8658 ParameterMappingSubstitution, NamedDecl *Template, 8659 SourceRange InstantiationRange); 8660 8661 /// \brief Note that we are substituting template arguments into a part of 8662 /// a requirement of a requires expression. 8663 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8664 concepts::Requirement *Req, 8665 sema::TemplateDeductionInfo &DeductionInfo, 8666 SourceRange InstantiationRange = SourceRange()); 8667 8668 /// \brief Note that we are checking the satisfaction of the constraint 8669 /// expression inside of a nested requirement. 8670 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8671 concepts::NestedRequirement *Req, ConstraintsCheck, 8672 SourceRange InstantiationRange = SourceRange()); 8673 8674 /// Note that we have finished instantiating this template. 8675 void Clear(); 8676 ~InstantiatingTemplateInstantiatingTemplate8677 ~InstantiatingTemplate() { Clear(); } 8678 8679 /// Determines whether we have exceeded the maximum 8680 /// recursive template instantiations. isInvalidInstantiatingTemplate8681 bool isInvalid() const { return Invalid; } 8682 8683 /// Determine whether we are already instantiating this 8684 /// specialization in some surrounding active instantiation. isAlreadyInstantiatingInstantiatingTemplate8685 bool isAlreadyInstantiating() const { return AlreadyInstantiating; } 8686 8687 private: 8688 Sema &SemaRef; 8689 bool Invalid; 8690 bool AlreadyInstantiating; 8691 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, 8692 SourceRange InstantiationRange); 8693 8694 InstantiatingTemplate( 8695 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, 8696 SourceLocation PointOfInstantiation, SourceRange InstantiationRange, 8697 Decl *Entity, NamedDecl *Template = nullptr, 8698 ArrayRef<TemplateArgument> TemplateArgs = None, 8699 sema::TemplateDeductionInfo *DeductionInfo = nullptr); 8700 8701 InstantiatingTemplate(const InstantiatingTemplate&) = delete; 8702 8703 InstantiatingTemplate& 8704 operator=(const InstantiatingTemplate&) = delete; 8705 }; 8706 8707 void pushCodeSynthesisContext(CodeSynthesisContext Ctx); 8708 void popCodeSynthesisContext(); 8709 8710 /// Determine whether we are currently performing template instantiation. inTemplateInstantiation()8711 bool inTemplateInstantiation() const { 8712 return CodeSynthesisContexts.size() > NonInstantiationEntries; 8713 } 8714 PrintContextStack()8715 void PrintContextStack() { 8716 if (!CodeSynthesisContexts.empty() && 8717 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) { 8718 PrintInstantiationStack(); 8719 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size(); 8720 } 8721 if (PragmaAttributeCurrentTargetDecl) 8722 PrintPragmaAttributeInstantiationPoint(); 8723 } 8724 void PrintInstantiationStack(); 8725 8726 void PrintPragmaAttributeInstantiationPoint(); 8727 8728 /// Determines whether we are currently in a context where 8729 /// template argument substitution failures are not considered 8730 /// errors. 8731 /// 8732 /// \returns An empty \c Optional if we're not in a SFINAE context. 8733 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest 8734 /// template-deduction context object, which can be used to capture 8735 /// diagnostics that will be suppressed. 8736 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; 8737 8738 /// Determines whether we are currently in a context that 8739 /// is not evaluated as per C++ [expr] p5. isUnevaluatedContext()8740 bool isUnevaluatedContext() const { 8741 assert(!ExprEvalContexts.empty() && 8742 "Must be in an expression evaluation context"); 8743 return ExprEvalContexts.back().isUnevaluated(); 8744 } 8745 8746 /// RAII class used to determine whether SFINAE has 8747 /// trapped any errors that occur during template argument 8748 /// deduction. 8749 class SFINAETrap { 8750 Sema &SemaRef; 8751 unsigned PrevSFINAEErrors; 8752 bool PrevInNonInstantiationSFINAEContext; 8753 bool PrevAccessCheckingSFINAE; 8754 bool PrevLastDiagnosticIgnored; 8755 8756 public: 8757 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) SemaRef(SemaRef)8758 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), 8759 PrevInNonInstantiationSFINAEContext( 8760 SemaRef.InNonInstantiationSFINAEContext), 8761 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE), 8762 PrevLastDiagnosticIgnored( 8763 SemaRef.getDiagnostics().isLastDiagnosticIgnored()) 8764 { 8765 if (!SemaRef.isSFINAEContext()) 8766 SemaRef.InNonInstantiationSFINAEContext = true; 8767 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; 8768 } 8769 ~SFINAETrap()8770 ~SFINAETrap() { 8771 SemaRef.NumSFINAEErrors = PrevSFINAEErrors; 8772 SemaRef.InNonInstantiationSFINAEContext 8773 = PrevInNonInstantiationSFINAEContext; 8774 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; 8775 SemaRef.getDiagnostics().setLastDiagnosticIgnored( 8776 PrevLastDiagnosticIgnored); 8777 } 8778 8779 /// Determine whether any SFINAE errors have been trapped. hasErrorOccurred()8780 bool hasErrorOccurred() const { 8781 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; 8782 } 8783 }; 8784 8785 /// RAII class used to indicate that we are performing provisional 8786 /// semantic analysis to determine the validity of a construct, so 8787 /// typo-correction and diagnostics in the immediate context (not within 8788 /// implicitly-instantiated templates) should be suppressed. 8789 class TentativeAnalysisScope { 8790 Sema &SemaRef; 8791 // FIXME: Using a SFINAETrap for this is a hack. 8792 SFINAETrap Trap; 8793 bool PrevDisableTypoCorrection; 8794 public: TentativeAnalysisScope(Sema & SemaRef)8795 explicit TentativeAnalysisScope(Sema &SemaRef) 8796 : SemaRef(SemaRef), Trap(SemaRef, true), 8797 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) { 8798 SemaRef.DisableTypoCorrection = true; 8799 } ~TentativeAnalysisScope()8800 ~TentativeAnalysisScope() { 8801 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection; 8802 } 8803 }; 8804 8805 /// The current instantiation scope used to store local 8806 /// variables. 8807 LocalInstantiationScope *CurrentInstantiationScope; 8808 8809 /// Tracks whether we are in a context where typo correction is 8810 /// disabled. 8811 bool DisableTypoCorrection; 8812 8813 /// The number of typos corrected by CorrectTypo. 8814 unsigned TyposCorrected; 8815 8816 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet; 8817 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations; 8818 8819 /// A cache containing identifiers for which typo correction failed and 8820 /// their locations, so that repeated attempts to correct an identifier in a 8821 /// given location are ignored if typo correction already failed for it. 8822 IdentifierSourceLocations TypoCorrectionFailures; 8823 8824 /// Worker object for performing CFG-based warnings. 8825 sema::AnalysisBasedWarnings AnalysisWarnings; 8826 threadSafety::BeforeSet *ThreadSafetyDeclCache; 8827 8828 /// An entity for which implicit template instantiation is required. 8829 /// 8830 /// The source location associated with the declaration is the first place in 8831 /// the source code where the declaration was "used". It is not necessarily 8832 /// the point of instantiation (which will be either before or after the 8833 /// namespace-scope declaration that triggered this implicit instantiation), 8834 /// However, it is the location that diagnostics should generally refer to, 8835 /// because users will need to know what code triggered the instantiation. 8836 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; 8837 8838 /// The queue of implicit template instantiations that are required 8839 /// but have not yet been performed. 8840 std::deque<PendingImplicitInstantiation> PendingInstantiations; 8841 8842 /// Queue of implicit template instantiations that cannot be performed 8843 /// eagerly. 8844 SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations; 8845 8846 class GlobalEagerInstantiationScope { 8847 public: GlobalEagerInstantiationScope(Sema & S,bool Enabled)8848 GlobalEagerInstantiationScope(Sema &S, bool Enabled) 8849 : S(S), Enabled(Enabled) { 8850 if (!Enabled) return; 8851 8852 SavedPendingInstantiations.swap(S.PendingInstantiations); 8853 SavedVTableUses.swap(S.VTableUses); 8854 } 8855 perform()8856 void perform() { 8857 if (Enabled) { 8858 S.DefineUsedVTables(); 8859 S.PerformPendingInstantiations(); 8860 } 8861 } 8862 ~GlobalEagerInstantiationScope()8863 ~GlobalEagerInstantiationScope() { 8864 if (!Enabled) return; 8865 8866 // Restore the set of pending vtables. 8867 assert(S.VTableUses.empty() && 8868 "VTableUses should be empty before it is discarded."); 8869 S.VTableUses.swap(SavedVTableUses); 8870 8871 // Restore the set of pending implicit instantiations. 8872 if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) { 8873 assert(S.PendingInstantiations.empty() && 8874 "PendingInstantiations should be empty before it is discarded."); 8875 S.PendingInstantiations.swap(SavedPendingInstantiations); 8876 } else { 8877 // Template instantiations in the PCH may be delayed until the TU. 8878 S.PendingInstantiations.swap(SavedPendingInstantiations); 8879 S.PendingInstantiations.insert(S.PendingInstantiations.end(), 8880 SavedPendingInstantiations.begin(), 8881 SavedPendingInstantiations.end()); 8882 } 8883 } 8884 8885 private: 8886 Sema &S; 8887 SmallVector<VTableUse, 16> SavedVTableUses; 8888 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; 8889 bool Enabled; 8890 }; 8891 8892 /// The queue of implicit template instantiations that are required 8893 /// and must be performed within the current local scope. 8894 /// 8895 /// This queue is only used for member functions of local classes in 8896 /// templates, which must be instantiated in the same scope as their 8897 /// enclosing function, so that they can reference function-local 8898 /// types, static variables, enumerators, etc. 8899 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; 8900 8901 class LocalEagerInstantiationScope { 8902 public: LocalEagerInstantiationScope(Sema & S)8903 LocalEagerInstantiationScope(Sema &S) : S(S) { 8904 SavedPendingLocalImplicitInstantiations.swap( 8905 S.PendingLocalImplicitInstantiations); 8906 } 8907 perform()8908 void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); } 8909 ~LocalEagerInstantiationScope()8910 ~LocalEagerInstantiationScope() { 8911 assert(S.PendingLocalImplicitInstantiations.empty() && 8912 "there shouldn't be any pending local implicit instantiations"); 8913 SavedPendingLocalImplicitInstantiations.swap( 8914 S.PendingLocalImplicitInstantiations); 8915 } 8916 8917 private: 8918 Sema &S; 8919 std::deque<PendingImplicitInstantiation> 8920 SavedPendingLocalImplicitInstantiations; 8921 }; 8922 8923 /// A helper class for building up ExtParameterInfos. 8924 class ExtParameterInfoBuilder { 8925 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos; 8926 bool HasInteresting = false; 8927 8928 public: 8929 /// Set the ExtParameterInfo for the parameter at the given index, 8930 /// set(unsigned index,FunctionProtoType::ExtParameterInfo info)8931 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) { 8932 assert(Infos.size() <= index); 8933 Infos.resize(index); 8934 Infos.push_back(info); 8935 8936 if (!HasInteresting) 8937 HasInteresting = (info != FunctionProtoType::ExtParameterInfo()); 8938 } 8939 8940 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the 8941 /// ExtParameterInfo array we've built up. 8942 const FunctionProtoType::ExtParameterInfo * getPointerOrNull(unsigned numParams)8943 getPointerOrNull(unsigned numParams) { 8944 if (!HasInteresting) return nullptr; 8945 Infos.resize(numParams); 8946 return Infos.data(); 8947 } 8948 }; 8949 8950 void PerformPendingInstantiations(bool LocalOnly = false); 8951 8952 TypeSourceInfo *SubstType(TypeSourceInfo *T, 8953 const MultiLevelTemplateArgumentList &TemplateArgs, 8954 SourceLocation Loc, DeclarationName Entity, 8955 bool AllowDeducedTST = false); 8956 8957 QualType SubstType(QualType T, 8958 const MultiLevelTemplateArgumentList &TemplateArgs, 8959 SourceLocation Loc, DeclarationName Entity); 8960 8961 TypeSourceInfo *SubstType(TypeLoc TL, 8962 const MultiLevelTemplateArgumentList &TemplateArgs, 8963 SourceLocation Loc, DeclarationName Entity); 8964 8965 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, 8966 const MultiLevelTemplateArgumentList &TemplateArgs, 8967 SourceLocation Loc, 8968 DeclarationName Entity, 8969 CXXRecordDecl *ThisContext, 8970 Qualifiers ThisTypeQuals); 8971 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, 8972 const MultiLevelTemplateArgumentList &Args); 8973 bool SubstExceptionSpec(SourceLocation Loc, 8974 FunctionProtoType::ExceptionSpecInfo &ESI, 8975 SmallVectorImpl<QualType> &ExceptionStorage, 8976 const MultiLevelTemplateArgumentList &Args); 8977 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, 8978 const MultiLevelTemplateArgumentList &TemplateArgs, 8979 int indexAdjustment, 8980 Optional<unsigned> NumExpansions, 8981 bool ExpectParameterPack); 8982 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, 8983 const FunctionProtoType::ExtParameterInfo *ExtParamInfos, 8984 const MultiLevelTemplateArgumentList &TemplateArgs, 8985 SmallVectorImpl<QualType> &ParamTypes, 8986 SmallVectorImpl<ParmVarDecl *> *OutParams, 8987 ExtParameterInfoBuilder &ParamInfos); 8988 ExprResult SubstExpr(Expr *E, 8989 const MultiLevelTemplateArgumentList &TemplateArgs); 8990 8991 /// Substitute the given template arguments into a list of 8992 /// expressions, expanding pack expansions if required. 8993 /// 8994 /// \param Exprs The list of expressions to substitute into. 8995 /// 8996 /// \param IsCall Whether this is some form of call, in which case 8997 /// default arguments will be dropped. 8998 /// 8999 /// \param TemplateArgs The set of template arguments to substitute. 9000 /// 9001 /// \param Outputs Will receive all of the substituted arguments. 9002 /// 9003 /// \returns true if an error occurred, false otherwise. 9004 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, 9005 const MultiLevelTemplateArgumentList &TemplateArgs, 9006 SmallVectorImpl<Expr *> &Outputs); 9007 9008 StmtResult SubstStmt(Stmt *S, 9009 const MultiLevelTemplateArgumentList &TemplateArgs); 9010 9011 TemplateParameterList * 9012 SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, 9013 const MultiLevelTemplateArgumentList &TemplateArgs); 9014 9015 bool 9016 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, 9017 const MultiLevelTemplateArgumentList &TemplateArgs, 9018 TemplateArgumentListInfo &Outputs); 9019 9020 9021 Decl *SubstDecl(Decl *D, DeclContext *Owner, 9022 const MultiLevelTemplateArgumentList &TemplateArgs); 9023 9024 /// Substitute the name and return type of a defaulted 'operator<=>' to form 9025 /// an implicit 'operator=='. 9026 FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, 9027 FunctionDecl *Spaceship); 9028 9029 ExprResult SubstInitializer(Expr *E, 9030 const MultiLevelTemplateArgumentList &TemplateArgs, 9031 bool CXXDirectInit); 9032 9033 bool 9034 SubstBaseSpecifiers(CXXRecordDecl *Instantiation, 9035 CXXRecordDecl *Pattern, 9036 const MultiLevelTemplateArgumentList &TemplateArgs); 9037 9038 bool 9039 InstantiateClass(SourceLocation PointOfInstantiation, 9040 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, 9041 const MultiLevelTemplateArgumentList &TemplateArgs, 9042 TemplateSpecializationKind TSK, 9043 bool Complain = true); 9044 9045 bool InstantiateEnum(SourceLocation PointOfInstantiation, 9046 EnumDecl *Instantiation, EnumDecl *Pattern, 9047 const MultiLevelTemplateArgumentList &TemplateArgs, 9048 TemplateSpecializationKind TSK); 9049 9050 bool InstantiateInClassInitializer( 9051 SourceLocation PointOfInstantiation, FieldDecl *Instantiation, 9052 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); 9053 9054 struct LateInstantiatedAttribute { 9055 const Attr *TmplAttr; 9056 LocalInstantiationScope *Scope; 9057 Decl *NewDecl; 9058 LateInstantiatedAttributeLateInstantiatedAttribute9059 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, 9060 Decl *D) 9061 : TmplAttr(A), Scope(S), NewDecl(D) 9062 { } 9063 }; 9064 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; 9065 9066 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, 9067 const Decl *Pattern, Decl *Inst, 9068 LateInstantiatedAttrVec *LateAttrs = nullptr, 9069 LocalInstantiationScope *OuterMostScope = nullptr); 9070 9071 void 9072 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, 9073 const Decl *Pattern, Decl *Inst, 9074 LateInstantiatedAttrVec *LateAttrs = nullptr, 9075 LocalInstantiationScope *OuterMostScope = nullptr); 9076 9077 bool usesPartialOrExplicitSpecialization( 9078 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec); 9079 9080 bool 9081 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, 9082 ClassTemplateSpecializationDecl *ClassTemplateSpec, 9083 TemplateSpecializationKind TSK, 9084 bool Complain = true); 9085 9086 void InstantiateClassMembers(SourceLocation PointOfInstantiation, 9087 CXXRecordDecl *Instantiation, 9088 const MultiLevelTemplateArgumentList &TemplateArgs, 9089 TemplateSpecializationKind TSK); 9090 9091 void InstantiateClassTemplateSpecializationMembers( 9092 SourceLocation PointOfInstantiation, 9093 ClassTemplateSpecializationDecl *ClassTemplateSpec, 9094 TemplateSpecializationKind TSK); 9095 9096 NestedNameSpecifierLoc 9097 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 9098 const MultiLevelTemplateArgumentList &TemplateArgs); 9099 9100 DeclarationNameInfo 9101 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 9102 const MultiLevelTemplateArgumentList &TemplateArgs); 9103 TemplateName 9104 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, 9105 SourceLocation Loc, 9106 const MultiLevelTemplateArgumentList &TemplateArgs); 9107 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, 9108 TemplateArgumentListInfo &Result, 9109 const MultiLevelTemplateArgumentList &TemplateArgs); 9110 9111 bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, 9112 ParmVarDecl *Param); 9113 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, 9114 FunctionDecl *Function); 9115 bool CheckInstantiatedFunctionTemplateConstraints( 9116 SourceLocation PointOfInstantiation, FunctionDecl *Decl, 9117 ArrayRef<TemplateArgument> TemplateArgs, 9118 ConstraintSatisfaction &Satisfaction); 9119 FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, 9120 const TemplateArgumentList *Args, 9121 SourceLocation Loc); 9122 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 9123 FunctionDecl *Function, 9124 bool Recursive = false, 9125 bool DefinitionRequired = false, 9126 bool AtEndOfTU = false); 9127 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation( 9128 VarTemplateDecl *VarTemplate, VarDecl *FromVar, 9129 const TemplateArgumentList &TemplateArgList, 9130 const TemplateArgumentListInfo &TemplateArgsInfo, 9131 SmallVectorImpl<TemplateArgument> &Converted, 9132 SourceLocation PointOfInstantiation, void *InsertPos, 9133 LateInstantiatedAttrVec *LateAttrs = nullptr, 9134 LocalInstantiationScope *StartingScope = nullptr); 9135 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl( 9136 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, 9137 const MultiLevelTemplateArgumentList &TemplateArgs); 9138 void 9139 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, 9140 const MultiLevelTemplateArgumentList &TemplateArgs, 9141 LateInstantiatedAttrVec *LateAttrs, 9142 DeclContext *Owner, 9143 LocalInstantiationScope *StartingScope, 9144 bool InstantiatingVarTemplate = false, 9145 VarTemplateSpecializationDecl *PrevVTSD = nullptr); 9146 9147 VarDecl *getVarTemplateSpecialization( 9148 VarTemplateDecl *VarTempl, const TemplateArgumentListInfo *TemplateArgs, 9149 const DeclarationNameInfo &MemberNameInfo, SourceLocation TemplateKWLoc); 9150 9151 void InstantiateVariableInitializer( 9152 VarDecl *Var, VarDecl *OldVar, 9153 const MultiLevelTemplateArgumentList &TemplateArgs); 9154 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, 9155 VarDecl *Var, bool Recursive = false, 9156 bool DefinitionRequired = false, 9157 bool AtEndOfTU = false); 9158 9159 void InstantiateMemInitializers(CXXConstructorDecl *New, 9160 const CXXConstructorDecl *Tmpl, 9161 const MultiLevelTemplateArgumentList &TemplateArgs); 9162 9163 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 9164 const MultiLevelTemplateArgumentList &TemplateArgs, 9165 bool FindingInstantiatedContext = false); 9166 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, 9167 const MultiLevelTemplateArgumentList &TemplateArgs); 9168 9169 // Objective-C declarations. 9170 enum ObjCContainerKind { 9171 OCK_None = -1, 9172 OCK_Interface = 0, 9173 OCK_Protocol, 9174 OCK_Category, 9175 OCK_ClassExtension, 9176 OCK_Implementation, 9177 OCK_CategoryImplementation 9178 }; 9179 ObjCContainerKind getObjCContainerKind() const; 9180 9181 DeclResult actOnObjCTypeParam(Scope *S, 9182 ObjCTypeParamVariance variance, 9183 SourceLocation varianceLoc, 9184 unsigned index, 9185 IdentifierInfo *paramName, 9186 SourceLocation paramLoc, 9187 SourceLocation colonLoc, 9188 ParsedType typeBound); 9189 9190 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc, 9191 ArrayRef<Decl *> typeParams, 9192 SourceLocation rAngleLoc); 9193 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList); 9194 9195 Decl *ActOnStartClassInterface( 9196 Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, 9197 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, 9198 IdentifierInfo *SuperName, SourceLocation SuperLoc, 9199 ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange, 9200 Decl *const *ProtoRefs, unsigned NumProtoRefs, 9201 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, 9202 const ParsedAttributesView &AttrList); 9203 9204 void ActOnSuperClassOfClassInterface(Scope *S, 9205 SourceLocation AtInterfaceLoc, 9206 ObjCInterfaceDecl *IDecl, 9207 IdentifierInfo *ClassName, 9208 SourceLocation ClassLoc, 9209 IdentifierInfo *SuperName, 9210 SourceLocation SuperLoc, 9211 ArrayRef<ParsedType> SuperTypeArgs, 9212 SourceRange SuperTypeArgsRange); 9213 9214 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, 9215 SmallVectorImpl<SourceLocation> &ProtocolLocs, 9216 IdentifierInfo *SuperName, 9217 SourceLocation SuperLoc); 9218 9219 Decl *ActOnCompatibilityAlias( 9220 SourceLocation AtCompatibilityAliasLoc, 9221 IdentifierInfo *AliasName, SourceLocation AliasLocation, 9222 IdentifierInfo *ClassName, SourceLocation ClassLocation); 9223 9224 bool CheckForwardProtocolDeclarationForCircularDependency( 9225 IdentifierInfo *PName, 9226 SourceLocation &PLoc, SourceLocation PrevLoc, 9227 const ObjCList<ObjCProtocolDecl> &PList); 9228 9229 Decl *ActOnStartProtocolInterface( 9230 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName, 9231 SourceLocation ProtocolLoc, Decl *const *ProtoRefNames, 9232 unsigned NumProtoRefs, const SourceLocation *ProtoLocs, 9233 SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); 9234 9235 Decl *ActOnStartCategoryInterface( 9236 SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, 9237 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, 9238 IdentifierInfo *CategoryName, SourceLocation CategoryLoc, 9239 Decl *const *ProtoRefs, unsigned NumProtoRefs, 9240 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, 9241 const ParsedAttributesView &AttrList); 9242 9243 Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc, 9244 IdentifierInfo *ClassName, 9245 SourceLocation ClassLoc, 9246 IdentifierInfo *SuperClassname, 9247 SourceLocation SuperClassLoc, 9248 const ParsedAttributesView &AttrList); 9249 9250 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, 9251 IdentifierInfo *ClassName, 9252 SourceLocation ClassLoc, 9253 IdentifierInfo *CatName, 9254 SourceLocation CatLoc, 9255 const ParsedAttributesView &AttrList); 9256 9257 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, 9258 ArrayRef<Decl *> Decls); 9259 9260 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, 9261 IdentifierInfo **IdentList, 9262 SourceLocation *IdentLocs, 9263 ArrayRef<ObjCTypeParamList *> TypeParamLists, 9264 unsigned NumElts); 9265 9266 DeclGroupPtrTy 9267 ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, 9268 ArrayRef<IdentifierLocPair> IdentList, 9269 const ParsedAttributesView &attrList); 9270 9271 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer, 9272 ArrayRef<IdentifierLocPair> ProtocolId, 9273 SmallVectorImpl<Decl *> &Protocols); 9274 9275 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId, 9276 SourceLocation ProtocolLoc, 9277 IdentifierInfo *TypeArgId, 9278 SourceLocation TypeArgLoc, 9279 bool SelectProtocolFirst = false); 9280 9281 /// Given a list of identifiers (and their locations), resolve the 9282 /// names to either Objective-C protocol qualifiers or type 9283 /// arguments, as appropriate. 9284 void actOnObjCTypeArgsOrProtocolQualifiers( 9285 Scope *S, 9286 ParsedType baseType, 9287 SourceLocation lAngleLoc, 9288 ArrayRef<IdentifierInfo *> identifiers, 9289 ArrayRef<SourceLocation> identifierLocs, 9290 SourceLocation rAngleLoc, 9291 SourceLocation &typeArgsLAngleLoc, 9292 SmallVectorImpl<ParsedType> &typeArgs, 9293 SourceLocation &typeArgsRAngleLoc, 9294 SourceLocation &protocolLAngleLoc, 9295 SmallVectorImpl<Decl *> &protocols, 9296 SourceLocation &protocolRAngleLoc, 9297 bool warnOnIncompleteProtocols); 9298 9299 /// Build a an Objective-C protocol-qualified 'id' type where no 9300 /// base type was specified. 9301 TypeResult actOnObjCProtocolQualifierType( 9302 SourceLocation lAngleLoc, 9303 ArrayRef<Decl *> protocols, 9304 ArrayRef<SourceLocation> protocolLocs, 9305 SourceLocation rAngleLoc); 9306 9307 /// Build a specialized and/or protocol-qualified Objective-C type. 9308 TypeResult actOnObjCTypeArgsAndProtocolQualifiers( 9309 Scope *S, 9310 SourceLocation Loc, 9311 ParsedType BaseType, 9312 SourceLocation TypeArgsLAngleLoc, 9313 ArrayRef<ParsedType> TypeArgs, 9314 SourceLocation TypeArgsRAngleLoc, 9315 SourceLocation ProtocolLAngleLoc, 9316 ArrayRef<Decl *> Protocols, 9317 ArrayRef<SourceLocation> ProtocolLocs, 9318 SourceLocation ProtocolRAngleLoc); 9319 9320 /// Build an Objective-C type parameter type. 9321 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, 9322 SourceLocation ProtocolLAngleLoc, 9323 ArrayRef<ObjCProtocolDecl *> Protocols, 9324 ArrayRef<SourceLocation> ProtocolLocs, 9325 SourceLocation ProtocolRAngleLoc, 9326 bool FailOnError = false); 9327 9328 /// Build an Objective-C object pointer type. 9329 QualType BuildObjCObjectType(QualType BaseType, 9330 SourceLocation Loc, 9331 SourceLocation TypeArgsLAngleLoc, 9332 ArrayRef<TypeSourceInfo *> TypeArgs, 9333 SourceLocation TypeArgsRAngleLoc, 9334 SourceLocation ProtocolLAngleLoc, 9335 ArrayRef<ObjCProtocolDecl *> Protocols, 9336 ArrayRef<SourceLocation> ProtocolLocs, 9337 SourceLocation ProtocolRAngleLoc, 9338 bool FailOnError = false); 9339 9340 /// Ensure attributes are consistent with type. 9341 /// \param [in, out] Attributes The attributes to check; they will 9342 /// be modified to be consistent with \p PropertyTy. 9343 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, 9344 SourceLocation Loc, 9345 unsigned &Attributes, 9346 bool propertyInPrimaryClass); 9347 9348 /// Process the specified property declaration and create decls for the 9349 /// setters and getters as needed. 9350 /// \param property The property declaration being processed 9351 void ProcessPropertyDecl(ObjCPropertyDecl *property); 9352 9353 9354 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, 9355 ObjCPropertyDecl *SuperProperty, 9356 const IdentifierInfo *Name, 9357 bool OverridingProtocolProperty); 9358 9359 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, 9360 ObjCInterfaceDecl *ID); 9361 9362 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, 9363 ArrayRef<Decl *> allMethods = None, 9364 ArrayRef<DeclGroupPtrTy> allTUVars = None); 9365 9366 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, 9367 SourceLocation LParenLoc, 9368 FieldDeclarator &FD, ObjCDeclSpec &ODS, 9369 Selector GetterSel, Selector SetterSel, 9370 tok::ObjCKeywordKind MethodImplKind, 9371 DeclContext *lexicalDC = nullptr); 9372 9373 Decl *ActOnPropertyImplDecl(Scope *S, 9374 SourceLocation AtLoc, 9375 SourceLocation PropertyLoc, 9376 bool ImplKind, 9377 IdentifierInfo *PropertyId, 9378 IdentifierInfo *PropertyIvar, 9379 SourceLocation PropertyIvarLoc, 9380 ObjCPropertyQueryKind QueryKind); 9381 9382 enum ObjCSpecialMethodKind { 9383 OSMK_None, 9384 OSMK_Alloc, 9385 OSMK_New, 9386 OSMK_Copy, 9387 OSMK_RetainingInit, 9388 OSMK_NonRetainingInit 9389 }; 9390 9391 struct ObjCArgInfo { 9392 IdentifierInfo *Name; 9393 SourceLocation NameLoc; 9394 // The Type is null if no type was specified, and the DeclSpec is invalid 9395 // in this case. 9396 ParsedType Type; 9397 ObjCDeclSpec DeclSpec; 9398 9399 /// ArgAttrs - Attribute list for this argument. 9400 ParsedAttributesView ArgAttrs; 9401 }; 9402 9403 Decl *ActOnMethodDeclaration( 9404 Scope *S, 9405 SourceLocation BeginLoc, // location of the + or -. 9406 SourceLocation EndLoc, // location of the ; or {. 9407 tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType, 9408 ArrayRef<SourceLocation> SelectorLocs, Selector Sel, 9409 // optional arguments. The number of types/arguments is obtained 9410 // from the Sel.getNumArgs(). 9411 ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo, 9412 unsigned CNumArgs, // c-style args 9413 const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind, 9414 bool isVariadic, bool MethodDefinition); 9415 9416 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, 9417 const ObjCObjectPointerType *OPT, 9418 bool IsInstance); 9419 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, 9420 bool IsInstance); 9421 9422 bool CheckARCMethodDecl(ObjCMethodDecl *method); 9423 bool inferObjCARCLifetime(ValueDecl *decl); 9424 9425 void deduceOpenCLAddressSpace(ValueDecl *decl); 9426 9427 ExprResult 9428 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, 9429 Expr *BaseExpr, 9430 SourceLocation OpLoc, 9431 DeclarationName MemberName, 9432 SourceLocation MemberLoc, 9433 SourceLocation SuperLoc, QualType SuperType, 9434 bool Super); 9435 9436 ExprResult 9437 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, 9438 IdentifierInfo &propertyName, 9439 SourceLocation receiverNameLoc, 9440 SourceLocation propertyNameLoc); 9441 9442 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); 9443 9444 /// Describes the kind of message expression indicated by a message 9445 /// send that starts with an identifier. 9446 enum ObjCMessageKind { 9447 /// The message is sent to 'super'. 9448 ObjCSuperMessage, 9449 /// The message is an instance message. 9450 ObjCInstanceMessage, 9451 /// The message is a class message, and the identifier is a type 9452 /// name. 9453 ObjCClassMessage 9454 }; 9455 9456 ObjCMessageKind getObjCMessageKind(Scope *S, 9457 IdentifierInfo *Name, 9458 SourceLocation NameLoc, 9459 bool IsSuper, 9460 bool HasTrailingDot, 9461 ParsedType &ReceiverType); 9462 9463 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, 9464 Selector Sel, 9465 SourceLocation LBracLoc, 9466 ArrayRef<SourceLocation> SelectorLocs, 9467 SourceLocation RBracLoc, 9468 MultiExprArg Args); 9469 9470 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, 9471 QualType ReceiverType, 9472 SourceLocation SuperLoc, 9473 Selector Sel, 9474 ObjCMethodDecl *Method, 9475 SourceLocation LBracLoc, 9476 ArrayRef<SourceLocation> SelectorLocs, 9477 SourceLocation RBracLoc, 9478 MultiExprArg Args, 9479 bool isImplicit = false); 9480 9481 ExprResult BuildClassMessageImplicit(QualType ReceiverType, 9482 bool isSuperReceiver, 9483 SourceLocation Loc, 9484 Selector Sel, 9485 ObjCMethodDecl *Method, 9486 MultiExprArg Args); 9487 9488 ExprResult ActOnClassMessage(Scope *S, 9489 ParsedType Receiver, 9490 Selector Sel, 9491 SourceLocation LBracLoc, 9492 ArrayRef<SourceLocation> SelectorLocs, 9493 SourceLocation RBracLoc, 9494 MultiExprArg Args); 9495 9496 ExprResult BuildInstanceMessage(Expr *Receiver, 9497 QualType ReceiverType, 9498 SourceLocation SuperLoc, 9499 Selector Sel, 9500 ObjCMethodDecl *Method, 9501 SourceLocation LBracLoc, 9502 ArrayRef<SourceLocation> SelectorLocs, 9503 SourceLocation RBracLoc, 9504 MultiExprArg Args, 9505 bool isImplicit = false); 9506 9507 ExprResult BuildInstanceMessageImplicit(Expr *Receiver, 9508 QualType ReceiverType, 9509 SourceLocation Loc, 9510 Selector Sel, 9511 ObjCMethodDecl *Method, 9512 MultiExprArg Args); 9513 9514 ExprResult ActOnInstanceMessage(Scope *S, 9515 Expr *Receiver, 9516 Selector Sel, 9517 SourceLocation LBracLoc, 9518 ArrayRef<SourceLocation> SelectorLocs, 9519 SourceLocation RBracLoc, 9520 MultiExprArg Args); 9521 9522 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, 9523 ObjCBridgeCastKind Kind, 9524 SourceLocation BridgeKeywordLoc, 9525 TypeSourceInfo *TSInfo, 9526 Expr *SubExpr); 9527 9528 ExprResult ActOnObjCBridgedCast(Scope *S, 9529 SourceLocation LParenLoc, 9530 ObjCBridgeCastKind Kind, 9531 SourceLocation BridgeKeywordLoc, 9532 ParsedType Type, 9533 SourceLocation RParenLoc, 9534 Expr *SubExpr); 9535 9536 ExprResult BuildCheriToOrFromCap(SourceLocation LParenLoc, bool IsToCap, 9537 TypeSourceInfo *TSInfo, 9538 SourceLocation RParenLoc, Expr *SubExpr); 9539 9540 ExprResult BuildCheriOffsetOrAddress(SourceLocation LParenLoc, 9541 bool IsOffsetCast, 9542 TypeSourceInfo *TSInfo, 9543 SourceLocation RParenLoc, Expr *SubExpr); 9544 9545 ExprResult ActOnCheriCast(Scope *S, SourceLocation LParenLoc, 9546 tok::TokenKind Kind, SourceLocation KeywordLoc, 9547 ParsedType Type, SourceLocation RParenLoc, 9548 Expr *SubExpr); 9549 9550 bool CheckCHERIAssignCompatible(QualType LHS, QualType RHS, Expr *&RHSExpr, 9551 bool InsertBitCast = true); 9552 9553 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr); 9554 9555 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr); 9556 9557 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, 9558 CastKind &Kind); 9559 9560 bool checkObjCBridgeRelatedComponents(SourceLocation Loc, 9561 QualType DestType, QualType SrcType, 9562 ObjCInterfaceDecl *&RelatedClass, 9563 ObjCMethodDecl *&ClassMethod, 9564 ObjCMethodDecl *&InstanceMethod, 9565 TypedefNameDecl *&TDNDecl, 9566 bool CfToNs, bool Diagnose = true); 9567 9568 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, 9569 QualType DestType, QualType SrcType, 9570 Expr *&SrcExpr, bool Diagnose = true); 9571 9572 bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr, 9573 bool Diagnose = true); 9574 9575 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); 9576 9577 /// Check whether the given new method is a valid override of the 9578 /// given overridden method, and set any properties that should be inherited. 9579 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, 9580 const ObjCMethodDecl *Overridden); 9581 9582 /// Describes the compatibility of a result type with its method. 9583 enum ResultTypeCompatibilityKind { 9584 RTC_Compatible, 9585 RTC_Incompatible, 9586 RTC_Unknown 9587 }; 9588 9589 void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method, 9590 ObjCMethodDecl *overridden); 9591 9592 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, 9593 ObjCInterfaceDecl *CurrentClass, 9594 ResultTypeCompatibilityKind RTC); 9595 9596 enum PragmaOptionsAlignKind { 9597 POAK_Native, // #pragma options align=native 9598 POAK_Natural, // #pragma options align=natural 9599 POAK_Packed, // #pragma options align=packed 9600 POAK_Power, // #pragma options align=power 9601 POAK_Mac68k, // #pragma options align=mac68k 9602 POAK_Reset // #pragma options align=reset 9603 }; 9604 9605 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section 9606 void ActOnPragmaClangSection(SourceLocation PragmaLoc, 9607 PragmaClangSectionAction Action, 9608 PragmaClangSectionKind SecKind, StringRef SecName); 9609 9610 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. 9611 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, 9612 SourceLocation PragmaLoc); 9613 9614 PointerInterpretationKind PointerInterpretation; 9615 llvm::SmallVector<PointerInterpretationKind, 4> PointerInterpretationStack; 9616 9617 /// ActOnPragmaPack - Called on well formed \#pragma pack(...). 9618 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, 9619 StringRef SlotLabel, Expr *Alignment); 9620 9621 void ActOnPragmaPointerInterpretation(PointerInterpretationKind K); ActOnPragmaPointerInterpretationPush()9622 void ActOnPragmaPointerInterpretationPush() { 9623 PointerInterpretationStack.push_back(PointerInterpretation); 9624 } ActOnPragmaPointerInterpretationPop()9625 void ActOnPragmaPointerInterpretationPop() { 9626 PointerInterpretation = PointerInterpretationStack.back(); 9627 PointerInterpretationStack.pop_back(); 9628 } 9629 9630 enum class PragmaPackDiagnoseKind { 9631 NonDefaultStateAtInclude, 9632 ChangedStateAtExit 9633 }; 9634 9635 void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind, 9636 SourceLocation IncludeLoc); 9637 void DiagnoseUnterminatedPragmaPack(); 9638 9639 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. 9640 void ActOnPragmaMSStruct(PragmaMSStructKind Kind); 9641 9642 /// ActOnPragmaMSComment - Called on well formed 9643 /// \#pragma comment(kind, "arg"). 9644 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind, 9645 StringRef Arg); 9646 9647 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma 9648 /// pointers_to_members(representation method[, general purpose 9649 /// representation]). 9650 void ActOnPragmaMSPointersToMembers( 9651 LangOptions::PragmaMSPointersToMembersKind Kind, 9652 SourceLocation PragmaLoc); 9653 9654 /// Called on well formed \#pragma vtordisp(). 9655 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, 9656 SourceLocation PragmaLoc, 9657 MSVtorDispMode Value); 9658 9659 enum PragmaSectionKind { 9660 PSK_DataSeg, 9661 PSK_BSSSeg, 9662 PSK_ConstSeg, 9663 PSK_CodeSeg, 9664 }; 9665 9666 bool UnifySection(StringRef SectionName, 9667 int SectionFlags, 9668 DeclaratorDecl *TheDecl); 9669 bool UnifySection(StringRef SectionName, 9670 int SectionFlags, 9671 SourceLocation PragmaSectionLocation); 9672 9673 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg. 9674 void ActOnPragmaMSSeg(SourceLocation PragmaLocation, 9675 PragmaMsStackAction Action, 9676 llvm::StringRef StackSlotLabel, 9677 StringLiteral *SegmentName, 9678 llvm::StringRef PragmaName); 9679 9680 /// Called on well formed \#pragma section(). 9681 void ActOnPragmaMSSection(SourceLocation PragmaLocation, 9682 int SectionFlags, StringLiteral *SegmentName); 9683 9684 /// Called on well-formed \#pragma init_seg(). 9685 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, 9686 StringLiteral *SegmentName); 9687 9688 /// Called on #pragma clang __debug dump II 9689 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II); 9690 9691 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch 9692 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, 9693 StringRef Value); 9694 9695 /// Are precise floating point semantics currently enabled? isPreciseFPEnabled()9696 bool isPreciseFPEnabled() { 9697 return !CurFPFeatures.getAllowFPReassociate() && 9698 !CurFPFeatures.getNoSignedZero() && 9699 !CurFPFeatures.getAllowReciprocal() && 9700 !CurFPFeatures.getAllowApproxFunc(); 9701 } 9702 9703 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control 9704 void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action, 9705 PragmaFloatControlKind Value); 9706 9707 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. 9708 void ActOnPragmaUnused(const Token &Identifier, 9709 Scope *curScope, 9710 SourceLocation PragmaLoc); 9711 9712 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . 9713 void ActOnPragmaVisibility(const IdentifierInfo* VisType, 9714 SourceLocation PragmaLoc); 9715 9716 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, 9717 SourceLocation Loc); 9718 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); 9719 9720 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. 9721 void ActOnPragmaWeakID(IdentifierInfo* WeakName, 9722 SourceLocation PragmaLoc, 9723 SourceLocation WeakNameLoc); 9724 9725 /// ActOnPragmaRedefineExtname - Called on well formed 9726 /// \#pragma redefine_extname oldname newname. 9727 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, 9728 IdentifierInfo* AliasName, 9729 SourceLocation PragmaLoc, 9730 SourceLocation WeakNameLoc, 9731 SourceLocation AliasNameLoc); 9732 9733 void ActOnPragmaOpaque(IdentifierInfo* TypeName, 9734 IdentifierInfo* KeyName, 9735 SourceLocation PragmaLoc, 9736 SourceLocation TypeLoc, 9737 SourceLocation KeyLoc); 9738 9739 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. 9740 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, 9741 IdentifierInfo* AliasName, 9742 SourceLocation PragmaLoc, 9743 SourceLocation WeakNameLoc, 9744 SourceLocation AliasNameLoc); 9745 9746 /// ActOnPragmaFPContract - Called on well formed 9747 /// \#pragma {STDC,OPENCL} FP_CONTRACT and 9748 /// \#pragma clang fp contract 9749 void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC); 9750 9751 /// Called on well formed 9752 /// \#pragma clang fp reassociate 9753 void ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled); 9754 9755 /// ActOnPragmaFenvAccess - Called on well formed 9756 /// \#pragma STDC FENV_ACCESS 9757 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled); 9758 9759 /// Called to set rounding mode for floating point operations. 9760 void setRoundingMode(SourceLocation Loc, llvm::RoundingMode); 9761 9762 /// Called to set exception behavior for floating point operations. 9763 void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind); 9764 9765 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to 9766 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. 9767 void AddAlignmentAttributesForRecord(RecordDecl *RD); 9768 9769 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. 9770 void AddMsStructLayoutForRecord(RecordDecl *RD); 9771 9772 /// FreePackedContext - Deallocate and null out PackContext. 9773 void FreePackedContext(); 9774 9775 /// PushNamespaceVisibilityAttr - Note that we've entered a 9776 /// namespace with a visibility attribute. 9777 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, 9778 SourceLocation Loc); 9779 9780 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, 9781 /// add an appropriate visibility attribute. 9782 void AddPushedVisibilityAttribute(Decl *RD); 9783 9784 /// PopPragmaVisibility - Pop the top element of the visibility stack; used 9785 /// for '\#pragma GCC visibility' and visibility attributes on namespaces. 9786 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); 9787 9788 /// FreeVisContext - Deallocate and null out VisContext. 9789 void FreeVisContext(); 9790 9791 /// AddCFAuditedAttribute - Check whether we're currently within 9792 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding 9793 /// the appropriate attribute. 9794 void AddCFAuditedAttribute(Decl *D); 9795 9796 void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, 9797 SourceLocation PragmaLoc, 9798 attr::ParsedSubjectMatchRuleSet Rules); 9799 void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc, 9800 const IdentifierInfo *Namespace); 9801 9802 /// Called on well-formed '\#pragma clang attribute pop'. 9803 void ActOnPragmaAttributePop(SourceLocation PragmaLoc, 9804 const IdentifierInfo *Namespace); 9805 9806 /// Adds the attributes that have been specified using the 9807 /// '\#pragma clang attribute push' directives to the given declaration. 9808 void AddPragmaAttributes(Scope *S, Decl *D); 9809 9810 void DiagnoseUnterminatedPragmaAttribute(); 9811 9812 /// Called on well formed \#pragma clang optimize. 9813 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); 9814 9815 /// Get the location for the currently active "\#pragma clang optimize 9816 /// off". If this location is invalid, then the state of the pragma is "on". getOptimizeOffPragmaLocation()9817 SourceLocation getOptimizeOffPragmaLocation() const { 9818 return OptimizeOffPragmaLocation; 9819 } 9820 9821 /// Only called on function definitions; if there is a pragma in scope 9822 /// with the effect of a range-based optnone, consider marking the function 9823 /// with attribute optnone. 9824 void AddRangeBasedOptnone(FunctionDecl *FD); 9825 9826 /// Adds the 'optnone' attribute to the function declaration if there 9827 /// are no conflicts; Loc represents the location causing the 'optnone' 9828 /// attribute to be added (usually because of a pragma). 9829 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc); 9830 9831 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. 9832 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, 9833 bool IsPackExpansion); 9834 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T, 9835 bool IsPackExpansion); 9836 9837 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular 9838 /// declaration. 9839 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, 9840 Expr *OE); 9841 9842 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular 9843 /// declaration. 9844 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, 9845 Expr *ParamExpr); 9846 9847 /// AddAlignValueAttr - Adds an align_value attribute to a particular 9848 /// declaration. 9849 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); 9850 9851 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular 9852 /// declaration. 9853 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, 9854 Expr *MaxThreads, Expr *MinBlocks); 9855 9856 /// AddModeAttr - Adds a mode attribute to a particular declaration. 9857 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name, 9858 bool InInstantiation = false); 9859 9860 void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI, 9861 ParameterABI ABI); 9862 9863 enum class RetainOwnershipKind {NS, CF, OS}; 9864 void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI, 9865 RetainOwnershipKind K, bool IsTemplateInstantiation); 9866 9867 /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size 9868 /// attribute to a particular declaration. 9869 void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, 9870 Expr *Min, Expr *Max); 9871 9872 /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a 9873 /// particular declaration. 9874 void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, 9875 Expr *Min, Expr *Max); 9876 9877 bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type); 9878 9879 //===--------------------------------------------------------------------===// 9880 // C++ Coroutines TS 9881 // 9882 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, 9883 StringRef Keyword); 9884 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E); 9885 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E); 9886 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E); 9887 9888 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, 9889 bool IsImplicit = false); 9890 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, 9891 UnresolvedLookupExpr* Lookup); 9892 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E); 9893 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, 9894 bool IsImplicit = false); 9895 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs); 9896 bool buildCoroutineParameterMoves(SourceLocation Loc); 9897 VarDecl *buildCoroutinePromise(SourceLocation Loc); 9898 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body); 9899 ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc, 9900 SourceLocation FuncLoc); 9901 /// Check that the expression co_await promise.final_suspend() shall not be 9902 /// potentially-throwing. 9903 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend); 9904 9905 //===--------------------------------------------------------------------===// 9906 // OpenCL extensions. 9907 // 9908 private: 9909 std::string CurrOpenCLExtension; 9910 /// Extensions required by an OpenCL type. 9911 llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap; 9912 /// Extensions required by an OpenCL declaration. 9913 llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap; 9914 public: getCurrentOpenCLExtension()9915 llvm::StringRef getCurrentOpenCLExtension() const { 9916 return CurrOpenCLExtension; 9917 } 9918 9919 /// Check if a function declaration \p FD associates with any 9920 /// extensions present in OpenCLDeclExtMap and if so return the 9921 /// extension(s) name(s). 9922 std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD); 9923 9924 /// Check if a function type \p FT associates with any 9925 /// extensions present in OpenCLTypeExtMap and if so return the 9926 /// extension(s) name(s). 9927 std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT); 9928 9929 /// Find an extension in an appropriate extension map and return its name 9930 template<typename T, typename MapT> 9931 std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map); 9932 setCurrentOpenCLExtension(llvm::StringRef Ext)9933 void setCurrentOpenCLExtension(llvm::StringRef Ext) { 9934 CurrOpenCLExtension = std::string(Ext); 9935 } 9936 9937 /// Set OpenCL extensions for a type which can only be used when these 9938 /// OpenCL extensions are enabled. If \p Exts is empty, do nothing. 9939 /// \param Exts A space separated list of OpenCL extensions. 9940 void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts); 9941 9942 /// Set OpenCL extensions for a declaration which can only be 9943 /// used when these OpenCL extensions are enabled. If \p Exts is empty, do 9944 /// nothing. 9945 /// \param Exts A space separated list of OpenCL extensions. 9946 void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts); 9947 9948 /// Set current OpenCL extensions for a type which can only be used 9949 /// when these OpenCL extensions are enabled. If current OpenCL extension is 9950 /// empty, do nothing. 9951 void setCurrentOpenCLExtensionForType(QualType T); 9952 9953 /// Set current OpenCL extensions for a declaration which 9954 /// can only be used when these OpenCL extensions are enabled. If current 9955 /// OpenCL extension is empty, do nothing. 9956 void setCurrentOpenCLExtensionForDecl(Decl *FD); 9957 9958 bool isOpenCLDisabledDecl(Decl *FD); 9959 9960 /// Check if type \p T corresponding to declaration specifier \p DS 9961 /// is disabled due to required OpenCL extensions being disabled. If so, 9962 /// emit diagnostics. 9963 /// \return true if type is disabled. 9964 bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T); 9965 9966 /// Check if declaration \p D used by expression \p E 9967 /// is disabled due to required OpenCL extensions being disabled. If so, 9968 /// emit diagnostics. 9969 /// \return true if type is disabled. 9970 bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E); 9971 9972 //===--------------------------------------------------------------------===// 9973 // OpenMP directives and clauses. 9974 // 9975 private: 9976 void *VarDataSharingAttributesStack; 9977 /// Number of nested '#pragma omp declare target' directives. 9978 unsigned DeclareTargetNestingLevel = 0; 9979 /// Initialization of data-sharing attributes stack. 9980 void InitDataSharingAttributesStack(); 9981 void DestroyDataSharingAttributesStack(); 9982 ExprResult 9983 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind, 9984 bool StrictlyPositive = true); 9985 /// Returns OpenMP nesting level for current directive. 9986 unsigned getOpenMPNestingLevel() const; 9987 9988 /// Adjusts the function scopes index for the target-based regions. 9989 void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, 9990 unsigned Level) const; 9991 9992 /// Returns the number of scopes associated with the construct on the given 9993 /// OpenMP level. 9994 int getNumberOfConstructScopes(unsigned Level) const; 9995 9996 /// Push new OpenMP function region for non-capturing function. 9997 void pushOpenMPFunctionRegion(); 9998 9999 /// Pop OpenMP function region for non-capturing function. 10000 void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI); 10001 10002 /// Checks if a type or a declaration is disabled due to the owning extension 10003 /// being disabled, and emits diagnostic messages if it is disabled. 10004 /// \param D type or declaration to be checked. 10005 /// \param DiagLoc source location for the diagnostic message. 10006 /// \param DiagInfo information to be emitted for the diagnostic message. 10007 /// \param SrcRange source range of the declaration. 10008 /// \param Map maps type or declaration to the extensions. 10009 /// \param Selector selects diagnostic message: 0 for type and 1 for 10010 /// declaration. 10011 /// \return true if the type or declaration is disabled. 10012 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT> 10013 bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo, 10014 MapT &Map, unsigned Selector = 0, 10015 SourceRange SrcRange = SourceRange()); 10016 10017 /// Helper to keep information about the current `omp begin/end declare 10018 /// variant` nesting. 10019 struct OMPDeclareVariantScope { 10020 /// The associated OpenMP context selector. 10021 OMPTraitInfo *TI; 10022 10023 /// The associated OpenMP context selector mangling. 10024 std::string NameSuffix; 10025 10026 OMPDeclareVariantScope(OMPTraitInfo &TI); 10027 }; 10028 10029 /// The current `omp begin/end declare variant` scopes. 10030 SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes; 10031 10032 /// The declarator \p D defines a function in the scope \p S which is nested 10033 /// in an `omp begin/end declare variant` scope. In this method we create a 10034 /// declaration for \p D and rename \p D according to the OpenMP context 10035 /// selector of the surrounding scope. 10036 FunctionDecl * 10037 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(Scope *S, 10038 Declarator &D); 10039 10040 /// Register \p FD as specialization of \p BaseFD in the current `omp 10041 /// begin/end declare variant` scope. 10042 void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( 10043 FunctionDecl *FD, FunctionDecl *BaseFD); 10044 10045 public: 10046 10047 /// Can we exit a scope at the moment. isInOpenMPDeclareVariantScope()10048 bool isInOpenMPDeclareVariantScope() { 10049 return !OMPDeclareVariantScopes.empty(); 10050 } 10051 10052 /// Given the potential call expression \p Call, determine if there is a 10053 /// specialization via the OpenMP declare variant mechanism available. If 10054 /// there is, return the specialized call expression, otherwise return the 10055 /// original \p Call. 10056 ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope, 10057 SourceLocation LParenLoc, MultiExprArg ArgExprs, 10058 SourceLocation RParenLoc, Expr *ExecConfig); 10059 10060 /// Handle a `omp begin declare variant`. 10061 void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI); 10062 10063 /// Handle a `omp end declare variant`. 10064 void ActOnOpenMPEndDeclareVariant(); 10065 10066 /// Checks if the variant/multiversion functions are compatible. 10067 bool areMultiversionVariantFunctionsCompatible( 10068 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10069 const PartialDiagnostic &NoProtoDiagID, 10070 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10071 const PartialDiagnosticAt &NoSupportDiagIDAt, 10072 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10073 bool ConstexprSupported, bool CLinkageMayDiffer); 10074 10075 /// Function tries to capture lambda's captured variables in the OpenMP region 10076 /// before the original lambda is captured. 10077 void tryCaptureOpenMPLambdas(ValueDecl *V); 10078 10079 /// Return true if the provided declaration \a VD should be captured by 10080 /// reference. 10081 /// \param Level Relative level of nested OpenMP construct for that the check 10082 /// is performed. 10083 /// \param OpenMPCaptureLevel Capture level within an OpenMP construct. 10084 bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, 10085 unsigned OpenMPCaptureLevel) const; 10086 10087 /// Check if the specified variable is used in one of the private 10088 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP 10089 /// constructs. 10090 VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false, 10091 unsigned StopAt = 0); 10092 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 10093 ExprObjectKind OK, SourceLocation Loc); 10094 10095 /// If the current region is a loop-based region, mark the start of the loop 10096 /// construct. 10097 void startOpenMPLoop(); 10098 10099 /// If the current region is a range loop-based region, mark the start of the 10100 /// loop construct. 10101 void startOpenMPCXXRangeFor(); 10102 10103 /// Check if the specified variable is used in 'private' clause. 10104 /// \param Level Relative level of nested OpenMP construct for that the check 10105 /// is performed. 10106 OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, 10107 unsigned CapLevel) const; 10108 10109 /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.) 10110 /// for \p FD based on DSA for the provided corresponding captured declaration 10111 /// \p D. 10112 void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level); 10113 10114 /// Check if the specified variable is captured by 'target' directive. 10115 /// \param Level Relative level of nested OpenMP construct for that the check 10116 /// is performed. 10117 bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, 10118 unsigned CaptureLevel) const; 10119 10120 /// Check if the specified global variable must be captured by outer capture 10121 /// regions. 10122 /// \param Level Relative level of nested OpenMP construct for that 10123 /// the check is performed. 10124 bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, 10125 unsigned CaptureLevel) const; 10126 10127 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc, 10128 Expr *Op); 10129 /// Called on start of new data sharing attribute block. 10130 void StartOpenMPDSABlock(OpenMPDirectiveKind K, 10131 const DeclarationNameInfo &DirName, Scope *CurScope, 10132 SourceLocation Loc); 10133 /// Start analysis of clauses. 10134 void StartOpenMPClause(OpenMPClauseKind K); 10135 /// End analysis of clauses. 10136 void EndOpenMPClause(); 10137 /// Called on end of data sharing attribute block. 10138 void EndOpenMPDSABlock(Stmt *CurDirective); 10139 10140 /// Check if the current region is an OpenMP loop region and if it is, 10141 /// mark loop control variable, used in \p Init for loop initialization, as 10142 /// private by default. 10143 /// \param Init First part of the for loop. 10144 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init); 10145 10146 // OpenMP directives and clauses. 10147 /// Called on correct id-expression from the '#pragma omp 10148 /// threadprivate'. 10149 ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec, 10150 const DeclarationNameInfo &Id, 10151 OpenMPDirectiveKind Kind); 10152 /// Called on well-formed '#pragma omp threadprivate'. 10153 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective( 10154 SourceLocation Loc, 10155 ArrayRef<Expr *> VarList); 10156 /// Builds a new OpenMPThreadPrivateDecl and checks its correctness. 10157 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc, 10158 ArrayRef<Expr *> VarList); 10159 /// Called on well-formed '#pragma omp allocate'. 10160 DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc, 10161 ArrayRef<Expr *> VarList, 10162 ArrayRef<OMPClause *> Clauses, 10163 DeclContext *Owner = nullptr); 10164 /// Called on well-formed '#pragma omp requires'. 10165 DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc, 10166 ArrayRef<OMPClause *> ClauseList); 10167 /// Check restrictions on Requires directive 10168 OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc, 10169 ArrayRef<OMPClause *> Clauses); 10170 /// Check if the specified type is allowed to be used in 'omp declare 10171 /// reduction' construct. 10172 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 10173 TypeResult ParsedType); 10174 /// Called on start of '#pragma omp declare reduction'. 10175 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart( 10176 Scope *S, DeclContext *DC, DeclarationName Name, 10177 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 10178 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); 10179 /// Initialize declare reduction construct initializer. 10180 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D); 10181 /// Finish current declare reduction construct initializer. 10182 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner); 10183 /// Initialize declare reduction construct initializer. 10184 /// \return omp_priv variable. 10185 VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D); 10186 /// Finish current declare reduction construct initializer. 10187 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, 10188 VarDecl *OmpPrivParm); 10189 /// Called at the end of '#pragma omp declare reduction'. 10190 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd( 10191 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid); 10192 10193 /// Check variable declaration in 'omp declare mapper' construct. 10194 TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D); 10195 /// Check if the specified type is allowed to be used in 'omp declare 10196 /// mapper' construct. 10197 QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, 10198 TypeResult ParsedType); 10199 /// Called on start of '#pragma omp declare mapper'. 10200 OMPDeclareMapperDecl *ActOnOpenMPDeclareMapperDirectiveStart( 10201 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, 10202 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, 10203 Decl *PrevDeclInScope = nullptr); 10204 /// Build the mapper variable of '#pragma omp declare mapper'. 10205 void ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD, 10206 Scope *S, QualType MapperType, 10207 SourceLocation StartLoc, 10208 DeclarationName VN); 10209 /// Called at the end of '#pragma omp declare mapper'. 10210 DeclGroupPtrTy 10211 ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S, 10212 ArrayRef<OMPClause *> ClauseList); 10213 10214 /// Called on the start of target region i.e. '#pragma omp declare target'. 10215 bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc); 10216 /// Called at the end of target region i.e. '#pragme omp end declare target'. 10217 void ActOnFinishOpenMPDeclareTargetDirective(); 10218 /// Searches for the provided declaration name for OpenMP declare target 10219 /// directive. 10220 NamedDecl * 10221 lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, 10222 const DeclarationNameInfo &Id, 10223 NamedDeclSetType &SameDirectiveDecls); 10224 /// Called on correct id-expression from the '#pragma omp declare target'. 10225 void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc, 10226 OMPDeclareTargetDeclAttr::MapTypeTy MT, 10227 OMPDeclareTargetDeclAttr::DevTypeTy DT); 10228 /// Check declaration inside target region. 10229 void 10230 checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, 10231 SourceLocation IdLoc = SourceLocation()); 10232 /// Finishes analysis of the deferred functions calls that may be declared as 10233 /// host/nohost during device/host compilation. 10234 void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller, 10235 const FunctionDecl *Callee, 10236 SourceLocation Loc); 10237 /// Return true inside OpenMP declare target region. isInOpenMPDeclareTargetContext()10238 bool isInOpenMPDeclareTargetContext() const { 10239 return DeclareTargetNestingLevel > 0; 10240 } 10241 /// Return true inside OpenMP target region. 10242 bool isInOpenMPTargetExecutionDirective() const; 10243 10244 /// Return the number of captured regions created for an OpenMP directive. 10245 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind); 10246 10247 /// Initialization of captured region for OpenMP region. 10248 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope); 10249 /// End of OpenMP region. 10250 /// 10251 /// \param S Statement associated with the current OpenMP region. 10252 /// \param Clauses List of clauses for the current OpenMP region. 10253 /// 10254 /// \returns Statement for finished OpenMP region. 10255 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses); 10256 StmtResult ActOnOpenMPExecutableDirective( 10257 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 10258 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 10259 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); 10260 /// Called on well-formed '\#pragma omp parallel' after parsing 10261 /// of the associated statement. 10262 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 10263 Stmt *AStmt, 10264 SourceLocation StartLoc, 10265 SourceLocation EndLoc); 10266 using VarsWithInheritedDSAType = 10267 llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>; 10268 /// Called on well-formed '\#pragma omp simd' after parsing 10269 /// of the associated statement. 10270 StmtResult 10271 ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 10272 SourceLocation StartLoc, SourceLocation EndLoc, 10273 VarsWithInheritedDSAType &VarsWithImplicitDSA); 10274 /// Called on well-formed '\#pragma omp for' after parsing 10275 /// of the associated statement. 10276 StmtResult 10277 ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 10278 SourceLocation StartLoc, SourceLocation EndLoc, 10279 VarsWithInheritedDSAType &VarsWithImplicitDSA); 10280 /// Called on well-formed '\#pragma omp for simd' after parsing 10281 /// of the associated statement. 10282 StmtResult 10283 ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 10284 SourceLocation StartLoc, SourceLocation EndLoc, 10285 VarsWithInheritedDSAType &VarsWithImplicitDSA); 10286 /// Called on well-formed '\#pragma omp sections' after parsing 10287 /// of the associated statement. 10288 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 10289 Stmt *AStmt, SourceLocation StartLoc, 10290 SourceLocation EndLoc); 10291 /// Called on well-formed '\#pragma omp section' after parsing of the 10292 /// associated statement. 10293 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc, 10294 SourceLocation EndLoc); 10295 /// Called on well-formed '\#pragma omp single' after parsing of the 10296 /// associated statement. 10297 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 10298 Stmt *AStmt, SourceLocation StartLoc, 10299 SourceLocation EndLoc); 10300 /// Called on well-formed '\#pragma omp master' after parsing of the 10301 /// associated statement. 10302 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc, 10303 SourceLocation EndLoc); 10304 /// Called on well-formed '\#pragma omp critical' after parsing of the 10305 /// associated statement. 10306 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, 10307 ArrayRef<OMPClause *> Clauses, 10308 Stmt *AStmt, SourceLocation StartLoc, 10309 SourceLocation EndLoc); 10310 /// Called on well-formed '\#pragma omp parallel for' after parsing 10311 /// of the associated statement. 10312 StmtResult ActOnOpenMPParallelForDirective( 10313 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10314 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10315 /// Called on well-formed '\#pragma omp parallel for simd' after 10316 /// parsing of the associated statement. 10317 StmtResult ActOnOpenMPParallelForSimdDirective( 10318 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10319 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10320 /// Called on well-formed '\#pragma omp parallel master' after 10321 /// parsing of the associated statement. 10322 StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses, 10323 Stmt *AStmt, 10324 SourceLocation StartLoc, 10325 SourceLocation EndLoc); 10326 /// Called on well-formed '\#pragma omp parallel sections' after 10327 /// parsing of the associated statement. 10328 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 10329 Stmt *AStmt, 10330 SourceLocation StartLoc, 10331 SourceLocation EndLoc); 10332 /// Called on well-formed '\#pragma omp task' after parsing of the 10333 /// associated statement. 10334 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 10335 Stmt *AStmt, SourceLocation StartLoc, 10336 SourceLocation EndLoc); 10337 /// Called on well-formed '\#pragma omp taskyield'. 10338 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 10339 SourceLocation EndLoc); 10340 /// Called on well-formed '\#pragma omp barrier'. 10341 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 10342 SourceLocation EndLoc); 10343 /// Called on well-formed '\#pragma omp taskwait'. 10344 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 10345 SourceLocation EndLoc); 10346 /// Called on well-formed '\#pragma omp taskgroup'. 10347 StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, 10348 Stmt *AStmt, SourceLocation StartLoc, 10349 SourceLocation EndLoc); 10350 /// Called on well-formed '\#pragma omp flush'. 10351 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 10352 SourceLocation StartLoc, 10353 SourceLocation EndLoc); 10354 /// Called on well-formed '\#pragma omp depobj'. 10355 StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses, 10356 SourceLocation StartLoc, 10357 SourceLocation EndLoc); 10358 /// Called on well-formed '\#pragma omp scan'. 10359 StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses, 10360 SourceLocation StartLoc, 10361 SourceLocation EndLoc); 10362 /// Called on well-formed '\#pragma omp ordered' after parsing of the 10363 /// associated statement. 10364 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 10365 Stmt *AStmt, SourceLocation StartLoc, 10366 SourceLocation EndLoc); 10367 /// Called on well-formed '\#pragma omp atomic' after parsing of the 10368 /// associated statement. 10369 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 10370 Stmt *AStmt, SourceLocation StartLoc, 10371 SourceLocation EndLoc); 10372 /// Called on well-formed '\#pragma omp target' after parsing of the 10373 /// associated statement. 10374 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 10375 Stmt *AStmt, SourceLocation StartLoc, 10376 SourceLocation EndLoc); 10377 /// Called on well-formed '\#pragma omp target data' after parsing of 10378 /// the associated statement. 10379 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 10380 Stmt *AStmt, SourceLocation StartLoc, 10381 SourceLocation EndLoc); 10382 /// Called on well-formed '\#pragma omp target enter data' after 10383 /// parsing of the associated statement. 10384 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 10385 SourceLocation StartLoc, 10386 SourceLocation EndLoc, 10387 Stmt *AStmt); 10388 /// Called on well-formed '\#pragma omp target exit data' after 10389 /// parsing of the associated statement. 10390 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 10391 SourceLocation StartLoc, 10392 SourceLocation EndLoc, 10393 Stmt *AStmt); 10394 /// Called on well-formed '\#pragma omp target parallel' after 10395 /// parsing of the associated statement. 10396 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 10397 Stmt *AStmt, 10398 SourceLocation StartLoc, 10399 SourceLocation EndLoc); 10400 /// Called on well-formed '\#pragma omp target parallel for' after 10401 /// parsing of the associated statement. 10402 StmtResult ActOnOpenMPTargetParallelForDirective( 10403 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10404 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10405 /// Called on well-formed '\#pragma omp teams' after parsing of the 10406 /// associated statement. 10407 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 10408 Stmt *AStmt, SourceLocation StartLoc, 10409 SourceLocation EndLoc); 10410 /// Called on well-formed '\#pragma omp cancellation point'. 10411 StmtResult 10412 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 10413 SourceLocation EndLoc, 10414 OpenMPDirectiveKind CancelRegion); 10415 /// Called on well-formed '\#pragma omp cancel'. 10416 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 10417 SourceLocation StartLoc, 10418 SourceLocation EndLoc, 10419 OpenMPDirectiveKind CancelRegion); 10420 /// Called on well-formed '\#pragma omp taskloop' after parsing of the 10421 /// associated statement. 10422 StmtResult 10423 ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 10424 SourceLocation StartLoc, SourceLocation EndLoc, 10425 VarsWithInheritedDSAType &VarsWithImplicitDSA); 10426 /// Called on well-formed '\#pragma omp taskloop simd' after parsing of 10427 /// the associated statement. 10428 StmtResult ActOnOpenMPTaskLoopSimdDirective( 10429 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10430 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10431 /// Called on well-formed '\#pragma omp master taskloop' after parsing of the 10432 /// associated statement. 10433 StmtResult ActOnOpenMPMasterTaskLoopDirective( 10434 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10435 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10436 /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of 10437 /// the associated statement. 10438 StmtResult ActOnOpenMPMasterTaskLoopSimdDirective( 10439 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10440 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10441 /// Called on well-formed '\#pragma omp parallel master taskloop' after 10442 /// parsing of the associated statement. 10443 StmtResult ActOnOpenMPParallelMasterTaskLoopDirective( 10444 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10445 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10446 /// Called on well-formed '\#pragma omp parallel master taskloop simd' after 10447 /// parsing of the associated statement. 10448 StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective( 10449 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10450 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10451 /// Called on well-formed '\#pragma omp distribute' after parsing 10452 /// of the associated statement. 10453 StmtResult 10454 ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 10455 SourceLocation StartLoc, SourceLocation EndLoc, 10456 VarsWithInheritedDSAType &VarsWithImplicitDSA); 10457 /// Called on well-formed '\#pragma omp target update'. 10458 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 10459 SourceLocation StartLoc, 10460 SourceLocation EndLoc, 10461 Stmt *AStmt); 10462 /// Called on well-formed '\#pragma omp distribute parallel for' after 10463 /// parsing of the associated statement. 10464 StmtResult ActOnOpenMPDistributeParallelForDirective( 10465 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10466 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10467 /// Called on well-formed '\#pragma omp distribute parallel for simd' 10468 /// after parsing of the associated statement. 10469 StmtResult ActOnOpenMPDistributeParallelForSimdDirective( 10470 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10471 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10472 /// Called on well-formed '\#pragma omp distribute simd' after 10473 /// parsing of the associated statement. 10474 StmtResult ActOnOpenMPDistributeSimdDirective( 10475 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10476 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10477 /// Called on well-formed '\#pragma omp target parallel for simd' after 10478 /// parsing of the associated statement. 10479 StmtResult ActOnOpenMPTargetParallelForSimdDirective( 10480 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10481 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10482 /// Called on well-formed '\#pragma omp target simd' after parsing of 10483 /// the associated statement. 10484 StmtResult 10485 ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 10486 SourceLocation StartLoc, SourceLocation EndLoc, 10487 VarsWithInheritedDSAType &VarsWithImplicitDSA); 10488 /// Called on well-formed '\#pragma omp teams distribute' after parsing of 10489 /// the associated statement. 10490 StmtResult ActOnOpenMPTeamsDistributeDirective( 10491 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10492 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10493 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing 10494 /// of the associated statement. 10495 StmtResult ActOnOpenMPTeamsDistributeSimdDirective( 10496 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10497 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10498 /// Called on well-formed '\#pragma omp teams distribute parallel for simd' 10499 /// after parsing of the associated statement. 10500 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective( 10501 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10502 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10503 /// Called on well-formed '\#pragma omp teams distribute parallel for' 10504 /// after parsing of the associated statement. 10505 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective( 10506 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10507 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10508 /// Called on well-formed '\#pragma omp target teams' after parsing of the 10509 /// associated statement. 10510 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 10511 Stmt *AStmt, 10512 SourceLocation StartLoc, 10513 SourceLocation EndLoc); 10514 /// Called on well-formed '\#pragma omp target teams distribute' after parsing 10515 /// of the associated statement. 10516 StmtResult ActOnOpenMPTargetTeamsDistributeDirective( 10517 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10518 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10519 /// Called on well-formed '\#pragma omp target teams distribute parallel for' 10520 /// after parsing of the associated statement. 10521 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective( 10522 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10523 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10524 /// Called on well-formed '\#pragma omp target teams distribute parallel for 10525 /// simd' after parsing of the associated statement. 10526 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 10527 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10528 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10529 /// Called on well-formed '\#pragma omp target teams distribute simd' after 10530 /// parsing of the associated statement. 10531 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective( 10532 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10533 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10534 10535 /// Checks correctness of linear modifiers. 10536 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 10537 SourceLocation LinLoc); 10538 /// Checks that the specified declaration matches requirements for the linear 10539 /// decls. 10540 bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, 10541 OpenMPLinearClauseKind LinKind, QualType Type, 10542 bool IsDeclareSimd = false); 10543 10544 /// Called on well-formed '\#pragma omp declare simd' after parsing of 10545 /// the associated method/function. 10546 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective( 10547 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, 10548 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 10549 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 10550 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR); 10551 10552 /// Checks '\#pragma omp declare variant' variant function and original 10553 /// functions after parsing of the associated method/function. 10554 /// \param DG Function declaration to which declare variant directive is 10555 /// applied to. 10556 /// \param VariantRef Expression that references the variant function, which 10557 /// must be used instead of the original one, specified in \p DG. 10558 /// \param TI The trait info object representing the match clause. 10559 /// \returns None, if the function/variant function are not compatible with 10560 /// the pragma, pair of original function/variant ref expression otherwise. 10561 Optional<std::pair<FunctionDecl *, Expr *>> 10562 checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef, 10563 OMPTraitInfo &TI, SourceRange SR); 10564 10565 /// Called on well-formed '\#pragma omp declare variant' after parsing of 10566 /// the associated method/function. 10567 /// \param FD Function declaration to which declare variant directive is 10568 /// applied to. 10569 /// \param VariantRef Expression that references the variant function, which 10570 /// must be used instead of the original one, specified in \p DG. 10571 /// \param TI The context traits associated with the function variant. 10572 void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef, 10573 OMPTraitInfo &TI, SourceRange SR); 10574 10575 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, 10576 Expr *Expr, 10577 SourceLocation StartLoc, 10578 SourceLocation LParenLoc, 10579 SourceLocation EndLoc); 10580 /// Called on well-formed 'allocator' clause. 10581 OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator, 10582 SourceLocation StartLoc, 10583 SourceLocation LParenLoc, 10584 SourceLocation EndLoc); 10585 /// Called on well-formed 'if' clause. 10586 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 10587 Expr *Condition, SourceLocation StartLoc, 10588 SourceLocation LParenLoc, 10589 SourceLocation NameModifierLoc, 10590 SourceLocation ColonLoc, 10591 SourceLocation EndLoc); 10592 /// Called on well-formed 'final' clause. 10593 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc, 10594 SourceLocation LParenLoc, 10595 SourceLocation EndLoc); 10596 /// Called on well-formed 'num_threads' clause. 10597 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads, 10598 SourceLocation StartLoc, 10599 SourceLocation LParenLoc, 10600 SourceLocation EndLoc); 10601 /// Called on well-formed 'safelen' clause. 10602 OMPClause *ActOnOpenMPSafelenClause(Expr *Length, 10603 SourceLocation StartLoc, 10604 SourceLocation LParenLoc, 10605 SourceLocation EndLoc); 10606 /// Called on well-formed 'simdlen' clause. 10607 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc, 10608 SourceLocation LParenLoc, 10609 SourceLocation EndLoc); 10610 /// Called on well-formed 'collapse' clause. 10611 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops, 10612 SourceLocation StartLoc, 10613 SourceLocation LParenLoc, 10614 SourceLocation EndLoc); 10615 /// Called on well-formed 'ordered' clause. 10616 OMPClause * 10617 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc, 10618 SourceLocation LParenLoc = SourceLocation(), 10619 Expr *NumForLoops = nullptr); 10620 /// Called on well-formed 'grainsize' clause. 10621 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc, 10622 SourceLocation LParenLoc, 10623 SourceLocation EndLoc); 10624 /// Called on well-formed 'num_tasks' clause. 10625 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc, 10626 SourceLocation LParenLoc, 10627 SourceLocation EndLoc); 10628 /// Called on well-formed 'hint' clause. 10629 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 10630 SourceLocation LParenLoc, 10631 SourceLocation EndLoc); 10632 /// Called on well-formed 'detach' clause. 10633 OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc, 10634 SourceLocation LParenLoc, 10635 SourceLocation EndLoc); 10636 10637 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind, 10638 unsigned Argument, 10639 SourceLocation ArgumentLoc, 10640 SourceLocation StartLoc, 10641 SourceLocation LParenLoc, 10642 SourceLocation EndLoc); 10643 /// Called on well-formed 'default' clause. 10644 OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind, 10645 SourceLocation KindLoc, 10646 SourceLocation StartLoc, 10647 SourceLocation LParenLoc, 10648 SourceLocation EndLoc); 10649 /// Called on well-formed 'proc_bind' clause. 10650 OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind, 10651 SourceLocation KindLoc, 10652 SourceLocation StartLoc, 10653 SourceLocation LParenLoc, 10654 SourceLocation EndLoc); 10655 /// Called on well-formed 'order' clause. 10656 OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind, 10657 SourceLocation KindLoc, 10658 SourceLocation StartLoc, 10659 SourceLocation LParenLoc, 10660 SourceLocation EndLoc); 10661 /// Called on well-formed 'update' clause. 10662 OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind, 10663 SourceLocation KindLoc, 10664 SourceLocation StartLoc, 10665 SourceLocation LParenLoc, 10666 SourceLocation EndLoc); 10667 10668 OMPClause *ActOnOpenMPSingleExprWithArgClause( 10669 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr, 10670 SourceLocation StartLoc, SourceLocation LParenLoc, 10671 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc, 10672 SourceLocation EndLoc); 10673 /// Called on well-formed 'schedule' clause. 10674 OMPClause *ActOnOpenMPScheduleClause( 10675 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 10676 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 10677 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 10678 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); 10679 10680 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc, 10681 SourceLocation EndLoc); 10682 /// Called on well-formed 'nowait' clause. 10683 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc, 10684 SourceLocation EndLoc); 10685 /// Called on well-formed 'untied' clause. 10686 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc, 10687 SourceLocation EndLoc); 10688 /// Called on well-formed 'mergeable' clause. 10689 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc, 10690 SourceLocation EndLoc); 10691 /// Called on well-formed 'read' clause. 10692 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc, 10693 SourceLocation EndLoc); 10694 /// Called on well-formed 'write' clause. 10695 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc, 10696 SourceLocation EndLoc); 10697 /// Called on well-formed 'update' clause. 10698 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc, 10699 SourceLocation EndLoc); 10700 /// Called on well-formed 'capture' clause. 10701 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc, 10702 SourceLocation EndLoc); 10703 /// Called on well-formed 'seq_cst' clause. 10704 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 10705 SourceLocation EndLoc); 10706 /// Called on well-formed 'acq_rel' clause. 10707 OMPClause *ActOnOpenMPAcqRelClause(SourceLocation StartLoc, 10708 SourceLocation EndLoc); 10709 /// Called on well-formed 'acquire' clause. 10710 OMPClause *ActOnOpenMPAcquireClause(SourceLocation StartLoc, 10711 SourceLocation EndLoc); 10712 /// Called on well-formed 'release' clause. 10713 OMPClause *ActOnOpenMPReleaseClause(SourceLocation StartLoc, 10714 SourceLocation EndLoc); 10715 /// Called on well-formed 'relaxed' clause. 10716 OMPClause *ActOnOpenMPRelaxedClause(SourceLocation StartLoc, 10717 SourceLocation EndLoc); 10718 /// Called on well-formed 'destroy' clause. 10719 OMPClause *ActOnOpenMPDestroyClause(SourceLocation StartLoc, 10720 SourceLocation EndLoc); 10721 /// Called on well-formed 'threads' clause. 10722 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc, 10723 SourceLocation EndLoc); 10724 /// Called on well-formed 'simd' clause. 10725 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc, 10726 SourceLocation EndLoc); 10727 /// Called on well-formed 'nogroup' clause. 10728 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc, 10729 SourceLocation EndLoc); 10730 /// Called on well-formed 'unified_address' clause. 10731 OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, 10732 SourceLocation EndLoc); 10733 10734 /// Called on well-formed 'unified_address' clause. 10735 OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, 10736 SourceLocation EndLoc); 10737 10738 /// Called on well-formed 'reverse_offload' clause. 10739 OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, 10740 SourceLocation EndLoc); 10741 10742 /// Called on well-formed 'dynamic_allocators' clause. 10743 OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, 10744 SourceLocation EndLoc); 10745 10746 /// Called on well-formed 'atomic_default_mem_order' clause. 10747 OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause( 10748 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc, 10749 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); 10750 10751 OMPClause *ActOnOpenMPVarListClause( 10752 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *DepModOrTailExpr, 10753 const OMPVarListLocTy &Locs, SourceLocation ColonLoc, 10754 CXXScopeSpec &ReductionOrMapperIdScopeSpec, 10755 DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier, 10756 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 10757 ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit, 10758 SourceLocation ExtraModifierLoc); 10759 /// Called on well-formed 'inclusive' clause. 10760 OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList, 10761 SourceLocation StartLoc, 10762 SourceLocation LParenLoc, 10763 SourceLocation EndLoc); 10764 /// Called on well-formed 'exclusive' clause. 10765 OMPClause *ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList, 10766 SourceLocation StartLoc, 10767 SourceLocation LParenLoc, 10768 SourceLocation EndLoc); 10769 /// Called on well-formed 'allocate' clause. 10770 OMPClause * 10771 ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList, 10772 SourceLocation StartLoc, SourceLocation ColonLoc, 10773 SourceLocation LParenLoc, SourceLocation EndLoc); 10774 /// Called on well-formed 'private' clause. 10775 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 10776 SourceLocation StartLoc, 10777 SourceLocation LParenLoc, 10778 SourceLocation EndLoc); 10779 /// Called on well-formed 'firstprivate' clause. 10780 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 10781 SourceLocation StartLoc, 10782 SourceLocation LParenLoc, 10783 SourceLocation EndLoc); 10784 /// Called on well-formed 'lastprivate' clause. 10785 OMPClause *ActOnOpenMPLastprivateClause( 10786 ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind, 10787 SourceLocation LPKindLoc, SourceLocation ColonLoc, 10788 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); 10789 /// Called on well-formed 'shared' clause. 10790 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 10791 SourceLocation StartLoc, 10792 SourceLocation LParenLoc, 10793 SourceLocation EndLoc); 10794 /// Called on well-formed 'reduction' clause. 10795 OMPClause *ActOnOpenMPReductionClause( 10796 ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier, 10797 SourceLocation StartLoc, SourceLocation LParenLoc, 10798 SourceLocation ModifierLoc, SourceLocation ColonLoc, 10799 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, 10800 const DeclarationNameInfo &ReductionId, 10801 ArrayRef<Expr *> UnresolvedReductions = llvm::None); 10802 /// Called on well-formed 'task_reduction' clause. 10803 OMPClause *ActOnOpenMPTaskReductionClause( 10804 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 10805 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, 10806 CXXScopeSpec &ReductionIdScopeSpec, 10807 const DeclarationNameInfo &ReductionId, 10808 ArrayRef<Expr *> UnresolvedReductions = llvm::None); 10809 /// Called on well-formed 'in_reduction' clause. 10810 OMPClause *ActOnOpenMPInReductionClause( 10811 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 10812 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, 10813 CXXScopeSpec &ReductionIdScopeSpec, 10814 const DeclarationNameInfo &ReductionId, 10815 ArrayRef<Expr *> UnresolvedReductions = llvm::None); 10816 /// Called on well-formed 'linear' clause. 10817 OMPClause * 10818 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step, 10819 SourceLocation StartLoc, SourceLocation LParenLoc, 10820 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc, 10821 SourceLocation ColonLoc, SourceLocation EndLoc); 10822 /// Called on well-formed 'aligned' clause. 10823 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList, 10824 Expr *Alignment, 10825 SourceLocation StartLoc, 10826 SourceLocation LParenLoc, 10827 SourceLocation ColonLoc, 10828 SourceLocation EndLoc); 10829 /// Called on well-formed 'copyin' clause. 10830 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 10831 SourceLocation StartLoc, 10832 SourceLocation LParenLoc, 10833 SourceLocation EndLoc); 10834 /// Called on well-formed 'copyprivate' clause. 10835 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 10836 SourceLocation StartLoc, 10837 SourceLocation LParenLoc, 10838 SourceLocation EndLoc); 10839 /// Called on well-formed 'flush' pseudo clause. 10840 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 10841 SourceLocation StartLoc, 10842 SourceLocation LParenLoc, 10843 SourceLocation EndLoc); 10844 /// Called on well-formed 'depobj' pseudo clause. 10845 OMPClause *ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc, 10846 SourceLocation LParenLoc, 10847 SourceLocation EndLoc); 10848 /// Called on well-formed 'depend' clause. 10849 OMPClause * 10850 ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind, 10851 SourceLocation DepLoc, SourceLocation ColonLoc, 10852 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 10853 SourceLocation LParenLoc, SourceLocation EndLoc); 10854 /// Called on well-formed 'device' clause. 10855 OMPClause *ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier, 10856 Expr *Device, SourceLocation StartLoc, 10857 SourceLocation LParenLoc, 10858 SourceLocation ModifierLoc, 10859 SourceLocation EndLoc); 10860 /// Called on well-formed 'map' clause. 10861 OMPClause * 10862 ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 10863 ArrayRef<SourceLocation> MapTypeModifiersLoc, 10864 CXXScopeSpec &MapperIdScopeSpec, 10865 DeclarationNameInfo &MapperId, 10866 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 10867 SourceLocation MapLoc, SourceLocation ColonLoc, 10868 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, 10869 ArrayRef<Expr *> UnresolvedMappers = llvm::None); 10870 /// Called on well-formed 'num_teams' clause. 10871 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc, 10872 SourceLocation LParenLoc, 10873 SourceLocation EndLoc); 10874 /// Called on well-formed 'thread_limit' clause. 10875 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 10876 SourceLocation StartLoc, 10877 SourceLocation LParenLoc, 10878 SourceLocation EndLoc); 10879 /// Called on well-formed 'priority' clause. 10880 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc, 10881 SourceLocation LParenLoc, 10882 SourceLocation EndLoc); 10883 /// Called on well-formed 'dist_schedule' clause. 10884 OMPClause *ActOnOpenMPDistScheduleClause( 10885 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, 10886 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc, 10887 SourceLocation CommaLoc, SourceLocation EndLoc); 10888 /// Called on well-formed 'defaultmap' clause. 10889 OMPClause *ActOnOpenMPDefaultmapClause( 10890 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 10891 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 10892 SourceLocation KindLoc, SourceLocation EndLoc); 10893 /// Called on well-formed 'to' clause. 10894 OMPClause * 10895 ActOnOpenMPToClause(ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec, 10896 DeclarationNameInfo &MapperId, 10897 const OMPVarListLocTy &Locs, 10898 ArrayRef<Expr *> UnresolvedMappers = llvm::None); 10899 /// Called on well-formed 'from' clause. 10900 OMPClause *ActOnOpenMPFromClause( 10901 ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec, 10902 DeclarationNameInfo &MapperId, const OMPVarListLocTy &Locs, 10903 ArrayRef<Expr *> UnresolvedMappers = llvm::None); 10904 /// Called on well-formed 'use_device_ptr' clause. 10905 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 10906 const OMPVarListLocTy &Locs); 10907 /// Called on well-formed 'use_device_addr' clause. 10908 OMPClause *ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList, 10909 const OMPVarListLocTy &Locs); 10910 /// Called on well-formed 'is_device_ptr' clause. 10911 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 10912 const OMPVarListLocTy &Locs); 10913 /// Called on well-formed 'nontemporal' clause. 10914 OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList, 10915 SourceLocation StartLoc, 10916 SourceLocation LParenLoc, 10917 SourceLocation EndLoc); 10918 10919 /// Data for list of allocators. 10920 struct UsesAllocatorsData { 10921 /// Allocator. 10922 Expr *Allocator = nullptr; 10923 /// Allocator traits. 10924 Expr *AllocatorTraits = nullptr; 10925 /// Locations of '(' and ')' symbols. 10926 SourceLocation LParenLoc, RParenLoc; 10927 }; 10928 /// Called on well-formed 'uses_allocators' clause. 10929 OMPClause *ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc, 10930 SourceLocation LParenLoc, 10931 SourceLocation EndLoc, 10932 ArrayRef<UsesAllocatorsData> Data); 10933 /// Called on well-formed 'affinity' clause. 10934 OMPClause *ActOnOpenMPAffinityClause(SourceLocation StartLoc, 10935 SourceLocation LParenLoc, 10936 SourceLocation ColonLoc, 10937 SourceLocation EndLoc, Expr *Modifier, 10938 ArrayRef<Expr *> Locators); 10939 10940 /// The kind of conversion being performed. 10941 enum CheckedConversionKind { 10942 /// An implicit conversion. 10943 CCK_ImplicitConversion, 10944 /// A C-style cast. 10945 CCK_CStyleCast, 10946 /// A functional-style cast. 10947 CCK_FunctionalCast, 10948 /// A cast other than a C-style cast. 10949 CCK_OtherCast, 10950 /// A conversion for an operand of a builtin overloaded operator. 10951 CCK_ForBuiltinOverloadedOp 10952 }; 10953 isCast(CheckedConversionKind CCK)10954 static bool isCast(CheckedConversionKind CCK) { 10955 return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast || 10956 CCK == CCK_OtherCast; 10957 } 10958 10959 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit 10960 /// cast. If there is already an implicit cast, merge into the existing one. 10961 /// If isLvalue, the result of the cast is an lvalue. 10962 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, 10963 ExprValueKind VK = VK_RValue, 10964 const CXXCastPath *BasePath = nullptr, 10965 CheckedConversionKind CCK 10966 = CCK_ImplicitConversion); 10967 10968 /// ImpCastPointerToCHERICapability - Checks if pointer type FromTy can be 10969 /// implicitly converted to capability type ToTy 10970 bool ImpCastPointerToCHERICapability(QualType FromTy, QualType ToTy, 10971 Expr *&From, bool Diagnose); 10972 10973 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding 10974 /// to the conversion from scalar type ScalarTy to the Boolean type. 10975 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); 10976 10977 /// IgnoredValueConversions - Given that an expression's result is 10978 /// syntactically ignored, perform any conversions that are 10979 /// required. 10980 ExprResult IgnoredValueConversions(Expr *E); 10981 10982 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts 10983 // functions and arrays to their respective pointers (C99 6.3.2.1). 10984 ExprResult UsualUnaryConversions(Expr *E); 10985 10986 /// CallExprUnaryConversions - a special case of an unary conversion 10987 /// performed on a function designator of a call expression. 10988 ExprResult CallExprUnaryConversions(Expr *E); 10989 10990 // DefaultFunctionArrayConversion - converts functions and arrays 10991 // to their respective pointers (C99 6.3.2.1). 10992 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true); 10993 10994 // DefaultFunctionArrayLvalueConversion - converts functions and 10995 // arrays to their respective pointers and performs the 10996 // lvalue-to-rvalue conversion. 10997 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, 10998 bool Diagnose = true); 10999 11000 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on 11001 // the operand. This function is a no-op if the operand has a function type 11002 // or an array type. 11003 ExprResult DefaultLvalueConversion(Expr *E); 11004 11005 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 11006 // do not have a prototype. Integer promotions are performed on each 11007 // argument, and arguments that have type float are promoted to double. 11008 ExprResult DefaultArgumentPromotion(Expr *E); 11009 11010 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize 11011 /// it as an xvalue. In C++98, the result will still be a prvalue, because 11012 /// we don't have xvalues there. 11013 ExprResult TemporaryMaterializationConversion(Expr *E); 11014 11015 // Used for emitting the right warning by DefaultVariadicArgumentPromotion 11016 enum VariadicCallType { 11017 VariadicFunction, 11018 VariadicBlock, 11019 VariadicMethod, 11020 VariadicConstructor, 11021 VariadicDoesNotApply 11022 }; 11023 11024 VariadicCallType getVariadicCallType(FunctionDecl *FDecl, 11025 const FunctionProtoType *Proto, 11026 Expr *Fn); 11027 11028 // Used for determining in which context a type is allowed to be passed to a 11029 // vararg function. 11030 enum VarArgKind { 11031 VAK_Valid, 11032 VAK_ValidInCXX11, 11033 VAK_Undefined, 11034 VAK_MSVCUndefined, 11035 VAK_Invalid 11036 }; 11037 11038 // Determines which VarArgKind fits an expression. 11039 VarArgKind isValidVarArgType(const QualType &Ty); 11040 11041 /// Check to see if the given expression is a valid argument to a variadic 11042 /// function, issuing a diagnostic if not. 11043 void checkVariadicArgument(const Expr *E, VariadicCallType CT); 11044 11045 /// Check to see if a given expression could have '.c_str()' called on it. 11046 bool hasCStrMethod(const Expr *E); 11047 11048 /// GatherArgumentsForCall - Collector argument expressions for various 11049 /// form of call prototypes. 11050 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 11051 const FunctionProtoType *Proto, 11052 unsigned FirstParam, ArrayRef<Expr *> Args, 11053 SmallVectorImpl<Expr *> &AllArgs, 11054 VariadicCallType CallType = VariadicDoesNotApply, 11055 bool AllowExplicit = false, 11056 bool IsListInitialization = false); 11057 11058 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 11059 // will create a runtime trap if the resulting type is not a POD type. 11060 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 11061 FunctionDecl *FDecl); 11062 11063 /// Context in which we're performing a usual arithmetic conversion. 11064 enum ArithConvKind { 11065 /// An arithmetic operation. 11066 ACK_Arithmetic, 11067 /// A bitwise operation. 11068 ACK_BitwiseOp, 11069 /// A comparison. 11070 ACK_Comparison, 11071 /// A conditional (?:) operator. 11072 ACK_Conditional, 11073 /// A compound assignment expression. 11074 ACK_CompAssign, 11075 }; 11076 11077 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's 11078 // operands and then handles various conversions that are common to binary 11079 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this 11080 // routine returns the first non-arithmetic type found. The client is 11081 // responsible for emitting appropriate error diagnostics. 11082 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 11083 SourceLocation Loc, ArithConvKind ACK); 11084 11085 /// AssignConvertType - All of the 'assignment' semantic checks return this 11086 /// enum to indicate whether the assignment was allowed. These checks are 11087 /// done for simple assignments, as well as initialization, return from 11088 /// function, argument passing, etc. The query is phrased in terms of a 11089 /// source and destination type. 11090 enum AssignConvertType { 11091 /// Compatible - the types are compatible according to the standard. 11092 Compatible, 11093 11094 /// PointerToInt - The assignment converts a pointer to an int, which we 11095 /// accept as an extension. 11096 PointerToInt, 11097 11098 /// IntToPointer - The assignment converts an int to a pointer, which we 11099 /// accept as an extension. 11100 IntToPointer, 11101 11102 /// CHERICapabilityToPointer - The assignment converts a capability to a 11103 /// pointer, which we reject (it needs an explicit __cheri_fromcap). 11104 CHERICapabilityToPointer, 11105 /// PointerToCHERICapability - The assignment converts a pointer to a 11106 /// capability, which we reject (it needs an explicit __cheri_tocap). 11107 PointerToCHERICapability, 11108 11109 /// FunctionVoidPointer - The assignment is between a function pointer and 11110 /// void*, which the standard doesn't allow, but we accept as an extension. 11111 FunctionVoidPointer, 11112 11113 /// IncompatiblePointer - The assignment is between two pointers types that 11114 /// are not compatible, but we accept them as an extension. 11115 IncompatiblePointer, 11116 11117 /// IncompatibleFunctionPointer - The assignment is between two function 11118 /// pointers types that are not compatible, but we accept them as an 11119 /// extension. 11120 IncompatibleFunctionPointer, 11121 11122 /// IncompatiblePointerSign - The assignment is between two pointers types 11123 /// which point to integers which have a different sign, but are otherwise 11124 /// identical. This is a subset of the above, but broken out because it's by 11125 /// far the most common case of incompatible pointers. 11126 IncompatiblePointerSign, 11127 11128 /// CompatiblePointerDiscardsQualifiers - The assignment discards 11129 /// c/v/r qualifiers, which we accept as an extension. 11130 CompatiblePointerDiscardsQualifiers, 11131 11132 /// IncompatiblePointerDiscardsQualifiers - The assignment 11133 /// discards qualifiers that we don't permit to be discarded, 11134 /// like address spaces. 11135 IncompatiblePointerDiscardsQualifiers, 11136 11137 /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment 11138 /// changes address spaces in nested pointer types which is not allowed. 11139 /// For instance, converting __private int ** to __generic int ** is 11140 /// illegal even though __private could be converted to __generic. 11141 IncompatibleNestedPointerAddressSpaceMismatch, 11142 11143 /// IncompatibleNestedPointerQualifiers - The assignment is between two 11144 /// nested pointer types, and the qualifiers other than the first two 11145 /// levels differ e.g. char ** -> const char **, but we accept them as an 11146 /// extension. 11147 IncompatibleNestedPointerQualifiers, 11148 11149 /// IncompatibleVectors - The assignment is between two vector types that 11150 /// have the same size, which we accept as an extension. 11151 IncompatibleVectors, 11152 11153 /// IntToBlockPointer - The assignment converts an int to a block 11154 /// pointer. We disallow this. 11155 IntToBlockPointer, 11156 11157 /// IncompatibleBlockPointer - The assignment is between two block 11158 /// pointers types that are not compatible. 11159 IncompatibleBlockPointer, 11160 11161 /// IncompatibleObjCQualifiedId - The assignment is between a qualified 11162 /// id type and something else (that is incompatible with it). For example, 11163 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. 11164 IncompatibleObjCQualifiedId, 11165 11166 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an 11167 /// object with __weak qualifier. 11168 IncompatibleObjCWeakRef, 11169 11170 /// Incompatible - We reject this conversion outright, it is invalid to 11171 /// represent it in the AST. 11172 Incompatible 11173 }; 11174 11175 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the 11176 /// assignment conversion type specified by ConvTy. This returns true if the 11177 /// conversion was invalid or false if the conversion was accepted. 11178 bool DiagnoseAssignmentResult(AssignConvertType ConvTy, 11179 SourceLocation Loc, 11180 QualType DstType, QualType SrcType, 11181 Expr *SrcExpr, AssignmentAction Action, 11182 bool *Complained = nullptr); 11183 11184 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag 11185 /// enum. If AllowMask is true, then we also allow the complement of a valid 11186 /// value, to be used as a mask. 11187 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 11188 bool AllowMask) const; 11189 11190 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant 11191 /// integer not in the range of enum values. 11192 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, 11193 Expr *SrcExpr); 11194 11195 /// CheckAssignmentConstraints - Perform type checking for assignment, 11196 /// argument passing, variable initialization, and function return values. 11197 /// C99 6.5.16. 11198 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, 11199 QualType LHSType, 11200 QualType RHSType); 11201 11202 /// Check assignment constraints and optionally prepare for a conversion of 11203 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS 11204 /// is true. 11205 AssignConvertType CheckAssignmentConstraints(QualType LHSType, 11206 ExprResult &RHS, 11207 CastKind &Kind, 11208 bool ConvertRHS = true); 11209 11210 /// Check assignment constraints for an assignment of RHS to LHSType. 11211 /// 11212 /// \param LHSType The destination type for the assignment. 11213 /// \param RHS The source expression for the assignment. 11214 /// \param Diagnose If \c true, diagnostics may be produced when checking 11215 /// for assignability. If a diagnostic is produced, \p RHS will be 11216 /// set to ExprError(). Note that this function may still return 11217 /// without producing a diagnostic, even for an invalid assignment. 11218 /// \param DiagnoseCFAudited If \c true, the target is a function parameter 11219 /// in an audited Core Foundation API and does not need to be checked 11220 /// for ARC retain issues. 11221 /// \param ConvertRHS If \c true, \p RHS will be updated to model the 11222 /// conversions necessary to perform the assignment. If \c false, 11223 /// \p Diagnose must also be \c false. 11224 AssignConvertType CheckSingleAssignmentConstraints( 11225 QualType LHSType, ExprResult &RHS, bool Diagnose = true, 11226 bool DiagnoseCFAudited = false, bool ConvertRHS = true); 11227 11228 // If the lhs type is a transparent union, check whether we 11229 // can initialize the transparent union with the given expression. 11230 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, 11231 ExprResult &RHS); 11232 11233 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); 11234 11235 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); 11236 11237 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 11238 AssignmentAction Action, 11239 bool AllowExplicit = false); 11240 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 11241 AssignmentAction Action, 11242 bool AllowExplicit, 11243 ImplicitConversionSequence& ICS); 11244 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 11245 const ImplicitConversionSequence& ICS, 11246 AssignmentAction Action, 11247 CheckedConversionKind CCK 11248 = CCK_ImplicitConversion); 11249 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 11250 const StandardConversionSequence& SCS, 11251 AssignmentAction Action, 11252 CheckedConversionKind CCK); 11253 11254 ExprResult PerformQualificationConversion( 11255 Expr *E, QualType Ty, ExprValueKind VK = VK_RValue, 11256 CheckedConversionKind CCK = CCK_ImplicitConversion); 11257 11258 /// the following "Check" methods will return a valid/converted QualType 11259 /// or a null QualType (indicating an error diagnostic was issued). 11260 11261 /// type checking binary operators (subroutines of CreateBuiltinBinOp). 11262 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, 11263 ExprResult &RHS); 11264 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 11265 ExprResult &RHS); 11266 QualType CheckPointerToMemberOperands( // C++ 5.5 11267 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, 11268 SourceLocation OpLoc, bool isIndirect); 11269 QualType CheckMultiplyDivideOperands( // C99 6.5.5 11270 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, 11271 bool IsDivide); 11272 QualType CheckRemainderOperands( // C99 6.5.5 11273 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11274 bool IsCompAssign = false); 11275 QualType CheckAdditionOperands( // C99 6.5.6 11276 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11277 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr); 11278 QualType CheckSubtractionOperands( // C99 6.5.6 11279 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11280 QualType* CompLHSTy = nullptr); 11281 QualType CheckShiftOperands( // C99 6.5.7 11282 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11283 BinaryOperatorKind Opc, bool IsCompAssign = false); 11284 void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE); 11285 QualType CheckCompareOperands( // C99 6.5.8/9 11286 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11287 BinaryOperatorKind Opc); 11288 QualType CheckBitwiseOperands( // C99 6.5.[10...12] 11289 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11290 BinaryOperatorKind Opc); 11291 QualType CheckLogicalOperands( // C99 6.5.[13,14] 11292 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11293 BinaryOperatorKind Opc); 11294 // CheckAssignmentOperands is used for both simple and compound assignment. 11295 // For simple assignment, pass both expressions and a null converted type. 11296 // For compound assignment, pass both expressions and the converted type. 11297 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] 11298 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); 11299 11300 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, 11301 UnaryOperatorKind Opcode, Expr *Op); 11302 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, 11303 BinaryOperatorKind Opcode, 11304 Expr *LHS, Expr *RHS); 11305 ExprResult checkPseudoObjectRValue(Expr *E); 11306 Expr *recreateSyntacticForm(PseudoObjectExpr *E); 11307 11308 QualType CheckConditionalOperands( // C99 6.5.15 11309 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, 11310 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); 11311 QualType CXXCheckConditionalOperands( // C++ 5.16 11312 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, 11313 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); 11314 QualType CheckGNUVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, 11315 ExprResult &RHS, 11316 SourceLocation QuestionLoc); 11317 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, 11318 bool ConvertArgs = true); 11319 QualType FindCompositePointerType(SourceLocation Loc, 11320 ExprResult &E1, ExprResult &E2, 11321 bool ConvertArgs = true) { 11322 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get(); 11323 QualType Composite = 11324 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs); 11325 E1 = E1Tmp; 11326 E2 = E2Tmp; 11327 return Composite; 11328 } 11329 11330 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 11331 SourceLocation QuestionLoc); 11332 11333 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 11334 SourceLocation QuestionLoc); 11335 11336 void DiagnoseAlwaysNonNullPointer(Expr *E, 11337 Expr::NullPointerConstantKind NullType, 11338 bool IsEqual, SourceRange Range); 11339 11340 /// type checking for vector binary operators. 11341 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 11342 SourceLocation Loc, bool IsCompAssign, 11343 bool AllowBothBool, bool AllowBoolConversion); 11344 QualType GetSignedVectorType(QualType V); 11345 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11346 SourceLocation Loc, 11347 BinaryOperatorKind Opc); 11348 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11349 SourceLocation Loc); 11350 11351 /// Type checking for matrix binary operators. 11352 QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 11353 SourceLocation Loc, 11354 bool IsCompAssign); 11355 QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 11356 SourceLocation Loc, bool IsCompAssign); 11357 11358 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType); 11359 bool isLaxVectorConversion(QualType srcType, QualType destType); 11360 11361 /// type checking declaration initializers (C99 6.7.8) 11362 bool CheckForConstantInitializer(Expr *e, QualType t); 11363 11364 // type checking C++ declaration initializers (C++ [dcl.init]). 11365 11366 /// ReferenceCompareResult - Expresses the result of comparing two 11367 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the 11368 /// purposes of initialization by reference (C++ [dcl.init.ref]p4). 11369 enum ReferenceCompareResult { 11370 /// Ref_Incompatible - The two types are incompatible, so direct 11371 /// reference binding is not possible. 11372 Ref_Incompatible = 0, 11373 /// Ref_Related - The two types are reference-related, which means 11374 /// that their unqualified forms (T1 and T2) are either the same 11375 /// or T1 is a base class of T2. 11376 Ref_Related, 11377 /// Ref_Compatible - The two types are reference-compatible. 11378 Ref_Compatible 11379 }; 11380 11381 // Fake up a scoped enumeration that still contextually converts to bool. 11382 struct ReferenceConversionsScope { 11383 /// The conversions that would be performed on an lvalue of type T2 when 11384 /// binding a reference of type T1 to it, as determined when evaluating 11385 /// whether T1 is reference-compatible with T2. 11386 enum ReferenceConversions { 11387 Qualification = 0x1, 11388 NestedQualification = 0x2, 11389 Function = 0x4, 11390 DerivedToBase = 0x8, 11391 ObjC = 0x10, 11392 ObjCLifetime = 0x20, 11393 11394 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime) 11395 }; 11396 }; 11397 using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions; 11398 11399 ReferenceCompareResult 11400 CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, 11401 ReferenceConversions *Conv = nullptr); 11402 11403 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 11404 Expr *CastExpr, CastKind &CastKind, 11405 ExprValueKind &VK, CXXCastPath &Path); 11406 11407 /// Force an expression with unknown-type to an expression of the 11408 /// given type. 11409 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); 11410 11411 /// Type-check an expression that's being passed to an 11412 /// __unknown_anytype parameter. 11413 ExprResult checkUnknownAnyArg(SourceLocation callLoc, 11414 Expr *result, QualType ¶mType); 11415 11416 // CheckVectorCast - check type constraints for vectors. 11417 // Since vectors are an extension, there are no C standard reference for this. 11418 // We allow casting between vectors and integer datatypes of the same size. 11419 // returns true if the cast is invalid 11420 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 11421 CastKind &Kind); 11422 11423 /// Prepare `SplattedExpr` for a vector splat operation, adding 11424 /// implicit casts if necessary. 11425 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr); 11426 11427 // CheckExtVectorCast - check type constraints for extended vectors. 11428 // Since vectors are an extension, there are no C standard reference for this. 11429 // We allow casting between vectors and integer datatypes of the same size, 11430 // or vectors and the element type of that vector. 11431 // returns the cast expr 11432 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, 11433 CastKind &Kind); 11434 11435 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, 11436 SourceLocation LParenLoc, 11437 Expr *CastExpr, 11438 SourceLocation RParenLoc); 11439 11440 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error }; 11441 11442 /// Checks for invalid conversions and casts between 11443 /// retainable pointers and other pointer kinds for ARC and Weak. 11444 ARCConversionResult CheckObjCConversion(SourceRange castRange, 11445 QualType castType, Expr *&op, 11446 CheckedConversionKind CCK, 11447 bool Diagnose = true, 11448 bool DiagnoseCFAudited = false, 11449 BinaryOperatorKind Opc = BO_PtrMemD 11450 ); 11451 11452 Expr *stripARCUnbridgedCast(Expr *e); 11453 void diagnoseARCUnbridgedCast(Expr *e); 11454 11455 bool CheckObjCARCUnavailableWeakConversion(QualType castType, 11456 QualType ExprType); 11457 11458 /// checkRetainCycles - Check whether an Objective-C message send 11459 /// might create an obvious retain cycle. 11460 void checkRetainCycles(ObjCMessageExpr *msg); 11461 void checkRetainCycles(Expr *receiver, Expr *argument); 11462 void checkRetainCycles(VarDecl *Var, Expr *Init); 11463 11464 /// checkUnsafeAssigns - Check whether +1 expr is being assigned 11465 /// to weak/__unsafe_unretained type. 11466 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); 11467 11468 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned 11469 /// to weak/__unsafe_unretained expression. 11470 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); 11471 11472 /// CheckMessageArgumentTypes - Check types in an Obj-C message send. 11473 /// \param Method - May be null. 11474 /// \param [out] ReturnType - The return type of the send. 11475 /// \return true iff there were any incompatible types. 11476 bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType, 11477 MultiExprArg Args, Selector Sel, 11478 ArrayRef<SourceLocation> SelectorLocs, 11479 ObjCMethodDecl *Method, bool isClassMessage, 11480 bool isSuperMessage, SourceLocation lbrac, 11481 SourceLocation rbrac, SourceRange RecRange, 11482 QualType &ReturnType, ExprValueKind &VK); 11483 11484 /// Determine the result of a message send expression based on 11485 /// the type of the receiver, the method expected to receive the message, 11486 /// and the form of the message send. 11487 QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType, 11488 ObjCMethodDecl *Method, bool isClassMessage, 11489 bool isSuperMessage); 11490 11491 /// If the given expression involves a message send to a method 11492 /// with a related result type, emit a note describing what happened. 11493 void EmitRelatedResultTypeNote(const Expr *E); 11494 11495 /// Given that we had incompatible pointer types in a return 11496 /// statement, check whether we're in a method with a related result 11497 /// type, and if so, emit a note describing what happened. 11498 void EmitRelatedResultTypeNoteForReturn(QualType destType); 11499 11500 class ConditionResult { 11501 Decl *ConditionVar; 11502 FullExprArg Condition; 11503 bool Invalid; 11504 bool HasKnownValue; 11505 bool KnownValue; 11506 11507 friend class Sema; ConditionResult(Sema & S,Decl * ConditionVar,FullExprArg Condition,bool IsConstexpr)11508 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition, 11509 bool IsConstexpr) 11510 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false), 11511 HasKnownValue(IsConstexpr && Condition.get() && 11512 !Condition.get()->isValueDependent()), 11513 KnownValue(HasKnownValue && 11514 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {} ConditionResult(bool Invalid)11515 explicit ConditionResult(bool Invalid) 11516 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid), 11517 HasKnownValue(false), KnownValue(false) {} 11518 11519 public: ConditionResult()11520 ConditionResult() : ConditionResult(false) {} isInvalid()11521 bool isInvalid() const { return Invalid; } get()11522 std::pair<VarDecl *, Expr *> get() const { 11523 return std::make_pair(cast_or_null<VarDecl>(ConditionVar), 11524 Condition.get()); 11525 } getKnownValue()11526 llvm::Optional<bool> getKnownValue() const { 11527 if (!HasKnownValue) 11528 return None; 11529 return KnownValue; 11530 } 11531 }; ConditionError()11532 static ConditionResult ConditionError() { return ConditionResult(true); } 11533 11534 enum class ConditionKind { 11535 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'. 11536 ConstexprIf, ///< A constant boolean condition from 'if constexpr'. 11537 Switch ///< An integral condition for a 'switch' statement. 11538 }; 11539 11540 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, 11541 Expr *SubExpr, ConditionKind CK); 11542 11543 ConditionResult ActOnConditionVariable(Decl *ConditionVar, 11544 SourceLocation StmtLoc, 11545 ConditionKind CK); 11546 11547 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); 11548 11549 ExprResult CheckConditionVariable(VarDecl *ConditionVar, 11550 SourceLocation StmtLoc, 11551 ConditionKind CK); 11552 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond); 11553 11554 /// CheckBooleanCondition - Diagnose problems involving the use of 11555 /// the given expression as a boolean condition (e.g. in an if 11556 /// statement). Also performs the standard function and array 11557 /// decays, possibly changing the input variable. 11558 /// 11559 /// \param Loc - A location associated with the condition, e.g. the 11560 /// 'if' keyword. 11561 /// \return true iff there were any errors 11562 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, 11563 bool IsConstexpr = false); 11564 11565 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression 11566 /// found in an explicit(bool) specifier. 11567 ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E); 11568 11569 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier. 11570 /// Returns true if the explicit specifier is now resolved. 11571 bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec); 11572 11573 /// DiagnoseAssignmentAsCondition - Given that an expression is 11574 /// being used as a boolean condition, warn if it's an assignment. 11575 void DiagnoseAssignmentAsCondition(Expr *E); 11576 11577 /// Redundant parentheses over an equality comparison can indicate 11578 /// that the user intended an assignment used as condition. 11579 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); 11580 11581 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. 11582 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false); 11583 11584 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 11585 /// the specified width and sign. If an overflow occurs, detect it and emit 11586 /// the specified diagnostic. 11587 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, 11588 unsigned NewWidth, bool NewSign, 11589 SourceLocation Loc, unsigned DiagID); 11590 11591 /// Checks that the Objective-C declaration is declared in the global scope. 11592 /// Emits an error and marks the declaration as invalid if it's not declared 11593 /// in the global scope. 11594 bool CheckObjCDeclScope(Decl *D); 11595 11596 /// Abstract base class used for diagnosing integer constant 11597 /// expression violations. 11598 class VerifyICEDiagnoser { 11599 public: 11600 bool Suppress; 11601 Suppress(Suppress)11602 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } 11603 11604 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0; 11605 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR); ~VerifyICEDiagnoser()11606 virtual ~VerifyICEDiagnoser() { } 11607 }; 11608 11609 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, 11610 /// and reports the appropriate diagnostics. Returns false on success. 11611 /// Can optionally return the value of the expression. 11612 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 11613 VerifyICEDiagnoser &Diagnoser, 11614 bool AllowFold = true); 11615 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 11616 unsigned DiagID, 11617 bool AllowFold = true); 11618 ExprResult VerifyIntegerConstantExpression(Expr *E, 11619 llvm::APSInt *Result = nullptr); 11620 11621 /// VerifyBitField - verifies that a bit field expression is an ICE and has 11622 /// the correct width, and that the field type is valid. 11623 /// Returns false on success. 11624 /// Can optionally return whether the bit-field is of width 0 11625 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 11626 QualType FieldTy, bool IsMsStruct, 11627 Expr *BitWidth, bool *ZeroWidth = nullptr); 11628 11629 private: 11630 unsigned ForceCUDAHostDeviceDepth = 0; 11631 11632 public: 11633 /// Increments our count of the number of times we've seen a pragma forcing 11634 /// functions to be __host__ __device__. So long as this count is greater 11635 /// than zero, all functions encountered will be __host__ __device__. 11636 void PushForceCUDAHostDevice(); 11637 11638 /// Decrements our count of the number of times we've seen a pragma forcing 11639 /// functions to be __host__ __device__. Returns false if the count is 0 11640 /// before incrementing, so you can emit an error. 11641 bool PopForceCUDAHostDevice(); 11642 11643 /// Diagnostics that are emitted only if we discover that the given function 11644 /// must be codegen'ed. Because handling these correctly adds overhead to 11645 /// compilation, this is currently only enabled for CUDA compilations. 11646 llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>, 11647 std::vector<PartialDiagnosticAt>> 11648 DeviceDeferredDiags; 11649 11650 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the 11651 /// key in a hashtable, both the FD and location are hashed. 11652 struct FunctionDeclAndLoc { 11653 CanonicalDeclPtr<FunctionDecl> FD; 11654 SourceLocation Loc; 11655 }; 11656 11657 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a 11658 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the 11659 /// same deferred diag twice. 11660 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags; 11661 11662 /// An inverse call graph, mapping known-emitted functions to one of their 11663 /// known-emitted callers (plus the location of the call). 11664 /// 11665 /// Functions that we can tell a priori must be emitted aren't added to this 11666 /// map. 11667 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>, 11668 /* Caller = */ FunctionDeclAndLoc> 11669 DeviceKnownEmittedFns; 11670 11671 /// Diagnostic builder for CUDA/OpenMP devices errors which may or may not be 11672 /// deferred. 11673 /// 11674 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch) 11675 /// which are not allowed to appear inside __device__ functions and are 11676 /// allowed to appear in __host__ __device__ functions only if the host+device 11677 /// function is never codegen'ed. 11678 /// 11679 /// To handle this, we use the notion of "deferred diagnostics", where we 11680 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed. 11681 /// 11682 /// This class lets you emit either a regular diagnostic, a deferred 11683 /// diagnostic, or no diagnostic at all, according to an argument you pass to 11684 /// its constructor, thus simplifying the process of creating these "maybe 11685 /// deferred" diagnostics. 11686 class DeviceDiagBuilder { 11687 public: 11688 enum Kind { 11689 /// Emit no diagnostics. 11690 K_Nop, 11691 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()). 11692 K_Immediate, 11693 /// Emit the diagnostic immediately, and, if it's a warning or error, also 11694 /// emit a call stack showing how this function can be reached by an a 11695 /// priori known-emitted function. 11696 K_ImmediateWithCallStack, 11697 /// Create a deferred diagnostic, which is emitted only if the function 11698 /// it's attached to is codegen'ed. Also emit a call stack as with 11699 /// K_ImmediateWithCallStack. 11700 K_Deferred 11701 }; 11702 11703 DeviceDiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID, 11704 FunctionDecl *Fn, Sema &S); 11705 DeviceDiagBuilder(DeviceDiagBuilder &&D); 11706 DeviceDiagBuilder(const DeviceDiagBuilder &) = default; 11707 ~DeviceDiagBuilder(); 11708 11709 /// Convertible to bool: True if we immediately emitted an error, false if 11710 /// we didn't emit an error or we created a deferred error. 11711 /// 11712 /// Example usage: 11713 /// 11714 /// if (DeviceDiagBuilder(...) << foo << bar) 11715 /// return ExprError(); 11716 /// 11717 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably 11718 /// want to use these instead of creating a DeviceDiagBuilder yourself. 11719 operator bool() const { return ImmediateDiag.hasValue(); } 11720 11721 template <typename T> 11722 friend const DeviceDiagBuilder &operator<<(const DeviceDiagBuilder &Diag, 11723 const T &Value) { 11724 if (Diag.ImmediateDiag.hasValue()) 11725 *Diag.ImmediateDiag << Value; 11726 else if (Diag.PartialDiagId.hasValue()) 11727 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second 11728 << Value; 11729 return Diag; 11730 } 11731 11732 private: 11733 Sema &S; 11734 SourceLocation Loc; 11735 unsigned DiagID; 11736 FunctionDecl *Fn; 11737 bool ShowCallStack; 11738 11739 // Invariant: At most one of these Optionals has a value. 11740 // FIXME: Switch these to a Variant once that exists. 11741 llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag; 11742 llvm::Optional<unsigned> PartialDiagId; 11743 }; 11744 11745 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context 11746 /// is "used as device code". 11747 /// 11748 /// - If CurContext is a __host__ function, does not emit any diagnostics. 11749 /// - If CurContext is a __device__ or __global__ function, emits the 11750 /// diagnostics immediately. 11751 /// - If CurContext is a __host__ __device__ function and we are compiling for 11752 /// the device, creates a diagnostic which is emitted if and when we realize 11753 /// that the function will be codegen'ed. 11754 /// 11755 /// Example usage: 11756 /// 11757 /// // Variable-length arrays are not allowed in CUDA device code. 11758 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget()) 11759 /// return ExprError(); 11760 /// // Otherwise, continue parsing as normal. 11761 DeviceDiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); 11762 11763 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context 11764 /// is "used as host code". 11765 /// 11766 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched. 11767 DeviceDiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID); 11768 11769 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current 11770 /// context is "used as device code". 11771 /// 11772 /// - If CurContext is a `declare target` function or it is known that the 11773 /// function is emitted for the device, emits the diagnostics immediately. 11774 /// - If CurContext is a non-`declare target` function and we are compiling 11775 /// for the device, creates a diagnostic which is emitted if and when we 11776 /// realize that the function will be codegen'ed. 11777 /// 11778 /// Example usage: 11779 /// 11780 /// // Variable-length arrays are not allowed in NVPTX device code. 11781 /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported)) 11782 /// return ExprError(); 11783 /// // Otherwise, continue parsing as normal. 11784 DeviceDiagBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID); 11785 11786 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current 11787 /// context is "used as host code". 11788 /// 11789 /// - If CurContext is a `declare target` function or it is known that the 11790 /// function is emitted for the host, emits the diagnostics immediately. 11791 /// - If CurContext is a non-host function, just ignore it. 11792 /// 11793 /// Example usage: 11794 /// 11795 /// // Variable-length arrays are not allowed in NVPTX device code. 11796 /// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported)) 11797 /// return ExprError(); 11798 /// // Otherwise, continue parsing as normal. 11799 DeviceDiagBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID); 11800 11801 DeviceDiagBuilder targetDiag(SourceLocation Loc, unsigned DiagID); 11802 11803 /// Check if the expression is allowed to be used in expressions for the 11804 /// offloading devices. 11805 void checkDeviceDecl(const ValueDecl *D, SourceLocation Loc); 11806 11807 enum CUDAFunctionTarget { 11808 CFT_Device, 11809 CFT_Global, 11810 CFT_Host, 11811 CFT_HostDevice, 11812 CFT_InvalidTarget 11813 }; 11814 11815 /// Determines whether the given function is a CUDA device/host/kernel/etc. 11816 /// function. 11817 /// 11818 /// Use this rather than examining the function's attributes yourself -- you 11819 /// will get it wrong. Returns CFT_Host if D is null. 11820 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D, 11821 bool IgnoreImplicitHDAttr = false); 11822 CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs); 11823 11824 /// Gets the CUDA target for the current context. CurrentCUDATarget()11825 CUDAFunctionTarget CurrentCUDATarget() { 11826 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext)); 11827 } 11828 11829 static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D); 11830 11831 // CUDA function call preference. Must be ordered numerically from 11832 // worst to best. 11833 enum CUDAFunctionPreference { 11834 CFP_Never, // Invalid caller/callee combination. 11835 CFP_WrongSide, // Calls from host-device to host or device 11836 // function that do not match current compilation 11837 // mode. 11838 CFP_HostDevice, // Any calls to host/device functions. 11839 CFP_SameSide, // Calls from host-device to host or device 11840 // function matching current compilation mode. 11841 CFP_Native, // host-to-host or device-to-device calls. 11842 }; 11843 11844 /// Identifies relative preference of a given Caller/Callee 11845 /// combination, based on their host/device attributes. 11846 /// \param Caller function which needs address of \p Callee. 11847 /// nullptr in case of global context. 11848 /// \param Callee target function 11849 /// 11850 /// \returns preference value for particular Caller/Callee combination. 11851 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller, 11852 const FunctionDecl *Callee); 11853 11854 /// Determines whether Caller may invoke Callee, based on their CUDA 11855 /// host/device attributes. Returns false if the call is not allowed. 11856 /// 11857 /// Note: Will return true for CFP_WrongSide calls. These may appear in 11858 /// semantically correct CUDA programs, but only if they're never codegen'ed. IsAllowedCUDACall(const FunctionDecl * Caller,const FunctionDecl * Callee)11859 bool IsAllowedCUDACall(const FunctionDecl *Caller, 11860 const FunctionDecl *Callee) { 11861 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never; 11862 } 11863 11864 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, 11865 /// depending on FD and the current compilation settings. 11866 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD, 11867 const LookupResult &Previous); 11868 11869 /// May add implicit CUDAConstantAttr attribute to VD, depending on VD 11870 /// and current compilation settings. 11871 void MaybeAddCUDAConstantAttr(VarDecl *VD); 11872 11873 public: 11874 /// Check whether we're allowed to call Callee from the current context. 11875 /// 11876 /// - If the call is never allowed in a semantically-correct program 11877 /// (CFP_Never), emits an error and returns false. 11878 /// 11879 /// - If the call is allowed in semantically-correct programs, but only if 11880 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to 11881 /// be emitted if and when the caller is codegen'ed, and returns true. 11882 /// 11883 /// Will only create deferred diagnostics for a given SourceLocation once, 11884 /// so you can safely call this multiple times without generating duplicate 11885 /// deferred errors. 11886 /// 11887 /// - Otherwise, returns true without emitting any diagnostics. 11888 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee); 11889 11890 void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture); 11891 11892 /// Set __device__ or __host__ __device__ attributes on the given lambda 11893 /// operator() method. 11894 /// 11895 /// CUDA lambdas by default is host device function unless it has explicit 11896 /// host or device attribute. 11897 void CUDASetLambdaAttrs(CXXMethodDecl *Method); 11898 11899 /// Finds a function in \p Matches with highest calling priority 11900 /// from \p Caller context and erases all functions with lower 11901 /// calling priority. 11902 void EraseUnwantedCUDAMatches( 11903 const FunctionDecl *Caller, 11904 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches); 11905 11906 /// Given a implicit special member, infer its CUDA target from the 11907 /// calls it needs to make to underlying base/field special members. 11908 /// \param ClassDecl the class for which the member is being created. 11909 /// \param CSM the kind of special member. 11910 /// \param MemberDecl the special member itself. 11911 /// \param ConstRHS true if this is a copy operation with a const object on 11912 /// its RHS. 11913 /// \param Diagnose true if this call should emit diagnostics. 11914 /// \return true if there was an error inferring. 11915 /// The result of this call is implicit CUDA target attribute(s) attached to 11916 /// the member declaration. 11917 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, 11918 CXXSpecialMember CSM, 11919 CXXMethodDecl *MemberDecl, 11920 bool ConstRHS, 11921 bool Diagnose); 11922 11923 /// \return true if \p CD can be considered empty according to CUDA 11924 /// (E.2.3.1 in CUDA 7.5 Programming guide). 11925 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD); 11926 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD); 11927 11928 // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In 11929 // case of error emits appropriate diagnostic and invalidates \p Var. 11930 // 11931 // \details CUDA allows only empty constructors as initializers for global 11932 // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all 11933 // __shared__ variables whether they are local or not (they all are implicitly 11934 // static in CUDA). One exception is that CUDA allows constant initializers 11935 // for __constant__ and __device__ variables. 11936 void checkAllowedCUDAInitializer(VarDecl *VD); 11937 11938 /// Check whether NewFD is a valid overload for CUDA. Emits 11939 /// diagnostics and invalidates NewFD if not. 11940 void checkCUDATargetOverload(FunctionDecl *NewFD, 11941 const LookupResult &Previous); 11942 /// Copies target attributes from the template TD to the function FD. 11943 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD); 11944 11945 /// Returns the name of the launch configuration function. This is the name 11946 /// of the function that will be called to configure kernel call, with the 11947 /// parameters specified via <<<>>>. 11948 std::string getCudaConfigureFuncName() const; 11949 11950 /// \name Code completion 11951 //@{ 11952 /// Describes the context in which code completion occurs. 11953 enum ParserCompletionContext { 11954 /// Code completion occurs at top-level or namespace context. 11955 PCC_Namespace, 11956 /// Code completion occurs within a class, struct, or union. 11957 PCC_Class, 11958 /// Code completion occurs within an Objective-C interface, protocol, 11959 /// or category. 11960 PCC_ObjCInterface, 11961 /// Code completion occurs within an Objective-C implementation or 11962 /// category implementation 11963 PCC_ObjCImplementation, 11964 /// Code completion occurs within the list of instance variables 11965 /// in an Objective-C interface, protocol, category, or implementation. 11966 PCC_ObjCInstanceVariableList, 11967 /// Code completion occurs following one or more template 11968 /// headers. 11969 PCC_Template, 11970 /// Code completion occurs following one or more template 11971 /// headers within a class. 11972 PCC_MemberTemplate, 11973 /// Code completion occurs within an expression. 11974 PCC_Expression, 11975 /// Code completion occurs within a statement, which may 11976 /// also be an expression or a declaration. 11977 PCC_Statement, 11978 /// Code completion occurs at the beginning of the 11979 /// initialization statement (or expression) in a for loop. 11980 PCC_ForInit, 11981 /// Code completion occurs within the condition of an if, 11982 /// while, switch, or for statement. 11983 PCC_Condition, 11984 /// Code completion occurs within the body of a function on a 11985 /// recovery path, where we do not have a specific handle on our position 11986 /// in the grammar. 11987 PCC_RecoveryInFunction, 11988 /// Code completion occurs where only a type is permitted. 11989 PCC_Type, 11990 /// Code completion occurs in a parenthesized expression, which 11991 /// might also be a type cast. 11992 PCC_ParenthesizedExpression, 11993 /// Code completion occurs within a sequence of declaration 11994 /// specifiers within a function, method, or block. 11995 PCC_LocalDeclarationSpecifiers 11996 }; 11997 11998 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); 11999 void CodeCompleteOrdinaryName(Scope *S, 12000 ParserCompletionContext CompletionContext); 12001 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, 12002 bool AllowNonIdentifiers, 12003 bool AllowNestedNameSpecifiers); 12004 12005 struct CodeCompleteExpressionData; 12006 void CodeCompleteExpression(Scope *S, 12007 const CodeCompleteExpressionData &Data); 12008 void CodeCompleteExpression(Scope *S, QualType PreferredType, 12009 bool IsParenthesized = false); 12010 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase, 12011 SourceLocation OpLoc, bool IsArrow, 12012 bool IsBaseExprStatement, 12013 QualType PreferredType); 12014 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS, 12015 QualType PreferredType); 12016 void CodeCompleteTag(Scope *S, unsigned TagSpec); 12017 void CodeCompleteTypeQualifiers(DeclSpec &DS); 12018 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, 12019 const VirtSpecifiers *VS = nullptr); 12020 void CodeCompleteBracketDeclarator(Scope *S); 12021 void CodeCompleteCase(Scope *S); 12022 /// Reports signatures for a call to CodeCompleteConsumer and returns the 12023 /// preferred type for the current argument. Returned type can be null. 12024 QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args, 12025 SourceLocation OpenParLoc); 12026 QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type, 12027 SourceLocation Loc, 12028 ArrayRef<Expr *> Args, 12029 SourceLocation OpenParLoc); 12030 QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl, 12031 CXXScopeSpec SS, 12032 ParsedType TemplateTypeTy, 12033 ArrayRef<Expr *> ArgExprs, 12034 IdentifierInfo *II, 12035 SourceLocation OpenParLoc); 12036 void CodeCompleteInitializer(Scope *S, Decl *D); 12037 /// Trigger code completion for a record of \p BaseType. \p InitExprs are 12038 /// expressions in the initializer list seen so far and \p D is the current 12039 /// Designation being parsed. 12040 void CodeCompleteDesignator(const QualType BaseType, 12041 llvm::ArrayRef<Expr *> InitExprs, 12042 const Designation &D); 12043 void CodeCompleteAfterIf(Scope *S, bool IsBracedThen); 12044 12045 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext, 12046 bool IsUsingDeclaration, QualType BaseType, 12047 QualType PreferredType); 12048 void CodeCompleteUsing(Scope *S); 12049 void CodeCompleteUsingDirective(Scope *S); 12050 void CodeCompleteNamespaceDecl(Scope *S); 12051 void CodeCompleteNamespaceAliasDecl(Scope *S); 12052 void CodeCompleteOperatorName(Scope *S); 12053 void CodeCompleteConstructorInitializer( 12054 Decl *Constructor, 12055 ArrayRef<CXXCtorInitializer *> Initializers); 12056 12057 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, 12058 bool AfterAmpersand); 12059 void CodeCompleteAfterFunctionEquals(Declarator &D); 12060 12061 void CodeCompleteObjCAtDirective(Scope *S); 12062 void CodeCompleteObjCAtVisibility(Scope *S); 12063 void CodeCompleteObjCAtStatement(Scope *S); 12064 void CodeCompleteObjCAtExpression(Scope *S); 12065 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); 12066 void CodeCompleteObjCPropertyGetter(Scope *S); 12067 void CodeCompleteObjCPropertySetter(Scope *S); 12068 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, 12069 bool IsParameter); 12070 void CodeCompleteObjCMessageReceiver(Scope *S); 12071 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, 12072 ArrayRef<IdentifierInfo *> SelIdents, 12073 bool AtArgumentExpression); 12074 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, 12075 ArrayRef<IdentifierInfo *> SelIdents, 12076 bool AtArgumentExpression, 12077 bool IsSuper = false); 12078 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, 12079 ArrayRef<IdentifierInfo *> SelIdents, 12080 bool AtArgumentExpression, 12081 ObjCInterfaceDecl *Super = nullptr); 12082 void CodeCompleteObjCForCollection(Scope *S, 12083 DeclGroupPtrTy IterationVar); 12084 void CodeCompleteObjCSelector(Scope *S, 12085 ArrayRef<IdentifierInfo *> SelIdents); 12086 void CodeCompleteObjCProtocolReferences( 12087 ArrayRef<IdentifierLocPair> Protocols); 12088 void CodeCompleteObjCProtocolDecl(Scope *S); 12089 void CodeCompleteObjCInterfaceDecl(Scope *S); 12090 void CodeCompleteObjCSuperclass(Scope *S, 12091 IdentifierInfo *ClassName, 12092 SourceLocation ClassNameLoc); 12093 void CodeCompleteObjCImplementationDecl(Scope *S); 12094 void CodeCompleteObjCInterfaceCategory(Scope *S, 12095 IdentifierInfo *ClassName, 12096 SourceLocation ClassNameLoc); 12097 void CodeCompleteObjCImplementationCategory(Scope *S, 12098 IdentifierInfo *ClassName, 12099 SourceLocation ClassNameLoc); 12100 void CodeCompleteObjCPropertyDefinition(Scope *S); 12101 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, 12102 IdentifierInfo *PropertyName); 12103 void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, 12104 ParsedType ReturnType); 12105 void CodeCompleteObjCMethodDeclSelector(Scope *S, 12106 bool IsInstanceMethod, 12107 bool AtParameterName, 12108 ParsedType ReturnType, 12109 ArrayRef<IdentifierInfo *> SelIdents); 12110 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName, 12111 SourceLocation ClassNameLoc, 12112 bool IsBaseExprStatement); 12113 void CodeCompletePreprocessorDirective(bool InConditional); 12114 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); 12115 void CodeCompletePreprocessorMacroName(bool IsDefinition); 12116 void CodeCompletePreprocessorExpression(); 12117 void CodeCompletePreprocessorMacroArgument(Scope *S, 12118 IdentifierInfo *Macro, 12119 MacroInfo *MacroInfo, 12120 unsigned Argument); 12121 void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled); 12122 void CodeCompleteNaturalLanguage(); 12123 void CodeCompleteAvailabilityPlatformName(); 12124 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, 12125 CodeCompletionTUInfo &CCTUInfo, 12126 SmallVectorImpl<CodeCompletionResult> &Results); 12127 //@} 12128 12129 //===--------------------------------------------------------------------===// 12130 // Extra semantic analysis beyond the C type system 12131 12132 public: 12133 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, 12134 unsigned ByteNo) const; 12135 12136 private: 12137 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 12138 const ArraySubscriptExpr *ASE=nullptr, 12139 bool AllowOnePastEnd=true, bool IndexNegated=false); 12140 void CheckArrayAccess(const Expr *E); 12141 // Used to grab the relevant information from a FormatAttr and a 12142 // FunctionDeclaration. 12143 struct FormatStringInfo { 12144 unsigned FormatIdx; 12145 unsigned FirstDataArg; 12146 bool HasVAListArg; 12147 }; 12148 12149 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 12150 FormatStringInfo *FSI); 12151 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 12152 const FunctionProtoType *Proto); 12153 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, 12154 ArrayRef<const Expr *> Args); 12155 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 12156 const FunctionProtoType *Proto); 12157 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto); 12158 void CheckConstructorCall(FunctionDecl *FDecl, 12159 ArrayRef<const Expr *> Args, 12160 const FunctionProtoType *Proto, 12161 SourceLocation Loc); 12162 12163 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 12164 const Expr *ThisArg, ArrayRef<const Expr *> Args, 12165 bool IsMemberFunction, SourceLocation Loc, SourceRange Range, 12166 VariadicCallType CallType); 12167 12168 bool CheckObjCString(Expr *Arg); 12169 ExprResult CheckOSLogFormatStringArg(Expr *Arg); 12170 12171 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, 12172 unsigned BuiltinID, CallExpr *TheCall); 12173 12174 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12175 CallExpr *TheCall); 12176 12177 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall); 12178 12179 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 12180 unsigned MaxWidth); 12181 bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12182 CallExpr *TheCall); 12183 bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 12184 bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 12185 bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12186 CallExpr *TheCall); 12187 bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg, 12188 bool WantCDE); 12189 bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12190 CallExpr *TheCall); 12191 12192 bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12193 CallExpr *TheCall); 12194 bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 12195 bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 12196 bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); 12197 bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12198 CallExpr *TheCall); 12199 bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 12200 CallExpr *TheCall); 12201 bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); 12202 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 12203 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall); 12204 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall); 12205 bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall); 12206 bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 12207 ArrayRef<int> ArgNums); 12208 bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, int ArgNum); 12209 bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums); 12210 bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 12211 ArrayRef<int> ArgNums); 12212 bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12213 CallExpr *TheCall); 12214 bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12215 CallExpr *TheCall); 12216 bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 12217 12218 bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall); 12219 bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call); 12220 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); 12221 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); 12222 bool SemaBuiltinVSX(CallExpr *TheCall); 12223 bool SemaBuiltinOSLogFormat(CallExpr *TheCall); 12224 12225 public: 12226 // Used by C++ template instantiation. 12227 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); 12228 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 12229 SourceLocation BuiltinLoc, 12230 SourceLocation RParenLoc); 12231 12232 private: 12233 bool SemaBuiltinPrefetch(CallExpr *TheCall); 12234 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall); 12235 bool SemaBuiltinAssume(CallExpr *TheCall); 12236 bool SemaBuiltinAssumeAligned(CallExpr *TheCall); 12237 bool SemaBuiltinLongjmp(CallExpr *TheCall); 12238 bool SemaBuiltinSetjmp(CallExpr *TheCall); 12239 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); 12240 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult); 12241 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, 12242 AtomicExpr::AtomicOp Op); 12243 ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, 12244 bool IsDelete); 12245 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 12246 llvm::APSInt &Result); 12247 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, 12248 int High, bool RangeIsError = true); 12249 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 12250 unsigned Multiple); 12251 bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum); 12252 bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 12253 unsigned ArgBits); 12254 bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum, 12255 unsigned ArgBits); 12256 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 12257 int ArgNum, unsigned ExpectedFieldNum, 12258 bool AllowName); 12259 bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall); 12260 12261 // Matrix builtin handling. 12262 ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall, 12263 ExprResult CallResult); 12264 ExprResult SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 12265 ExprResult CallResult); 12266 ExprResult SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 12267 ExprResult CallResult); 12268 12269 public: 12270 enum FormatStringType { 12271 FST_Scanf, 12272 FST_Printf, 12273 FST_NSString, 12274 FST_Strftime, 12275 FST_Strfmon, 12276 FST_Kprintf, 12277 FST_FreeBSDKPrintf, 12278 FST_OSTrace, 12279 FST_OSLog, 12280 FST_Unknown 12281 }; 12282 static FormatStringType GetFormatStringType(const FormatAttr *Format); 12283 12284 bool FormatStringHasSArg(const StringLiteral *FExpr); 12285 12286 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx); 12287 12288 private: 12289 bool CheckFormatArguments(const FormatAttr *Format, 12290 ArrayRef<const Expr *> Args, 12291 bool IsCXXMember, 12292 VariadicCallType CallType, 12293 SourceLocation Loc, SourceRange Range, 12294 llvm::SmallBitVector &CheckedVarArgs); 12295 bool CheckFormatArguments(ArrayRef<const Expr *> Args, 12296 bool HasVAListArg, unsigned format_idx, 12297 unsigned firstDataArg, FormatStringType Type, 12298 VariadicCallType CallType, 12299 SourceLocation Loc, SourceRange range, 12300 llvm::SmallBitVector &CheckedVarArgs); 12301 12302 void CheckAbsoluteValueFunction(const CallExpr *Call, 12303 const FunctionDecl *FDecl); 12304 12305 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl); 12306 12307 void CheckMemaccessArguments(const CallExpr *Call, 12308 unsigned BId, 12309 IdentifierInfo *FnName); 12310 12311 void CheckStrlcpycatArguments(const CallExpr *Call, 12312 IdentifierInfo *FnName); 12313 12314 void CheckStrncatArguments(const CallExpr *Call, 12315 IdentifierInfo *FnName); 12316 12317 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 12318 SourceLocation ReturnLoc, 12319 bool isObjCMethod = false, 12320 const AttrVec *Attrs = nullptr, 12321 const FunctionDecl *FD = nullptr); 12322 12323 public: 12324 void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS); 12325 12326 private: 12327 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); 12328 void CheckBoolLikeConversion(Expr *E, SourceLocation CC); 12329 void CheckForIntOverflow(Expr *E); 12330 void CheckUnsequencedOperations(const Expr *E); 12331 12332 /// Perform semantic checks on a completed expression. This will either 12333 /// be a full-expression or a default argument expression. 12334 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(), 12335 bool IsConstexpr = false); 12336 12337 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, 12338 Expr *Init); 12339 12340 /// Check if there is a field shadowing. 12341 void CheckShadowInheritedFields(const SourceLocation &Loc, 12342 DeclarationName FieldName, 12343 const CXXRecordDecl *RD, 12344 bool DeclIsField = true); 12345 12346 /// Check if the given expression contains 'break' or 'continue' 12347 /// statement that produces control flow different from GCC. 12348 void CheckBreakContinueBinding(Expr *E); 12349 12350 /// Check whether receiver is mutable ObjC container which 12351 /// attempts to add itself into the container 12352 void CheckObjCCircularContainer(ObjCMessageExpr *Message); 12353 12354 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE); 12355 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, 12356 bool DeleteWasArrayForm); 12357 public: 12358 /// Register a magic integral constant to be used as a type tag. 12359 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 12360 uint64_t MagicValue, QualType Type, 12361 bool LayoutCompatible, bool MustBeNull); 12362 12363 struct TypeTagData { TypeTagDataTypeTagData12364 TypeTagData() {} 12365 TypeTagDataTypeTagData12366 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) : 12367 Type(Type), LayoutCompatible(LayoutCompatible), 12368 MustBeNull(MustBeNull) 12369 {} 12370 12371 QualType Type; 12372 12373 /// If true, \c Type should be compared with other expression's types for 12374 /// layout-compatibility. 12375 unsigned LayoutCompatible : 1; 12376 unsigned MustBeNull : 1; 12377 }; 12378 12379 /// A pair of ArgumentKind identifier and magic value. This uniquely 12380 /// identifies the magic value. 12381 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; 12382 12383 private: 12384 /// A map from magic value to type information. 12385 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>> 12386 TypeTagForDatatypeMagicValues; 12387 12388 /// Peform checks on a call of a function with argument_with_type_tag 12389 /// or pointer_with_type_tag attributes. 12390 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 12391 const ArrayRef<const Expr *> ExprArgs, 12392 SourceLocation CallSiteLoc); 12393 12394 /// Check if we are taking the address of a packed field 12395 /// as this may be a problem if the pointer value is dereferenced. 12396 void CheckAddressOfPackedMember(Expr *rhs); 12397 12398 /// The parser's current scope. 12399 /// 12400 /// The parser maintains this state here. 12401 Scope *CurScope; 12402 12403 mutable IdentifierInfo *Ident_super; 12404 mutable IdentifierInfo *Ident___float128; 12405 12406 /// Nullability type specifiers. 12407 IdentifierInfo *Ident__Nonnull = nullptr; 12408 IdentifierInfo *Ident__Nullable = nullptr; 12409 IdentifierInfo *Ident__Null_unspecified = nullptr; 12410 12411 IdentifierInfo *Ident_NSError = nullptr; 12412 12413 /// The handler for the FileChanged preprocessor events. 12414 /// 12415 /// Used for diagnostics that implement custom semantic analysis for #include 12416 /// directives, like -Wpragma-pack. 12417 sema::SemaPPCallbacks *SemaPPCallbackHandler; 12418 12419 protected: 12420 friend class Parser; 12421 friend class InitializationSequence; 12422 friend class ASTReader; 12423 friend class ASTDeclReader; 12424 friend class ASTWriter; 12425 12426 public: 12427 /// Retrieve the keyword associated 12428 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability); 12429 12430 /// The struct behind the CFErrorRef pointer. 12431 RecordDecl *CFError = nullptr; 12432 12433 /// Retrieve the identifier "NSError". 12434 IdentifierInfo *getNSErrorIdent(); 12435 12436 /// Retrieve the parser's current scope. 12437 /// 12438 /// This routine must only be used when it is certain that semantic analysis 12439 /// and the parser are in precisely the same context, which is not the case 12440 /// when, e.g., we are performing any kind of template instantiation. 12441 /// Therefore, the only safe places to use this scope are in the parser 12442 /// itself and in routines directly invoked from the parser and *never* from 12443 /// template substitution or instantiation. getCurScope()12444 Scope *getCurScope() const { return CurScope; } 12445 incrementMSManglingNumber()12446 void incrementMSManglingNumber() const { 12447 return CurScope->incrementMSManglingNumber(); 12448 } 12449 12450 IdentifierInfo *getSuperIdentifier() const; 12451 IdentifierInfo *getFloat128Identifier() const; 12452 12453 Decl *getObjCDeclContext() const; 12454 getCurLexicalContext()12455 DeclContext *getCurLexicalContext() const { 12456 return OriginalLexicalContext ? OriginalLexicalContext : CurContext; 12457 } 12458 getCurObjCLexicalContext()12459 const DeclContext *getCurObjCLexicalContext() const { 12460 const DeclContext *DC = getCurLexicalContext(); 12461 // A category implicitly has the attribute of the interface. 12462 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC)) 12463 DC = CatD->getClassInterface(); 12464 return DC; 12465 } 12466 12467 /// Determine the number of levels of enclosing template parameters. This is 12468 /// only usable while parsing. Note that this does not include dependent 12469 /// contexts in which no template parameters have yet been declared, such as 12470 /// in a terse function template or generic lambda before the first 'auto' is 12471 /// encountered. 12472 unsigned getTemplateDepth(Scope *S) const; 12473 12474 /// To be used for checking whether the arguments being passed to 12475 /// function exceeds the number of parameters expected for it. 12476 static bool TooManyArguments(size_t NumParams, size_t NumArgs, 12477 bool PartialOverloading = false) { 12478 // We check whether we're just after a comma in code-completion. 12479 if (NumArgs > 0 && PartialOverloading) 12480 return NumArgs + 1 > NumParams; // If so, we view as an extra argument. 12481 return NumArgs > NumParams; 12482 } 12483 12484 // Emitting members of dllexported classes is delayed until the class 12485 // (including field initializers) is fully parsed. 12486 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses; 12487 SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions; 12488 12489 private: 12490 int ParsingClassDepth = 0; 12491 12492 class SavePendingParsedClassStateRAII { 12493 public: SavePendingParsedClassStateRAII(Sema & S)12494 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); } 12495 ~SavePendingParsedClassStateRAII()12496 ~SavePendingParsedClassStateRAII() { 12497 assert(S.DelayedOverridingExceptionSpecChecks.empty() && 12498 "there shouldn't be any pending delayed exception spec checks"); 12499 assert(S.DelayedEquivalentExceptionSpecChecks.empty() && 12500 "there shouldn't be any pending delayed exception spec checks"); 12501 swapSavedState(); 12502 } 12503 12504 private: 12505 Sema &S; 12506 decltype(DelayedOverridingExceptionSpecChecks) 12507 SavedOverridingExceptionSpecChecks; 12508 decltype(DelayedEquivalentExceptionSpecChecks) 12509 SavedEquivalentExceptionSpecChecks; 12510 swapSavedState()12511 void swapSavedState() { 12512 SavedOverridingExceptionSpecChecks.swap( 12513 S.DelayedOverridingExceptionSpecChecks); 12514 SavedEquivalentExceptionSpecChecks.swap( 12515 S.DelayedEquivalentExceptionSpecChecks); 12516 } 12517 }; 12518 12519 /// Helper class that collects misaligned member designations and 12520 /// their location info for delayed diagnostics. 12521 struct MisalignedMember { 12522 Expr *E; 12523 RecordDecl *RD; 12524 ValueDecl *MD; 12525 CharUnits Alignment; 12526 MisalignedMemberMisalignedMember12527 MisalignedMember() : E(), RD(), MD(), Alignment() {} MisalignedMemberMisalignedMember12528 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD, 12529 CharUnits Alignment) 12530 : E(E), RD(RD), MD(MD), Alignment(Alignment) {} MisalignedMemberMisalignedMember12531 explicit MisalignedMember(Expr *E) 12532 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {} 12533 12534 bool operator==(const MisalignedMember &m) { return this->E == m.E; } 12535 }; 12536 /// Small set of gathered accesses to potentially misaligned members 12537 /// due to the packed attribute. 12538 SmallVector<MisalignedMember, 4> MisalignedMembers; 12539 12540 /// Adds an expression to the set of gathered misaligned members. 12541 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 12542 CharUnits Alignment); 12543 12544 public: 12545 /// Diagnoses the current set of gathered accesses. This typically 12546 /// happens at full expression level. The set is cleared after emitting the 12547 /// diagnostics. 12548 void DiagnoseMisalignedMembers(); 12549 12550 /// This function checks if the expression is in the sef of potentially 12551 /// misaligned members and it is converted to some pointer type T with lower 12552 /// or equal alignment requirements. If so it removes it. This is used when 12553 /// we do not want to diagnose such misaligned access (e.g. in conversions to 12554 /// void*). 12555 void DiscardMisalignedMemberAddress(const Type *T, Expr *E); 12556 12557 /// This function calls Action when it determines that E designates a 12558 /// misaligned member due to the packed attribute. This is used to emit 12559 /// local diagnostics like in reference binding. 12560 void RefersToMemberWithReducedAlignment( 12561 Expr *E, 12562 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 12563 Action); 12564 12565 /// Describes the reason a calling convention specification was ignored, used 12566 /// for diagnostics. 12567 enum class CallingConventionIgnoredReason { 12568 ForThisTarget = 0, 12569 VariadicFunction, 12570 ConstructorDestructor, 12571 BuiltinFunction 12572 }; 12573 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current 12574 /// context is "used as device code". 12575 /// 12576 /// - If CurLexicalContext is a kernel function or it is known that the 12577 /// function will be emitted for the device, emits the diagnostics 12578 /// immediately. 12579 /// - If CurLexicalContext is a function and we are compiling 12580 /// for the device, but we don't know that this function will be codegen'ed 12581 /// for devive yet, creates a diagnostic which is emitted if and when we 12582 /// realize that the function will be codegen'ed. 12583 /// 12584 /// Example usage: 12585 /// 12586 /// Diagnose __float128 type usage only from SYCL device code if the current 12587 /// target doesn't support it 12588 /// if (!S.Context.getTargetInfo().hasFloat128Type() && 12589 /// S.getLangOpts().SYCLIsDevice) 12590 /// SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128"; 12591 DeviceDiagBuilder SYCLDiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); 12592 12593 /// Check whether we're allowed to call Callee from the current context. 12594 /// 12595 /// - If the call is never allowed in a semantically-correct program 12596 /// emits an error and returns false. 12597 /// 12598 /// - If the call is allowed in semantically-correct programs, but only if 12599 /// it's never codegen'ed, creates a deferred diagnostic to be emitted if 12600 /// and when the caller is codegen'ed, and returns true. 12601 /// 12602 /// - Otherwise, returns true without emitting any diagnostics. 12603 /// 12604 /// Adds Callee to DeviceCallGraph if we don't know if its caller will be 12605 /// codegen'ed yet. 12606 bool checkSYCLDeviceFunction(SourceLocation Loc, FunctionDecl *Callee); 12607 }; 12608 12609 /// RAII object that enters a new expression evaluation context. 12610 class EnterExpressionEvaluationContext { 12611 Sema &Actions; 12612 bool Entered = true; 12613 12614 public: 12615 EnterExpressionEvaluationContext( 12616 Sema &Actions, Sema::ExpressionEvaluationContext NewContext, 12617 Decl *LambdaContextDecl = nullptr, 12618 Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = 12619 Sema::ExpressionEvaluationContextRecord::EK_Other, 12620 bool ShouldEnter = true) Actions(Actions)12621 : Actions(Actions), Entered(ShouldEnter) { 12622 if (Entered) 12623 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, 12624 ExprContext); 12625 } 12626 EnterExpressionEvaluationContext( 12627 Sema &Actions, Sema::ExpressionEvaluationContext NewContext, 12628 Sema::ReuseLambdaContextDecl_t, 12629 Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = 12630 Sema::ExpressionEvaluationContextRecord::EK_Other) Actions(Actions)12631 : Actions(Actions) { 12632 Actions.PushExpressionEvaluationContext( 12633 NewContext, Sema::ReuseLambdaContextDecl, ExprContext); 12634 } 12635 12636 enum InitListTag { InitList }; 12637 EnterExpressionEvaluationContext(Sema &Actions, InitListTag, 12638 bool ShouldEnter = true) Actions(Actions)12639 : Actions(Actions), Entered(false) { 12640 // In C++11 onwards, narrowing checks are performed on the contents of 12641 // braced-init-lists, even when they occur within unevaluated operands. 12642 // Therefore we still need to instantiate constexpr functions used in such 12643 // a context. 12644 if (ShouldEnter && Actions.isUnevaluatedContext() && 12645 Actions.getLangOpts().CPlusPlus11) { 12646 Actions.PushExpressionEvaluationContext( 12647 Sema::ExpressionEvaluationContext::UnevaluatedList); 12648 Entered = true; 12649 } 12650 } 12651 ~EnterExpressionEvaluationContext()12652 ~EnterExpressionEvaluationContext() { 12653 if (Entered) 12654 Actions.PopExpressionEvaluationContext(); 12655 } 12656 }; 12657 12658 DeductionFailureInfo 12659 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, 12660 sema::TemplateDeductionInfo &Info); 12661 12662 /// Contains a late templated function. 12663 /// Will be parsed at the end of the translation unit, used by Sema & Parser. 12664 struct LateParsedTemplate { 12665 CachedTokens Toks; 12666 /// The template function declaration to be late parsed. 12667 Decl *D; 12668 }; 12669 } // end namespace clang 12670 12671 namespace llvm { 12672 // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its 12673 // SourceLocation. 12674 template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> { 12675 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc; 12676 using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>; 12677 12678 static FunctionDeclAndLoc getEmptyKey() { 12679 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()}; 12680 } 12681 12682 static FunctionDeclAndLoc getTombstoneKey() { 12683 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()}; 12684 } 12685 12686 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) { 12687 return hash_combine(FDBaseInfo::getHashValue(FDL.FD), 12688 FDL.Loc.getRawEncoding()); 12689 } 12690 12691 static bool isEqual(const FunctionDeclAndLoc &LHS, 12692 const FunctionDeclAndLoc &RHS) { 12693 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc; 12694 } 12695 }; 12696 } // namespace llvm 12697 12698 #endif 12699