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 460 PragmaClangSection PragmaClangBSSSection; 461 PragmaClangSection PragmaClangDataSection; 462 PragmaClangSection PragmaClangRodataSection; 463 PragmaClangSection PragmaClangRelroSection; 464 PragmaClangSection PragmaClangTextSection; 465 466 enum PragmaMsStackAction { 467 PSK_Reset = 0x0, // #pragma () 468 PSK_Set = 0x1, // #pragma (value) 469 PSK_Push = 0x2, // #pragma (push[, id]) 470 PSK_Pop = 0x4, // #pragma (pop[, id]) 471 PSK_Show = 0x8, // #pragma (show) -- only for "pack"! 472 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value) 473 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value) 474 }; 475 476 template<typename ValueType> 477 struct PragmaStack { 478 struct Slot { 479 llvm::StringRef StackSlotLabel; 480 ValueType Value; 481 SourceLocation PragmaLocation; 482 SourceLocation PragmaPushLocation; SlotPragmaStack::Slot483 Slot(llvm::StringRef StackSlotLabel, ValueType Value, 484 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation) 485 : StackSlotLabel(StackSlotLabel), Value(Value), 486 PragmaLocation(PragmaLocation), 487 PragmaPushLocation(PragmaPushLocation) {} 488 }; 489 ActPragmaStack490 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, 491 llvm::StringRef StackSlotLabel, ValueType Value) { 492 if (Action == PSK_Reset) { 493 CurrentValue = DefaultValue; 494 CurrentPragmaLocation = PragmaLocation; 495 return; 496 } 497 if (Action & PSK_Push) 498 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation, 499 PragmaLocation); 500 else if (Action & PSK_Pop) { 501 if (!StackSlotLabel.empty()) { 502 // If we've got a label, try to find it and jump there. 503 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) { 504 return x.StackSlotLabel == StackSlotLabel; 505 }); 506 // If we found the label so pop from there. 507 if (I != Stack.rend()) { 508 CurrentValue = I->Value; 509 CurrentPragmaLocation = I->PragmaLocation; 510 Stack.erase(std::prev(I.base()), Stack.end()); 511 } 512 } else if (!Stack.empty()) { 513 // We do not have a label, just pop the last entry. 514 CurrentValue = Stack.back().Value; 515 CurrentPragmaLocation = Stack.back().PragmaLocation; 516 Stack.pop_back(); 517 } 518 } 519 if (Action & PSK_Set) { 520 CurrentValue = Value; 521 CurrentPragmaLocation = PragmaLocation; 522 } 523 } 524 525 // MSVC seems to add artificial slots to #pragma stacks on entering a C++ 526 // method body to restore the stacks on exit, so it works like this: 527 // 528 // struct S { 529 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>) 530 // void Method {} 531 // #pragma <name>(pop, InternalPragmaSlot) 532 // }; 533 // 534 // It works even with #pragma vtordisp, although MSVC doesn't support 535 // #pragma vtordisp(push [, id], n) 536 // syntax. 537 // 538 // Push / pop a named sentinel slot. SentinelActionPragmaStack539 void SentinelAction(PragmaMsStackAction Action, StringRef Label) { 540 assert((Action == PSK_Push || Action == PSK_Pop) && 541 "Can only push / pop #pragma stack sentinels!"); 542 Act(CurrentPragmaLocation, Action, Label, CurrentValue); 543 } 544 545 // Constructors. PragmaStackPragmaStack546 explicit PragmaStack(const ValueType &Default) 547 : DefaultValue(Default), CurrentValue(Default) {} 548 hasValuePragmaStack549 bool hasValue() const { return CurrentValue != DefaultValue; } 550 551 SmallVector<Slot, 2> Stack; 552 ValueType DefaultValue; // Value used for PSK_Reset action. 553 ValueType CurrentValue; 554 SourceLocation CurrentPragmaLocation; 555 }; 556 // FIXME: We should serialize / deserialize these if they occur in a PCH (but 557 // we shouldn't do so if they're in a module). 558 559 /// Whether to insert vtordisps prior to virtual bases in the Microsoft 560 /// C++ ABI. Possible values are 0, 1, and 2, which mean: 561 /// 562 /// 0: Suppress all vtordisps 563 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial 564 /// structors 565 /// 2: Always insert vtordisps to support RTTI on partially constructed 566 /// objects 567 PragmaStack<MSVtorDispMode> VtorDispStack; 568 // #pragma pack. 569 // Sentinel to represent when the stack is set to mac68k alignment. 570 static const unsigned kMac68kAlignmentSentinel = ~0U; 571 PragmaStack<unsigned> PackStack; 572 // The current #pragma pack values and locations at each #include. 573 struct PackIncludeState { 574 unsigned CurrentValue; 575 SourceLocation CurrentPragmaLocation; 576 bool HasNonDefaultValue, ShouldWarnOnInclude; 577 }; 578 SmallVector<PackIncludeState, 8> PackIncludeStack; 579 // Segment #pragmas. 580 PragmaStack<StringLiteral *> DataSegStack; 581 PragmaStack<StringLiteral *> BSSSegStack; 582 PragmaStack<StringLiteral *> ConstSegStack; 583 PragmaStack<StringLiteral *> CodeSegStack; 584 585 // This stack tracks the current state of Sema.CurFPFeatures. 586 PragmaStack<FPOptionsOverride> FpPragmaStack; CurFPFeatureOverrides()587 FPOptionsOverride CurFPFeatureOverrides() { 588 FPOptionsOverride result; 589 if (!FpPragmaStack.hasValue()) { 590 result = FPOptionsOverride(); 591 } else { 592 result = FpPragmaStack.CurrentValue; 593 } 594 return result; 595 } 596 597 // RAII object to push / pop sentinel slots for all MS #pragma stacks. 598 // Actions should be performed only if we enter / exit a C++ method body. 599 class PragmaStackSentinelRAII { 600 public: 601 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct); 602 ~PragmaStackSentinelRAII(); 603 604 private: 605 Sema &S; 606 StringRef SlotLabel; 607 bool ShouldAct; 608 }; 609 610 /// A mapping that describes the nullability we've seen in each header file. 611 FileNullabilityMap NullabilityMap; 612 613 /// Last section used with #pragma init_seg. 614 StringLiteral *CurInitSeg; 615 SourceLocation CurInitSegLoc; 616 617 /// VisContext - Manages the stack for \#pragma GCC visibility. 618 void *VisContext; // Really a "PragmaVisStack*" 619 620 /// This an attribute introduced by \#pragma clang attribute. 621 struct PragmaAttributeEntry { 622 SourceLocation Loc; 623 ParsedAttr *Attribute; 624 SmallVector<attr::SubjectMatchRule, 4> MatchRules; 625 bool IsUsed; 626 }; 627 628 /// A push'd group of PragmaAttributeEntries. 629 struct PragmaAttributeGroup { 630 /// The location of the push attribute. 631 SourceLocation Loc; 632 /// The namespace of this push group. 633 const IdentifierInfo *Namespace; 634 SmallVector<PragmaAttributeEntry, 2> Entries; 635 }; 636 637 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack; 638 639 /// The declaration that is currently receiving an attribute from the 640 /// #pragma attribute stack. 641 const Decl *PragmaAttributeCurrentTargetDecl; 642 643 /// This represents the last location of a "#pragma clang optimize off" 644 /// directive if such a directive has not been closed by an "on" yet. If 645 /// optimizations are currently "on", this is set to an invalid location. 646 SourceLocation OptimizeOffPragmaLocation; 647 648 /// Flag indicating if Sema is building a recovery call expression. 649 /// 650 /// This flag is used to avoid building recovery call expressions 651 /// if Sema is already doing so, which would cause infinite recursions. 652 bool IsBuildingRecoveryCallExpr; 653 654 /// Used to control the generation of ExprWithCleanups. 655 CleanupInfo Cleanup; 656 657 /// ExprCleanupObjects - This is the stack of objects requiring 658 /// cleanup that are created by the current full expression. 659 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects; 660 661 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference 662 /// to a variable (constant) that may or may not be odr-used in this Expr, and 663 /// we won't know until all lvalue-to-rvalue and discarded value conversions 664 /// have been applied to all subexpressions of the enclosing full expression. 665 /// This is cleared at the end of each full expression. 666 using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>, 667 llvm::SmallPtrSet<Expr *, 4>>; 668 MaybeODRUseExprSet MaybeODRUseExprs; 669 670 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope; 671 672 /// Stack containing information about each of the nested 673 /// function, block, and method scopes that are currently active. 674 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; 675 676 /// The index of the first FunctionScope that corresponds to the current 677 /// context. 678 unsigned FunctionScopesStart = 0; 679 getFunctionScopes()680 ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const { 681 return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart, 682 FunctionScopes.end()); 683 } 684 685 /// Stack containing information needed when in C++2a an 'auto' is encountered 686 /// in a function declaration parameter type specifier in order to invent a 687 /// corresponding template parameter in the enclosing abbreviated function 688 /// template. This information is also present in LambdaScopeInfo, stored in 689 /// the FunctionScopes stack. 690 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos; 691 692 /// The index of the first InventedParameterInfo that refers to the current 693 /// context. 694 unsigned InventedParameterInfosStart = 0; 695 getInventedParameterInfos()696 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const { 697 return llvm::makeArrayRef(InventedParameterInfos.begin() + 698 InventedParameterInfosStart, 699 InventedParameterInfos.end()); 700 } 701 702 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, 703 &ExternalSemaSource::ReadExtVectorDecls, 2, 2> 704 ExtVectorDeclsType; 705 706 /// ExtVectorDecls - This is a list all the extended vector types. This allows 707 /// us to associate a raw vector type with one of the ext_vector type names. 708 /// This is only necessary for issuing pretty diagnostics. 709 ExtVectorDeclsType ExtVectorDecls; 710 711 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. 712 std::unique_ptr<CXXFieldCollector> FieldCollector; 713 714 typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType; 715 716 /// Set containing all declared private fields that are not used. 717 NamedDeclSetType UnusedPrivateFields; 718 719 /// Set containing all typedefs that are likely unused. 720 llvm::SmallSetVector<const TypedefNameDecl *, 4> 721 UnusedLocalTypedefNameCandidates; 722 723 /// Delete-expressions to be analyzed at the end of translation unit 724 /// 725 /// This list contains class members, and locations of delete-expressions 726 /// that could not be proven as to whether they mismatch with new-expression 727 /// used in initializer of the field. 728 typedef std::pair<SourceLocation, bool> DeleteExprLoc; 729 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs; 730 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs; 731 732 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; 733 734 /// PureVirtualClassDiagSet - a set of class declarations which we have 735 /// emitted a list of pure virtual functions. Used to prevent emitting the 736 /// same list more than once. 737 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet; 738 739 /// ParsingInitForAutoVars - a set of declarations with auto types for which 740 /// we are currently parsing the initializer. 741 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; 742 743 /// Look for a locally scoped extern "C" declaration by the given name. 744 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name); 745 746 typedef LazyVector<VarDecl *, ExternalSemaSource, 747 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> 748 TentativeDefinitionsType; 749 750 /// All the tentative definitions encountered in the TU. 751 TentativeDefinitionsType TentativeDefinitions; 752 753 /// All the external declarations encoutered and used in the TU. 754 SmallVector<VarDecl *, 4> ExternalDeclarations; 755 756 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, 757 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> 758 UnusedFileScopedDeclsType; 759 760 /// The set of file scoped decls seen so far that have not been used 761 /// and must warn if not used. Only contains the first declaration. 762 UnusedFileScopedDeclsType UnusedFileScopedDecls; 763 764 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, 765 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> 766 DelegatingCtorDeclsType; 767 768 /// All the delegating constructors seen so far in the file, used for 769 /// cycle detection at the end of the TU. 770 DelegatingCtorDeclsType DelegatingCtorDecls; 771 772 /// All the overriding functions seen during a class definition 773 /// that had their exception spec checks delayed, plus the overridden 774 /// function. 775 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2> 776 DelayedOverridingExceptionSpecChecks; 777 778 /// All the function redeclarations seen during a class definition that had 779 /// their exception spec checks delayed, plus the prior declaration they 780 /// should be checked against. Except during error recovery, the new decl 781 /// should always be a friend declaration, as that's the only valid way to 782 /// redeclare a special member before its class is complete. 783 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2> 784 DelayedEquivalentExceptionSpecChecks; 785 786 typedef llvm::MapVector<const FunctionDecl *, 787 std::unique_ptr<LateParsedTemplate>> 788 LateParsedTemplateMapT; 789 LateParsedTemplateMapT LateParsedTemplateMap; 790 791 /// Callback to the parser to parse templated functions when needed. 792 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT); 793 typedef void LateTemplateParserCleanupCB(void *P); 794 LateTemplateParserCB *LateTemplateParser; 795 LateTemplateParserCleanupCB *LateTemplateParserCleanup; 796 void *OpaqueParser; 797 SetLateTemplateParser(LateTemplateParserCB * LTP,LateTemplateParserCleanupCB * LTPCleanup,void * P)798 void SetLateTemplateParser(LateTemplateParserCB *LTP, 799 LateTemplateParserCleanupCB *LTPCleanup, 800 void *P) { 801 LateTemplateParser = LTP; 802 LateTemplateParserCleanup = LTPCleanup; 803 OpaqueParser = P; 804 } 805 806 class DelayedDiagnostics; 807 808 class DelayedDiagnosticsState { 809 sema::DelayedDiagnosticPool *SavedPool; 810 friend class Sema::DelayedDiagnostics; 811 }; 812 typedef DelayedDiagnosticsState ParsingDeclState; 813 typedef DelayedDiagnosticsState ProcessingContextState; 814 815 /// A class which encapsulates the logic for delaying diagnostics 816 /// during parsing and other processing. 817 class DelayedDiagnostics { 818 /// The current pool of diagnostics into which delayed 819 /// diagnostics should go. 820 sema::DelayedDiagnosticPool *CurPool; 821 822 public: DelayedDiagnostics()823 DelayedDiagnostics() : CurPool(nullptr) {} 824 825 /// Adds a delayed diagnostic. 826 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h 827 828 /// Determines whether diagnostics should be delayed. shouldDelayDiagnostics()829 bool shouldDelayDiagnostics() { return CurPool != nullptr; } 830 831 /// Returns the current delayed-diagnostics pool. getCurrentPool()832 sema::DelayedDiagnosticPool *getCurrentPool() const { 833 return CurPool; 834 } 835 836 /// Enter a new scope. Access and deprecation diagnostics will be 837 /// collected in this pool. push(sema::DelayedDiagnosticPool & pool)838 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { 839 DelayedDiagnosticsState state; 840 state.SavedPool = CurPool; 841 CurPool = &pool; 842 return state; 843 } 844 845 /// Leave a delayed-diagnostic state that was previously pushed. 846 /// Do not emit any of the diagnostics. This is performed as part 847 /// of the bookkeeping of popping a pool "properly". popWithoutEmitting(DelayedDiagnosticsState state)848 void popWithoutEmitting(DelayedDiagnosticsState state) { 849 CurPool = state.SavedPool; 850 } 851 852 /// Enter a new scope where access and deprecation diagnostics are 853 /// not delayed. pushUndelayed()854 DelayedDiagnosticsState pushUndelayed() { 855 DelayedDiagnosticsState state; 856 state.SavedPool = CurPool; 857 CurPool = nullptr; 858 return state; 859 } 860 861 /// Undo a previous pushUndelayed(). popUndelayed(DelayedDiagnosticsState state)862 void popUndelayed(DelayedDiagnosticsState state) { 863 assert(CurPool == nullptr); 864 CurPool = state.SavedPool; 865 } 866 } DelayedDiagnostics; 867 868 /// A RAII object to temporarily push a declaration context. 869 class ContextRAII { 870 private: 871 Sema &S; 872 DeclContext *SavedContext; 873 ProcessingContextState SavedContextState; 874 QualType SavedCXXThisTypeOverride; 875 unsigned SavedFunctionScopesStart; 876 unsigned SavedInventedParameterInfosStart; 877 878 public: 879 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) S(S)880 : S(S), SavedContext(S.CurContext), 881 SavedContextState(S.DelayedDiagnostics.pushUndelayed()), 882 SavedCXXThisTypeOverride(S.CXXThisTypeOverride), 883 SavedFunctionScopesStart(S.FunctionScopesStart), 884 SavedInventedParameterInfosStart(S.InventedParameterInfosStart) 885 { 886 assert(ContextToPush && "pushing null context"); 887 S.CurContext = ContextToPush; 888 if (NewThisContext) 889 S.CXXThisTypeOverride = QualType(); 890 // Any saved FunctionScopes do not refer to this context. 891 S.FunctionScopesStart = S.FunctionScopes.size(); 892 S.InventedParameterInfosStart = S.InventedParameterInfos.size(); 893 } 894 pop()895 void pop() { 896 if (!SavedContext) return; 897 S.CurContext = SavedContext; 898 S.DelayedDiagnostics.popUndelayed(SavedContextState); 899 S.CXXThisTypeOverride = SavedCXXThisTypeOverride; 900 S.FunctionScopesStart = SavedFunctionScopesStart; 901 S.InventedParameterInfosStart = SavedInventedParameterInfosStart; 902 SavedContext = nullptr; 903 } 904 ~ContextRAII()905 ~ContextRAII() { 906 pop(); 907 } 908 }; 909 910 /// Whether the AST is currently being rebuilt to correct immediate 911 /// invocations. Immediate invocation candidates and references to consteval 912 /// functions aren't tracked when this is set. 913 bool RebuildingImmediateInvocation = false; 914 915 /// Used to change context to isConstantEvaluated without pushing a heavy 916 /// ExpressionEvaluationContextRecord object. 917 bool isConstantEvaluatedOverride; 918 isConstantEvaluated()919 bool isConstantEvaluated() { 920 return ExprEvalContexts.back().isConstantEvaluated() || 921 isConstantEvaluatedOverride; 922 } 923 924 /// RAII object to handle the state changes required to synthesize 925 /// a function body. 926 class SynthesizedFunctionScope { 927 Sema &S; 928 Sema::ContextRAII SavedContext; 929 bool PushedCodeSynthesisContext = false; 930 931 public: SynthesizedFunctionScope(Sema & S,DeclContext * DC)932 SynthesizedFunctionScope(Sema &S, DeclContext *DC) 933 : S(S), SavedContext(S, DC) { 934 S.PushFunctionScope(); 935 S.PushExpressionEvaluationContext( 936 Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 937 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 938 FD->setWillHaveBody(true); 939 else 940 assert(isa<ObjCMethodDecl>(DC)); 941 } 942 addContextNote(SourceLocation UseLoc)943 void addContextNote(SourceLocation UseLoc) { 944 assert(!PushedCodeSynthesisContext); 945 946 Sema::CodeSynthesisContext Ctx; 947 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction; 948 Ctx.PointOfInstantiation = UseLoc; 949 Ctx.Entity = cast<Decl>(S.CurContext); 950 S.pushCodeSynthesisContext(Ctx); 951 952 PushedCodeSynthesisContext = true; 953 } 954 ~SynthesizedFunctionScope()955 ~SynthesizedFunctionScope() { 956 if (PushedCodeSynthesisContext) 957 S.popCodeSynthesisContext(); 958 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) 959 FD->setWillHaveBody(false); 960 S.PopExpressionEvaluationContext(); 961 S.PopFunctionScopeInfo(); 962 } 963 }; 964 965 /// WeakUndeclaredIdentifiers - Identifiers contained in 966 /// \#pragma weak before declared. rare. may alias another 967 /// identifier, declared or undeclared 968 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers; 969 970 /// ExtnameUndeclaredIdentifiers - Identifiers contained in 971 /// \#pragma redefine_extname before declared. Used in Solaris system headers 972 /// to define functions that occur in multiple standards to call the version 973 /// in the currently selected standard. 974 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers; 975 976 977 /// Load weak undeclared identifiers from the external source. 978 void LoadExternalWeakUndeclaredIdentifiers(); 979 980 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by 981 /// \#pragma weak during processing of other Decls. 982 /// I couldn't figure out a clean way to generate these in-line, so 983 /// we store them here and handle separately -- which is a hack. 984 /// It would be best to refactor this. 985 SmallVector<Decl*,2> WeakTopLevelDecl; 986 987 IdentifierResolver IdResolver; 988 989 /// Translation Unit Scope - useful to Objective-C actions that need 990 /// to lookup file scope declarations in the "ordinary" C decl namespace. 991 /// For example, user-defined classes, built-in "id" type, etc. 992 Scope *TUScope; 993 994 /// The C++ "std" namespace, where the standard library resides. 995 LazyDeclPtr StdNamespace; 996 997 /// The C++ "std::bad_alloc" class, which is defined by the C++ 998 /// standard library. 999 LazyDeclPtr StdBadAlloc; 1000 1001 /// The C++ "std::align_val_t" enum class, which is defined by the C++ 1002 /// standard library. 1003 LazyDeclPtr StdAlignValT; 1004 1005 /// The C++ "std::experimental" namespace, where the experimental parts 1006 /// of the standard library resides. 1007 NamespaceDecl *StdExperimentalNamespaceCache; 1008 1009 /// The C++ "std::initializer_list" template, which is defined in 1010 /// \<initializer_list>. 1011 ClassTemplateDecl *StdInitializerList; 1012 1013 /// The C++ "std::coroutine_traits" template, which is defined in 1014 /// \<coroutine_traits> 1015 ClassTemplateDecl *StdCoroutineTraitsCache; 1016 1017 /// The C++ "type_info" declaration, which is defined in \<typeinfo>. 1018 RecordDecl *CXXTypeInfoDecl; 1019 1020 /// The MSVC "_GUID" struct, which is defined in MSVC header files. 1021 RecordDecl *MSVCGuidDecl; 1022 1023 /// Caches identifiers/selectors for NSFoundation APIs. 1024 std::unique_ptr<NSAPI> NSAPIObj; 1025 1026 /// The declaration of the Objective-C NSNumber class. 1027 ObjCInterfaceDecl *NSNumberDecl; 1028 1029 /// The declaration of the Objective-C NSValue class. 1030 ObjCInterfaceDecl *NSValueDecl; 1031 1032 /// Pointer to NSNumber type (NSNumber *). 1033 QualType NSNumberPointer; 1034 1035 /// Pointer to NSValue type (NSValue *). 1036 QualType NSValuePointer; 1037 1038 /// The Objective-C NSNumber methods used to create NSNumber literals. 1039 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; 1040 1041 /// The declaration of the Objective-C NSString class. 1042 ObjCInterfaceDecl *NSStringDecl; 1043 1044 /// Pointer to NSString type (NSString *). 1045 QualType NSStringPointer; 1046 1047 /// The declaration of the stringWithUTF8String: method. 1048 ObjCMethodDecl *StringWithUTF8StringMethod; 1049 1050 /// The declaration of the valueWithBytes:objCType: method. 1051 ObjCMethodDecl *ValueWithBytesObjCTypeMethod; 1052 1053 /// The declaration of the Objective-C NSArray class. 1054 ObjCInterfaceDecl *NSArrayDecl; 1055 1056 /// The declaration of the arrayWithObjects:count: method. 1057 ObjCMethodDecl *ArrayWithObjectsMethod; 1058 1059 /// The declaration of the Objective-C NSDictionary class. 1060 ObjCInterfaceDecl *NSDictionaryDecl; 1061 1062 /// The declaration of the dictionaryWithObjects:forKeys:count: method. 1063 ObjCMethodDecl *DictionaryWithObjectsMethod; 1064 1065 /// id<NSCopying> type. 1066 QualType QIDNSCopying; 1067 1068 /// will hold 'respondsToSelector:' 1069 Selector RespondsToSelectorSel; 1070 1071 /// A flag to remember whether the implicit forms of operator new and delete 1072 /// have been declared. 1073 bool GlobalNewDeleteDeclared; 1074 1075 /// Describes how the expressions currently being parsed are 1076 /// evaluated at run-time, if at all. 1077 enum class ExpressionEvaluationContext { 1078 /// The current expression and its subexpressions occur within an 1079 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of 1080 /// \c sizeof, where the type of the expression may be significant but 1081 /// no code will be generated to evaluate the value of the expression at 1082 /// run time. 1083 Unevaluated, 1084 1085 /// The current expression occurs within a braced-init-list within 1086 /// an unevaluated operand. This is mostly like a regular unevaluated 1087 /// context, except that we still instantiate constexpr functions that are 1088 /// referenced here so that we can perform narrowing checks correctly. 1089 UnevaluatedList, 1090 1091 /// The current expression occurs within a discarded statement. 1092 /// This behaves largely similarly to an unevaluated operand in preventing 1093 /// definitions from being required, but not in other ways. 1094 DiscardedStatement, 1095 1096 /// The current expression occurs within an unevaluated 1097 /// operand that unconditionally permits abstract references to 1098 /// fields, such as a SIZE operator in MS-style inline assembly. 1099 UnevaluatedAbstract, 1100 1101 /// The current context is "potentially evaluated" in C++11 terms, 1102 /// but the expression is evaluated at compile-time (like the values of 1103 /// cases in a switch statement). 1104 ConstantEvaluated, 1105 1106 /// The current expression is potentially evaluated at run time, 1107 /// which means that code may be generated to evaluate the value of the 1108 /// expression at run time. 1109 PotentiallyEvaluated, 1110 1111 /// The current expression is potentially evaluated, but any 1112 /// declarations referenced inside that expression are only used if 1113 /// in fact the current expression is used. 1114 /// 1115 /// This value is used when parsing default function arguments, for which 1116 /// we would like to provide diagnostics (e.g., passing non-POD arguments 1117 /// through varargs) but do not want to mark declarations as "referenced" 1118 /// until the default argument is used. 1119 PotentiallyEvaluatedIfUsed 1120 }; 1121 1122 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>; 1123 1124 /// Data structure used to record current or nested 1125 /// expression evaluation contexts. 1126 struct ExpressionEvaluationContextRecord { 1127 /// The expression evaluation context. 1128 ExpressionEvaluationContext Context; 1129 1130 /// Whether the enclosing context needed a cleanup. 1131 CleanupInfo ParentCleanup; 1132 1133 /// The number of active cleanup objects when we entered 1134 /// this expression evaluation context. 1135 unsigned NumCleanupObjects; 1136 1137 /// The number of typos encountered during this expression evaluation 1138 /// context (i.e. the number of TypoExprs created). 1139 unsigned NumTypos; 1140 1141 MaybeODRUseExprSet SavedMaybeODRUseExprs; 1142 1143 /// The lambdas that are present within this context, if it 1144 /// is indeed an unevaluated context. 1145 SmallVector<LambdaExpr *, 2> Lambdas; 1146 1147 /// The declaration that provides context for lambda expressions 1148 /// and block literals if the normal declaration context does not 1149 /// suffice, e.g., in a default function argument. 1150 Decl *ManglingContextDecl; 1151 1152 /// If we are processing a decltype type, a set of call expressions 1153 /// for which we have deferred checking the completeness of the return type. 1154 SmallVector<CallExpr *, 8> DelayedDecltypeCalls; 1155 1156 /// If we are processing a decltype type, a set of temporary binding 1157 /// expressions for which we have deferred checking the destructor. 1158 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; 1159 1160 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs; 1161 1162 /// Expressions appearing as the LHS of a volatile assignment in this 1163 /// context. We produce a warning for these when popping the context if 1164 /// they are not discarded-value expressions nor unevaluated operands. 1165 SmallVector<Expr*, 2> VolatileAssignmentLHSs; 1166 1167 /// Set of candidates for starting an immediate invocation. 1168 llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates; 1169 1170 /// Set of DeclRefExprs referencing a consteval function when used in a 1171 /// context not already known to be immediately invoked. 1172 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval; 1173 1174 /// \brief Describes whether we are in an expression constext which we have 1175 /// to handle differently. 1176 enum ExpressionKind { 1177 EK_Decltype, EK_TemplateArgument, EK_Other 1178 } ExprContext; 1179 ExpressionEvaluationContextRecordExpressionEvaluationContextRecord1180 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, 1181 unsigned NumCleanupObjects, 1182 CleanupInfo ParentCleanup, 1183 Decl *ManglingContextDecl, 1184 ExpressionKind ExprContext) 1185 : Context(Context), ParentCleanup(ParentCleanup), 1186 NumCleanupObjects(NumCleanupObjects), NumTypos(0), 1187 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {} 1188 isUnevaluatedExpressionEvaluationContextRecord1189 bool isUnevaluated() const { 1190 return Context == ExpressionEvaluationContext::Unevaluated || 1191 Context == ExpressionEvaluationContext::UnevaluatedAbstract || 1192 Context == ExpressionEvaluationContext::UnevaluatedList; 1193 } isConstantEvaluatedExpressionEvaluationContextRecord1194 bool isConstantEvaluated() const { 1195 return Context == ExpressionEvaluationContext::ConstantEvaluated; 1196 } 1197 }; 1198 1199 /// A stack of expression evaluation contexts. 1200 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; 1201 1202 /// Emit a warning for all pending noderef expressions that we recorded. 1203 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec); 1204 1205 /// Compute the mangling number context for a lambda expression or 1206 /// block literal. Also return the extra mangling decl if any. 1207 /// 1208 /// \param DC - The DeclContext containing the lambda expression or 1209 /// block literal. 1210 std::tuple<MangleNumberingContext *, Decl *> 1211 getCurrentMangleNumberContext(const DeclContext *DC); 1212 1213 1214 /// SpecialMemberOverloadResult - The overloading result for a special member 1215 /// function. 1216 /// 1217 /// This is basically a wrapper around PointerIntPair. The lowest bits of the 1218 /// integer are used to determine whether overload resolution succeeded. 1219 class SpecialMemberOverloadResult { 1220 public: 1221 enum Kind { 1222 NoMemberOrDeleted, 1223 Ambiguous, 1224 Success 1225 }; 1226 1227 private: 1228 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; 1229 1230 public: SpecialMemberOverloadResult()1231 SpecialMemberOverloadResult() : Pair() {} SpecialMemberOverloadResult(CXXMethodDecl * MD)1232 SpecialMemberOverloadResult(CXXMethodDecl *MD) 1233 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {} 1234 getMethod()1235 CXXMethodDecl *getMethod() const { return Pair.getPointer(); } setMethod(CXXMethodDecl * MD)1236 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } 1237 getKind()1238 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } setKind(Kind K)1239 void setKind(Kind K) { Pair.setInt(K); } 1240 }; 1241 1242 class SpecialMemberOverloadResultEntry 1243 : public llvm::FastFoldingSetNode, 1244 public SpecialMemberOverloadResult { 1245 public: SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID & ID)1246 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID) 1247 : FastFoldingSetNode(ID) 1248 {} 1249 }; 1250 1251 /// A cache of special member function overload resolution results 1252 /// for C++ records. 1253 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache; 1254 1255 /// A cache of the flags available in enumerations with the flag_bits 1256 /// attribute. 1257 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache; 1258 1259 /// The kind of translation unit we are processing. 1260 /// 1261 /// When we're processing a complete translation unit, Sema will perform 1262 /// end-of-translation-unit semantic tasks (such as creating 1263 /// initializers for tentative definitions in C) once parsing has 1264 /// completed. Modules and precompiled headers perform different kinds of 1265 /// checks. 1266 TranslationUnitKind TUKind; 1267 1268 llvm::BumpPtrAllocator BumpAlloc; 1269 1270 /// The number of SFINAE diagnostics that have been trapped. 1271 unsigned NumSFINAEErrors; 1272 1273 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>> 1274 UnparsedDefaultArgInstantiationsMap; 1275 1276 /// A mapping from parameters with unparsed default arguments to the 1277 /// set of instantiations of each parameter. 1278 /// 1279 /// This mapping is a temporary data structure used when parsing 1280 /// nested class templates or nested classes of class templates, 1281 /// where we might end up instantiating an inner class before the 1282 /// default arguments of its methods have been parsed. 1283 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; 1284 1285 // Contains the locations of the beginning of unparsed default 1286 // argument locations. 1287 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs; 1288 1289 /// UndefinedInternals - all the used, undefined objects which require a 1290 /// definition in this translation unit. 1291 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed; 1292 1293 /// Determine if VD, which must be a variable or function, is an external 1294 /// symbol that nonetheless can't be referenced from outside this translation 1295 /// unit because its type has no linkage and it's not extern "C". 1296 bool isExternalWithNoLinkageType(ValueDecl *VD); 1297 1298 /// Obtain a sorted list of functions that are undefined but ODR-used. 1299 void getUndefinedButUsed( 1300 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined); 1301 1302 /// Retrieves list of suspicious delete-expressions that will be checked at 1303 /// the end of translation unit. 1304 const llvm::MapVector<FieldDecl *, DeleteLocs> & 1305 getMismatchingDeleteExpressions() const; 1306 1307 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods; 1308 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool; 1309 1310 /// Method Pool - allows efficient lookup when typechecking messages to "id". 1311 /// We need to maintain a list, since selectors can have differing signatures 1312 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% 1313 /// of selectors are "overloaded"). 1314 /// At the head of the list it is recorded whether there were 0, 1, or >= 2 1315 /// methods inside categories with a particular selector. 1316 GlobalMethodPool MethodPool; 1317 1318 /// Method selectors used in a \@selector expression. Used for implementation 1319 /// of -Wselector. 1320 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors; 1321 1322 /// List of SourceLocations where 'self' is implicitly retained inside a 1323 /// block. 1324 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1> 1325 ImplicitlyRetainedSelfLocs; 1326 1327 /// Kinds of C++ special members. 1328 enum CXXSpecialMember { 1329 CXXDefaultConstructor, 1330 CXXCopyConstructor, 1331 CXXMoveConstructor, 1332 CXXCopyAssignment, 1333 CXXMoveAssignment, 1334 CXXDestructor, 1335 CXXInvalid 1336 }; 1337 1338 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember> 1339 SpecialMemberDecl; 1340 1341 /// The C++ special members which we are currently in the process of 1342 /// declaring. If this process recursively triggers the declaration of the 1343 /// same special member, we should act as if it is not yet declared. 1344 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; 1345 1346 /// Kinds of defaulted comparison operator functions. 1347 enum class DefaultedComparisonKind : unsigned char { 1348 /// This is not a defaultable comparison operator. 1349 None, 1350 /// This is an operator== that should be implemented as a series of 1351 /// subobject comparisons. 1352 Equal, 1353 /// This is an operator<=> that should be implemented as a series of 1354 /// subobject comparisons. 1355 ThreeWay, 1356 /// This is an operator!= that should be implemented as a rewrite in terms 1357 /// of a == comparison. 1358 NotEqual, 1359 /// This is an <, <=, >, or >= that should be implemented as a rewrite in 1360 /// terms of a <=> comparison. 1361 Relational, 1362 }; 1363 1364 /// The function definitions which were renamed as part of typo-correction 1365 /// to match their respective declarations. We want to keep track of them 1366 /// to ensure that we don't emit a "redefinition" error if we encounter a 1367 /// correctly named definition after the renamed definition. 1368 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions; 1369 1370 /// Stack of types that correspond to the parameter entities that are 1371 /// currently being copy-initialized. Can be empty. 1372 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes; 1373 1374 void ReadMethodPool(Selector Sel); 1375 void updateOutOfDateSelector(Selector Sel); 1376 1377 /// Private Helper predicate to check for 'self'. 1378 bool isSelfExpr(Expr *RExpr); 1379 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method); 1380 1381 /// Cause the active diagnostic on the DiagosticsEngine to be 1382 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and 1383 /// should not be used elsewhere. 1384 void EmitCurrentDiagnostic(unsigned DiagID); 1385 1386 /// Records and restores the CurFPFeatures state on entry/exit of compound 1387 /// statements. 1388 class FPFeaturesStateRAII { 1389 public: FPFeaturesStateRAII(Sema & S)1390 FPFeaturesStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.CurFPFeatures) { 1391 OldOverrides = S.FpPragmaStack.CurrentValue; 1392 } ~FPFeaturesStateRAII()1393 ~FPFeaturesStateRAII() { 1394 S.CurFPFeatures = OldFPFeaturesState; 1395 S.FpPragmaStack.CurrentValue = OldOverrides; 1396 } getOverrides()1397 FPOptionsOverride getOverrides() { return OldOverrides; } 1398 1399 private: 1400 Sema& S; 1401 FPOptions OldFPFeaturesState; 1402 FPOptionsOverride OldOverrides; 1403 }; 1404 1405 void addImplicitTypedef(StringRef Name, QualType T); 1406 1407 bool WarnedStackExhausted = false; 1408 1409 public: 1410 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 1411 TranslationUnitKind TUKind = TU_Complete, 1412 CodeCompleteConsumer *CompletionConsumer = nullptr); 1413 ~Sema(); 1414 1415 /// Perform initialization that occurs after the parser has been 1416 /// initialized but before it parses anything. 1417 void Initialize(); 1418 getLangOpts()1419 const LangOptions &getLangOpts() const { return LangOpts; } getOpenCLOptions()1420 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } getCurFPFeatures()1421 FPOptions &getCurFPFeatures() { return CurFPFeatures; } 1422 getDiagnostics()1423 DiagnosticsEngine &getDiagnostics() const { return Diags; } getSourceManager()1424 SourceManager &getSourceManager() const { return SourceMgr; } getPreprocessor()1425 Preprocessor &getPreprocessor() const { return PP; } getASTContext()1426 ASTContext &getASTContext() const { return Context; } getASTConsumer()1427 ASTConsumer &getASTConsumer() const { return Consumer; } 1428 ASTMutationListener *getASTMutationListener() const; getExternalSource()1429 ExternalSemaSource* getExternalSource() const { return ExternalSource; } 1430 1431 ///Registers an external source. If an external source already exists, 1432 /// creates a multiplex external source and appends to it. 1433 /// 1434 ///\param[in] E - A non-null external sema source. 1435 /// 1436 void addExternalSource(ExternalSemaSource *E); 1437 1438 void PrintStats() const; 1439 1440 /// Warn that the stack is nearly exhausted. 1441 void warnStackExhausted(SourceLocation Loc); 1442 1443 /// Run some code with "sufficient" stack space. (Currently, at least 256K is 1444 /// guaranteed). Produces a warning if we're low on stack space and allocates 1445 /// more in that case. Use this in code that may recurse deeply (for example, 1446 /// in template instantiation) to avoid stack overflow. 1447 void runWithSufficientStackSpace(SourceLocation Loc, 1448 llvm::function_ref<void()> Fn); 1449 1450 /// Helper class that creates diagnostics with optional 1451 /// template instantiation stacks. 1452 /// 1453 /// This class provides a wrapper around the basic DiagnosticBuilder 1454 /// class that emits diagnostics. ImmediateDiagBuilder is 1455 /// responsible for emitting the diagnostic (as DiagnosticBuilder 1456 /// does) and, if the diagnostic comes from inside a template 1457 /// instantiation, printing the template instantiation stack as 1458 /// well. 1459 class ImmediateDiagBuilder : public DiagnosticBuilder { 1460 Sema &SemaRef; 1461 unsigned DiagID; 1462 1463 public: ImmediateDiagBuilder(DiagnosticBuilder & DB,Sema & SemaRef,unsigned DiagID)1464 ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) 1465 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {} ImmediateDiagBuilder(DiagnosticBuilder && DB,Sema & SemaRef,unsigned DiagID)1466 ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID) 1467 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {} 1468 1469 // This is a cunning lie. DiagnosticBuilder actually performs move 1470 // construction in its copy constructor (but due to varied uses, it's not 1471 // possible to conveniently express this as actual move construction). So 1472 // the default copy ctor here is fine, because the base class disables the 1473 // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op 1474 // in that case anwyay. 1475 ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default; 1476 ~ImmediateDiagBuilder()1477 ~ImmediateDiagBuilder() { 1478 // If we aren't active, there is nothing to do. 1479 if (!isActive()) return; 1480 1481 // Otherwise, we need to emit the diagnostic. First clear the diagnostic 1482 // builder itself so it won't emit the diagnostic in its own destructor. 1483 // 1484 // This seems wasteful, in that as written the DiagnosticBuilder dtor will 1485 // do its own needless checks to see if the diagnostic needs to be 1486 // emitted. However, because we take care to ensure that the builder 1487 // objects never escape, a sufficiently smart compiler will be able to 1488 // eliminate that code. 1489 Clear(); 1490 1491 // Dispatch to Sema to emit the diagnostic. 1492 SemaRef.EmitCurrentDiagnostic(DiagID); 1493 } 1494 1495 /// Teach operator<< to produce an object of the correct type. 1496 template <typename T> 1497 friend const ImmediateDiagBuilder & 1498 operator<<(const ImmediateDiagBuilder &Diag, const T &Value) { 1499 const DiagnosticBuilder &BaseDiag = Diag; 1500 BaseDiag << Value; 1501 return Diag; 1502 } 1503 1504 // It is necessary to limit this to rvalue reference to avoid calling this 1505 // function with a bitfield lvalue argument since non-const reference to 1506 // bitfield is not allowed. 1507 template <typename T, typename = typename std::enable_if< 1508 !std::is_lvalue_reference<T>::value>::type> 1509 const ImmediateDiagBuilder &operator<<(T &&V) const { 1510 const DiagnosticBuilder &BaseDiag = *this; 1511 BaseDiag << std::move(V); 1512 return *this; 1513 } 1514 }; 1515 1516 /// A generic diagnostic builder for errors which may or may not be deferred. 1517 /// 1518 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch) 1519 /// which are not allowed to appear inside __device__ functions and are 1520 /// allowed to appear in __host__ __device__ functions only if the host+device 1521 /// function is never codegen'ed. 1522 /// 1523 /// To handle this, we use the notion of "deferred diagnostics", where we 1524 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed. 1525 /// 1526 /// This class lets you emit either a regular diagnostic, a deferred 1527 /// diagnostic, or no diagnostic at all, according to an argument you pass to 1528 /// its constructor, thus simplifying the process of creating these "maybe 1529 /// deferred" diagnostics. 1530 class SemaDiagnosticBuilder { 1531 public: 1532 enum Kind { 1533 /// Emit no diagnostics. 1534 K_Nop, 1535 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()). 1536 K_Immediate, 1537 /// Emit the diagnostic immediately, and, if it's a warning or error, also 1538 /// emit a call stack showing how this function can be reached by an a 1539 /// priori known-emitted function. 1540 K_ImmediateWithCallStack, 1541 /// Create a deferred diagnostic, which is emitted only if the function 1542 /// it's attached to is codegen'ed. Also emit a call stack as with 1543 /// K_ImmediateWithCallStack. 1544 K_Deferred 1545 }; 1546 1547 SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID, 1548 FunctionDecl *Fn, Sema &S); 1549 SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D); 1550 SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default; 1551 ~SemaDiagnosticBuilder(); 1552 isImmediate()1553 bool isImmediate() const { return ImmediateDiag.hasValue(); } 1554 1555 /// Convertible to bool: True if we immediately emitted an error, false if 1556 /// we didn't emit an error or we created a deferred error. 1557 /// 1558 /// Example usage: 1559 /// 1560 /// if (SemaDiagnosticBuilder(...) << foo << bar) 1561 /// return ExprError(); 1562 /// 1563 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably 1564 /// want to use these instead of creating a SemaDiagnosticBuilder yourself. 1565 operator bool() const { return isImmediate(); } 1566 1567 template <typename T> 1568 friend const SemaDiagnosticBuilder & 1569 operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) { 1570 if (Diag.ImmediateDiag.hasValue()) 1571 *Diag.ImmediateDiag << Value; 1572 else if (Diag.PartialDiagId.hasValue()) 1573 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second 1574 << Value; 1575 return Diag; 1576 } 1577 1578 // It is necessary to limit this to rvalue reference to avoid calling this 1579 // function with a bitfield lvalue argument since non-const reference to 1580 // bitfield is not allowed. 1581 template <typename T, typename = typename std::enable_if< 1582 !std::is_lvalue_reference<T>::value>::type> 1583 const SemaDiagnosticBuilder &operator<<(T &&V) const { 1584 if (ImmediateDiag.hasValue()) 1585 *ImmediateDiag << std::move(V); 1586 else if (PartialDiagId.hasValue()) 1587 S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V); 1588 return *this; 1589 } 1590 1591 friend const SemaDiagnosticBuilder & 1592 operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) { 1593 if (Diag.ImmediateDiag.hasValue()) 1594 PD.Emit(*Diag.ImmediateDiag); 1595 else if (Diag.PartialDiagId.hasValue()) 1596 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD; 1597 return Diag; 1598 } 1599 AddFixItHint(const FixItHint & Hint)1600 void AddFixItHint(const FixItHint &Hint) const { 1601 if (ImmediateDiag.hasValue()) 1602 ImmediateDiag->AddFixItHint(Hint); 1603 else if (PartialDiagId.hasValue()) 1604 S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint); 1605 } 1606 ExprError(const SemaDiagnosticBuilder &)1607 friend ExprResult ExprError(const SemaDiagnosticBuilder &) { 1608 return ExprError(); 1609 } StmtError(const SemaDiagnosticBuilder &)1610 friend StmtResult StmtError(const SemaDiagnosticBuilder &) { 1611 return StmtError(); 1612 } ExprResult()1613 operator ExprResult() const { return ExprError(); } StmtResult()1614 operator StmtResult() const { return StmtError(); } TypeResult()1615 operator TypeResult() const { return TypeError(); } DeclResult()1616 operator DeclResult() const { return DeclResult(true); } MemInitResult()1617 operator MemInitResult() const { return MemInitResult(true); } 1618 1619 private: 1620 Sema &S; 1621 SourceLocation Loc; 1622 unsigned DiagID; 1623 FunctionDecl *Fn; 1624 bool ShowCallStack; 1625 1626 // Invariant: At most one of these Optionals has a value. 1627 // FIXME: Switch these to a Variant once that exists. 1628 llvm::Optional<ImmediateDiagBuilder> ImmediateDiag; 1629 llvm::Optional<unsigned> PartialDiagId; 1630 }; 1631 1632 /// Is the last error level diagnostic immediate. This is used to determined 1633 /// whether the next info diagnostic should be immediate. 1634 bool IsLastErrorImmediate = true; 1635 1636 /// Emit a diagnostic. 1637 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, 1638 bool DeferHint = false); 1639 1640 /// Emit a partial diagnostic. 1641 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD, 1642 bool DeferHint = false); 1643 1644 /// Build a partial diagnostic. 1645 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h 1646 1647 /// Whether uncompilable error has occurred. This includes error happens 1648 /// in deferred diagnostics. 1649 bool hasUncompilableErrorOccurred() const; 1650 1651 bool findMacroSpelling(SourceLocation &loc, StringRef name); 1652 1653 /// Get a string to suggest for zero-initialization of a type. 1654 std::string 1655 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const; 1656 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const; 1657 1658 /// Calls \c Lexer::getLocForEndOfToken() 1659 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); 1660 1661 /// Retrieve the module loader associated with the preprocessor. 1662 ModuleLoader &getModuleLoader() const; 1663 1664 /// Invent a new identifier for parameters of abbreviated templates. 1665 IdentifierInfo * 1666 InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName, 1667 unsigned Index); 1668 1669 void emitAndClearUnusedLocalTypedefWarnings(); 1670 1671 private: 1672 /// Function or variable declarations to be checked for whether the deferred 1673 /// diagnostics should be emitted. 1674 SmallVector<Decl *, 4> DeclsToCheckForDeferredDiags; 1675 1676 public: 1677 // Emit all deferred diagnostics. 1678 void emitDeferredDiags(); 1679 1680 enum TUFragmentKind { 1681 /// The global module fragment, between 'module;' and a module-declaration. 1682 Global, 1683 /// A normal translation unit fragment. For a non-module unit, this is the 1684 /// entire translation unit. Otherwise, it runs from the module-declaration 1685 /// to the private-module-fragment (if any) or the end of the TU (if not). 1686 Normal, 1687 /// The private module fragment, between 'module :private;' and the end of 1688 /// the translation unit. 1689 Private 1690 }; 1691 1692 void ActOnStartOfTranslationUnit(); 1693 void ActOnEndOfTranslationUnit(); 1694 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind); 1695 1696 void CheckDelegatingCtorCycles(); 1697 1698 Scope *getScopeForContext(DeclContext *Ctx); 1699 1700 void PushFunctionScope(); 1701 void PushBlockScope(Scope *BlockScope, BlockDecl *Block); 1702 sema::LambdaScopeInfo *PushLambdaScope(); 1703 1704 /// This is used to inform Sema what the current TemplateParameterDepth 1705 /// is during Parsing. Currently it is used to pass on the depth 1706 /// when parsing generic lambda 'auto' parameters. 1707 void RecordParsingTemplateParameterDepth(unsigned Depth); 1708 1709 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, 1710 RecordDecl *RD, CapturedRegionKind K, 1711 unsigned OpenMPCaptureLevel = 0); 1712 1713 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short 1714 /// time after they've been popped. 1715 class PoppedFunctionScopeDeleter { 1716 Sema *Self; 1717 1718 public: PoppedFunctionScopeDeleter(Sema * Self)1719 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {} 1720 void operator()(sema::FunctionScopeInfo *Scope) const; 1721 }; 1722 1723 using PoppedFunctionScopePtr = 1724 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>; 1725 1726 PoppedFunctionScopePtr 1727 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, 1728 const Decl *D = nullptr, 1729 QualType BlockType = QualType()); 1730 getCurFunction()1731 sema::FunctionScopeInfo *getCurFunction() const { 1732 return FunctionScopes.empty() ? nullptr : FunctionScopes.back(); 1733 } 1734 1735 sema::FunctionScopeInfo *getEnclosingFunction() const; 1736 1737 void setFunctionHasBranchIntoScope(); 1738 void setFunctionHasBranchProtectedScope(); 1739 void setFunctionHasIndirectGoto(); 1740 1741 void PushCompoundScope(bool IsStmtExpr); 1742 void PopCompoundScope(); 1743 1744 sema::CompoundScopeInfo &getCurCompoundScope() const; 1745 1746 bool hasAnyUnrecoverableErrorsInThisFunction() const; 1747 1748 /// Retrieve the current block, if any. 1749 sema::BlockScopeInfo *getCurBlock(); 1750 1751 /// Get the innermost lambda enclosing the current location, if any. This 1752 /// looks through intervening non-lambda scopes such as local functions and 1753 /// blocks. 1754 sema::LambdaScopeInfo *getEnclosingLambda() const; 1755 1756 /// Retrieve the current lambda scope info, if any. 1757 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most 1758 /// lambda scope info ignoring all inner capturing scopes that are not 1759 /// lambda scopes. 1760 sema::LambdaScopeInfo * 1761 getCurLambda(bool IgnoreNonLambdaCapturingScope = false); 1762 1763 /// Retrieve the current generic lambda info, if any. 1764 sema::LambdaScopeInfo *getCurGenericLambda(); 1765 1766 /// Retrieve the current captured region, if any. 1767 sema::CapturedRegionScopeInfo *getCurCapturedRegion(); 1768 1769 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls WeakTopLevelDecls()1770 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } 1771 1772 /// Called before parsing a function declarator belonging to a function 1773 /// declaration. 1774 void ActOnStartFunctionDeclarationDeclarator(Declarator &D, 1775 unsigned TemplateParameterDepth); 1776 1777 /// Called after parsing a function declarator belonging to a function 1778 /// declaration. 1779 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D); 1780 1781 void ActOnComment(SourceRange Comment); 1782 1783 //===--------------------------------------------------------------------===// 1784 // Type Analysis / Processing: SemaType.cpp. 1785 // 1786 1787 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, 1788 const DeclSpec *DS = nullptr); 1789 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, 1790 const DeclSpec *DS = nullptr); 1791 QualType BuildPointerType(QualType T, 1792 SourceLocation Loc, DeclarationName Entity); 1793 QualType BuildReferenceType(QualType T, bool LValueRef, 1794 SourceLocation Loc, DeclarationName Entity); 1795 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, 1796 Expr *ArraySize, unsigned Quals, 1797 SourceRange Brackets, DeclarationName Entity); 1798 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc); 1799 QualType BuildExtVectorType(QualType T, Expr *ArraySize, 1800 SourceLocation AttrLoc); 1801 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, 1802 SourceLocation AttrLoc); 1803 1804 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, 1805 SourceLocation AttrLoc); 1806 1807 /// Same as above, but constructs the AddressSpace index if not provided. 1808 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, 1809 SourceLocation AttrLoc); 1810 1811 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc); 1812 1813 bool CheckFunctionReturnType(QualType T, SourceLocation Loc); 1814 1815 /// Build a function type. 1816 /// 1817 /// This routine checks the function type according to C++ rules and 1818 /// under the assumption that the result type and parameter types have 1819 /// just been instantiated from a template. It therefore duplicates 1820 /// some of the behavior of GetTypeForDeclarator, but in a much 1821 /// simpler form that is only suitable for this narrow use case. 1822 /// 1823 /// \param T The return type of the function. 1824 /// 1825 /// \param ParamTypes The parameter types of the function. This array 1826 /// will be modified to account for adjustments to the types of the 1827 /// function parameters. 1828 /// 1829 /// \param Loc The location of the entity whose type involves this 1830 /// function type or, if there is no such entity, the location of the 1831 /// type that will have function type. 1832 /// 1833 /// \param Entity The name of the entity that involves the function 1834 /// type, if known. 1835 /// 1836 /// \param EPI Extra information about the function type. Usually this will 1837 /// be taken from an existing function with the same prototype. 1838 /// 1839 /// \returns A suitable function type, if there are no errors. The 1840 /// unqualified type will always be a FunctionProtoType. 1841 /// Otherwise, returns a NULL type. 1842 QualType BuildFunctionType(QualType T, 1843 MutableArrayRef<QualType> ParamTypes, 1844 SourceLocation Loc, DeclarationName Entity, 1845 const FunctionProtoType::ExtProtoInfo &EPI); 1846 1847 QualType BuildMemberPointerType(QualType T, QualType Class, 1848 SourceLocation Loc, 1849 DeclarationName Entity); 1850 QualType BuildBlockPointerType(QualType T, 1851 SourceLocation Loc, DeclarationName Entity); 1852 QualType BuildParenType(QualType T); 1853 QualType BuildAtomicType(QualType T, SourceLocation Loc); 1854 QualType BuildReadPipeType(QualType T, 1855 SourceLocation Loc); 1856 QualType BuildWritePipeType(QualType T, 1857 SourceLocation Loc); 1858 QualType BuildExtIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc); 1859 1860 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); 1861 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); 1862 1863 /// Package the given type and TSI into a ParsedType. 1864 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); 1865 DeclarationNameInfo GetNameForDeclarator(Declarator &D); 1866 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); 1867 static QualType GetTypeFromParser(ParsedType Ty, 1868 TypeSourceInfo **TInfo = nullptr); 1869 CanThrowResult canThrow(const Stmt *E); 1870 /// Determine whether the callee of a particular function call can throw. 1871 /// E, D and Loc are all optional. 1872 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D, 1873 SourceLocation Loc = SourceLocation()); 1874 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, 1875 const FunctionProtoType *FPT); 1876 void UpdateExceptionSpec(FunctionDecl *FD, 1877 const FunctionProtoType::ExceptionSpecInfo &ESI); 1878 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range); 1879 bool CheckDistantExceptionSpec(QualType T); 1880 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); 1881 bool CheckEquivalentExceptionSpec( 1882 const FunctionProtoType *Old, SourceLocation OldLoc, 1883 const FunctionProtoType *New, SourceLocation NewLoc); 1884 bool CheckEquivalentExceptionSpec( 1885 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, 1886 const FunctionProtoType *Old, SourceLocation OldLoc, 1887 const FunctionProtoType *New, SourceLocation NewLoc); 1888 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType); 1889 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID, 1890 const PartialDiagnostic &NestedDiagID, 1891 const PartialDiagnostic &NoteID, 1892 const PartialDiagnostic &NoThrowDiagID, 1893 const FunctionProtoType *Superset, 1894 SourceLocation SuperLoc, 1895 const FunctionProtoType *Subset, 1896 SourceLocation SubLoc); 1897 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID, 1898 const PartialDiagnostic &NoteID, 1899 const FunctionProtoType *Target, 1900 SourceLocation TargetLoc, 1901 const FunctionProtoType *Source, 1902 SourceLocation SourceLoc); 1903 1904 TypeResult ActOnTypeName(Scope *S, Declarator &D); 1905 1906 /// The parser has parsed the context-sensitive type 'instancetype' 1907 /// in an Objective-C message declaration. Return the appropriate type. 1908 ParsedType ActOnObjCInstanceType(SourceLocation Loc); 1909 1910 /// Abstract class used to diagnose incomplete types. 1911 struct TypeDiagnoser { TypeDiagnoserTypeDiagnoser1912 TypeDiagnoser() {} 1913 1914 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0; ~TypeDiagnoserTypeDiagnoser1915 virtual ~TypeDiagnoser() {} 1916 }; 1917 getPrintable(int I)1918 static int getPrintable(int I) { return I; } getPrintable(unsigned I)1919 static unsigned getPrintable(unsigned I) { return I; } getPrintable(bool B)1920 static bool getPrintable(bool B) { return B; } getPrintable(const char * S)1921 static const char * getPrintable(const char *S) { return S; } getPrintable(StringRef S)1922 static StringRef getPrintable(StringRef S) { return S; } getPrintable(const std::string & S)1923 static const std::string &getPrintable(const std::string &S) { return S; } getPrintable(const IdentifierInfo * II)1924 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) { 1925 return II; 1926 } getPrintable(DeclarationName N)1927 static DeclarationName getPrintable(DeclarationName N) { return N; } getPrintable(QualType T)1928 static QualType getPrintable(QualType T) { return T; } getPrintable(SourceRange R)1929 static SourceRange getPrintable(SourceRange R) { return R; } getPrintable(SourceLocation L)1930 static SourceRange getPrintable(SourceLocation L) { return L; } getPrintable(const Expr * E)1931 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); } getPrintable(TypeLoc TL)1932 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();} 1933 1934 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser { 1935 protected: 1936 unsigned DiagID; 1937 std::tuple<const Ts &...> Args; 1938 1939 template <std::size_t... Is> emit(const SemaDiagnosticBuilder & DB,std::index_sequence<Is...>)1940 void emit(const SemaDiagnosticBuilder &DB, 1941 std::index_sequence<Is...>) const { 1942 // Apply all tuple elements to the builder in order. 1943 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...}; 1944 (void)Dummy; 1945 } 1946 1947 public: BoundTypeDiagnoser(unsigned DiagID,const Ts &...Args)1948 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args) 1949 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) { 1950 assert(DiagID != 0 && "no diagnostic for type diagnoser"); 1951 } 1952 diagnose(Sema & S,SourceLocation Loc,QualType T)1953 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 1954 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID); 1955 emit(DB, std::index_sequence_for<Ts...>()); 1956 DB << T; 1957 } 1958 }; 1959 1960 /// Do a check to make sure \p Name looks like a legal argument for the 1961 /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name 1962 /// is invalid for the given declaration. 1963 /// 1964 /// \p AL is used to provide caret diagnostics in case of a malformed name. 1965 /// 1966 /// \returns true if the name is a valid swift name for \p D, false otherwise. 1967 bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc, 1968 const ParsedAttr &AL, bool IsAsync); 1969 1970 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type 1971 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless. 1972 /// For example, a diagnostic with no other parameters would generally have 1973 /// the form "...%select{incomplete|sizeless}0 type %1...". 1974 template <typename... Ts> 1975 class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> { 1976 public: SizelessTypeDiagnoser(unsigned DiagID,const Ts &...Args)1977 SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args) 1978 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {} 1979 diagnose(Sema & S,SourceLocation Loc,QualType T)1980 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 1981 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID); 1982 this->emit(DB, std::index_sequence_for<Ts...>()); 1983 DB << T->isSizelessType() << T; 1984 } 1985 }; 1986 1987 enum class CompleteTypeKind { 1988 /// Apply the normal rules for complete types. In particular, 1989 /// treat all sizeless types as incomplete. 1990 Normal, 1991 1992 /// Relax the normal rules for complete types so that they include 1993 /// sizeless built-in types. 1994 AcceptSizeless, 1995 1996 // FIXME: Eventually we should flip the default to Normal and opt in 1997 // to AcceptSizeless rather than opt out of it. 1998 Default = AcceptSizeless 1999 }; 2000 2001 private: 2002 /// Methods for marking which expressions involve dereferencing a pointer 2003 /// marked with the 'noderef' attribute. Expressions are checked bottom up as 2004 /// they are parsed, meaning that a noderef pointer may not be accessed. For 2005 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the 2006 /// `*p`, but need to check that `address of` is called on it. This requires 2007 /// keeping a container of all pending expressions and checking if the address 2008 /// of them are eventually taken. 2009 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E); 2010 void CheckAddressOfNoDeref(const Expr *E); 2011 void CheckMemberAccessOfNoDeref(const MemberExpr *E); 2012 2013 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, 2014 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser); 2015 2016 struct ModuleScope { 2017 SourceLocation BeginLoc; 2018 clang::Module *Module = nullptr; 2019 bool ModuleInterface = false; 2020 bool ImplicitGlobalModuleFragment = false; 2021 VisibleModuleSet OuterVisibleModules; 2022 }; 2023 /// The modules we're currently parsing. 2024 llvm::SmallVector<ModuleScope, 16> ModuleScopes; 2025 2026 /// Namespace definitions that we will export when they finish. 2027 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces; 2028 2029 /// Get the module whose scope we are currently within. getCurrentModule()2030 Module *getCurrentModule() const { 2031 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module; 2032 } 2033 2034 VisibleModuleSet VisibleModules; 2035 2036 public: 2037 /// Get the module owning an entity. getOwningModule(const Decl * Entity)2038 Module *getOwningModule(const Decl *Entity) { 2039 return Entity->getOwningModule(); 2040 } 2041 2042 /// Make a merged definition of an existing hidden definition \p ND 2043 /// visible at the specified location. 2044 void makeMergedDefinitionVisible(NamedDecl *ND); 2045 2046 bool isModuleVisible(const Module *M, bool ModulePrivate = false); 2047 2048 // When loading a non-modular PCH files, this is used to restore module 2049 // visibility. makeModuleVisible(Module * Mod,SourceLocation ImportLoc)2050 void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) { 2051 VisibleModules.setVisible(Mod, ImportLoc); 2052 } 2053 2054 /// Determine whether a declaration is visible to name lookup. isVisible(const NamedDecl * D)2055 bool isVisible(const NamedDecl *D) { 2056 return D->isUnconditionallyVisible() || isVisibleSlow(D); 2057 } 2058 2059 /// Determine whether any declaration of an entity is visible. 2060 bool 2061 hasVisibleDeclaration(const NamedDecl *D, 2062 llvm::SmallVectorImpl<Module *> *Modules = nullptr) { 2063 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules); 2064 } 2065 bool hasVisibleDeclarationSlow(const NamedDecl *D, 2066 llvm::SmallVectorImpl<Module *> *Modules); 2067 2068 bool hasVisibleMergedDefinition(NamedDecl *Def); 2069 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def); 2070 2071 /// Determine if \p D and \p Suggested have a structurally compatible 2072 /// layout as described in C11 6.2.7/1. 2073 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested); 2074 2075 /// Determine if \p D has a visible definition. If not, suggest a declaration 2076 /// that should be made visible to expose the definition. 2077 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, 2078 bool OnlyNeedComplete = false); hasVisibleDefinition(const NamedDecl * D)2079 bool hasVisibleDefinition(const NamedDecl *D) { 2080 NamedDecl *Hidden; 2081 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden); 2082 } 2083 2084 /// Determine if the template parameter \p D has a visible default argument. 2085 bool 2086 hasVisibleDefaultArgument(const NamedDecl *D, 2087 llvm::SmallVectorImpl<Module *> *Modules = nullptr); 2088 2089 /// Determine if there is a visible declaration of \p D that is an explicit 2090 /// specialization declaration for a specialization of a template. (For a 2091 /// member specialization, use hasVisibleMemberSpecialization.) 2092 bool hasVisibleExplicitSpecialization( 2093 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); 2094 2095 /// Determine if there is a visible declaration of \p D that is a member 2096 /// specialization declaration (as opposed to an instantiated declaration). 2097 bool hasVisibleMemberSpecialization( 2098 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); 2099 2100 /// Determine if \p A and \p B are equivalent internal linkage declarations 2101 /// from different modules, and thus an ambiguity error can be downgraded to 2102 /// an extension warning. 2103 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 2104 const NamedDecl *B); 2105 void diagnoseEquivalentInternalLinkageDeclarations( 2106 SourceLocation Loc, const NamedDecl *D, 2107 ArrayRef<const NamedDecl *> Equiv); 2108 2109 bool isUsualDeallocationFunction(const CXXMethodDecl *FD); 2110 2111 bool isCompleteType(SourceLocation Loc, QualType T, 2112 CompleteTypeKind Kind = CompleteTypeKind::Default) { 2113 return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr); 2114 } 2115 bool RequireCompleteType(SourceLocation Loc, QualType T, 2116 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser); 2117 bool RequireCompleteType(SourceLocation Loc, QualType T, 2118 CompleteTypeKind Kind, unsigned DiagID); 2119 RequireCompleteType(SourceLocation Loc,QualType T,TypeDiagnoser & Diagnoser)2120 bool RequireCompleteType(SourceLocation Loc, QualType T, 2121 TypeDiagnoser &Diagnoser) { 2122 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser); 2123 } RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID)2124 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) { 2125 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID); 2126 } 2127 2128 template <typename... Ts> RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)2129 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, 2130 const Ts &...Args) { 2131 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 2132 return RequireCompleteType(Loc, T, Diagnoser); 2133 } 2134 2135 template <typename... Ts> RequireCompleteSizedType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)2136 bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, 2137 const Ts &... Args) { 2138 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 2139 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser); 2140 } 2141 2142 void completeExprArrayBound(Expr *E); 2143 bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, 2144 TypeDiagnoser &Diagnoser); 2145 bool RequireCompleteExprType(Expr *E, unsigned DiagID); 2146 2147 template <typename... Ts> RequireCompleteExprType(Expr * E,unsigned DiagID,const Ts &...Args)2148 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) { 2149 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 2150 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser); 2151 } 2152 2153 template <typename... Ts> RequireCompleteSizedExprType(Expr * E,unsigned DiagID,const Ts &...Args)2154 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, 2155 const Ts &... Args) { 2156 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 2157 return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser); 2158 } 2159 2160 bool RequireLiteralType(SourceLocation Loc, QualType T, 2161 TypeDiagnoser &Diagnoser); 2162 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); 2163 2164 template <typename... Ts> RequireLiteralType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)2165 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, 2166 const Ts &...Args) { 2167 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 2168 return RequireLiteralType(Loc, T, Diagnoser); 2169 } 2170 2171 QualType getElaboratedType(ElaboratedTypeKeyword Keyword, 2172 const CXXScopeSpec &SS, QualType T, 2173 TagDecl *OwnedTagDecl = nullptr); 2174 2175 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc); 2176 /// If AsUnevaluated is false, E is treated as though it were an evaluated 2177 /// context, such as when building a type for decltype(auto). 2178 QualType BuildDecltypeType(Expr *E, SourceLocation Loc, 2179 bool AsUnevaluated = true); 2180 QualType BuildUnaryTransformType(QualType BaseType, 2181 UnaryTransformType::UTTKind UKind, 2182 SourceLocation Loc); 2183 2184 //===--------------------------------------------------------------------===// 2185 // Symbol table / Decl tracking callbacks: SemaDecl.cpp. 2186 // 2187 2188 struct SkipBodyInfo { SkipBodyInfoSkipBodyInfo2189 SkipBodyInfo() 2190 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr), 2191 New(nullptr) {} 2192 bool ShouldSkip; 2193 bool CheckSameAsPrevious; 2194 NamedDecl *Previous; 2195 NamedDecl *New; 2196 }; 2197 2198 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); 2199 2200 void DiagnoseUseOfUnimplementedSelectors(); 2201 2202 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const; 2203 2204 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 2205 Scope *S, CXXScopeSpec *SS = nullptr, 2206 bool isClassName = false, bool HasTrailingDot = false, 2207 ParsedType ObjectType = nullptr, 2208 bool IsCtorOrDtorName = false, 2209 bool WantNontrivialTypeSourceInfo = false, 2210 bool IsClassTemplateDeductionContext = true, 2211 IdentifierInfo **CorrectedII = nullptr); 2212 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); 2213 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); 2214 void DiagnoseUnknownTypeName(IdentifierInfo *&II, 2215 SourceLocation IILoc, 2216 Scope *S, 2217 CXXScopeSpec *SS, 2218 ParsedType &SuggestedType, 2219 bool IsTemplateName = false); 2220 2221 /// Attempt to behave like MSVC in situations where lookup of an unqualified 2222 /// type name has failed in a dependent context. In these situations, we 2223 /// automatically form a DependentTypeName that will retry lookup in a related 2224 /// scope during instantiation. 2225 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 2226 SourceLocation NameLoc, 2227 bool IsTemplateTypeArg); 2228 2229 /// Describes the result of the name lookup and resolution performed 2230 /// by \c ClassifyName(). 2231 enum NameClassificationKind { 2232 /// This name is not a type or template in this context, but might be 2233 /// something else. 2234 NC_Unknown, 2235 /// Classification failed; an error has been produced. 2236 NC_Error, 2237 /// The name has been typo-corrected to a keyword. 2238 NC_Keyword, 2239 /// The name was classified as a type. 2240 NC_Type, 2241 /// The name was classified as a specific non-type, non-template 2242 /// declaration. ActOnNameClassifiedAsNonType should be called to 2243 /// convert the declaration to an expression. 2244 NC_NonType, 2245 /// The name was classified as an ADL-only function name. 2246 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the 2247 /// result to an expression. 2248 NC_UndeclaredNonType, 2249 /// The name denotes a member of a dependent type that could not be 2250 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to 2251 /// convert the result to an expression. 2252 NC_DependentNonType, 2253 /// The name was classified as an overload set, and an expression 2254 /// representing that overload set has been formed. 2255 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable 2256 /// expression referencing the overload set. 2257 NC_OverloadSet, 2258 /// The name was classified as a template whose specializations are types. 2259 NC_TypeTemplate, 2260 /// The name was classified as a variable template name. 2261 NC_VarTemplate, 2262 /// The name was classified as a function template name. 2263 NC_FunctionTemplate, 2264 /// The name was classified as an ADL-only function template name. 2265 NC_UndeclaredTemplate, 2266 /// The name was classified as a concept name. 2267 NC_Concept, 2268 }; 2269 2270 class NameClassification { 2271 NameClassificationKind Kind; 2272 union { 2273 ExprResult Expr; 2274 NamedDecl *NonTypeDecl; 2275 TemplateName Template; 2276 ParsedType Type; 2277 }; 2278 NameClassification(NameClassificationKind Kind)2279 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} 2280 2281 public: NameClassification(ParsedType Type)2282 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} 2283 NameClassification(const IdentifierInfo * Keyword)2284 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {} 2285 Error()2286 static NameClassification Error() { 2287 return NameClassification(NC_Error); 2288 } 2289 Unknown()2290 static NameClassification Unknown() { 2291 return NameClassification(NC_Unknown); 2292 } 2293 OverloadSet(ExprResult E)2294 static NameClassification OverloadSet(ExprResult E) { 2295 NameClassification Result(NC_OverloadSet); 2296 Result.Expr = E; 2297 return Result; 2298 } 2299 NonType(NamedDecl * D)2300 static NameClassification NonType(NamedDecl *D) { 2301 NameClassification Result(NC_NonType); 2302 Result.NonTypeDecl = D; 2303 return Result; 2304 } 2305 UndeclaredNonType()2306 static NameClassification UndeclaredNonType() { 2307 return NameClassification(NC_UndeclaredNonType); 2308 } 2309 DependentNonType()2310 static NameClassification DependentNonType() { 2311 return NameClassification(NC_DependentNonType); 2312 } 2313 TypeTemplate(TemplateName Name)2314 static NameClassification TypeTemplate(TemplateName Name) { 2315 NameClassification Result(NC_TypeTemplate); 2316 Result.Template = Name; 2317 return Result; 2318 } 2319 VarTemplate(TemplateName Name)2320 static NameClassification VarTemplate(TemplateName Name) { 2321 NameClassification Result(NC_VarTemplate); 2322 Result.Template = Name; 2323 return Result; 2324 } 2325 FunctionTemplate(TemplateName Name)2326 static NameClassification FunctionTemplate(TemplateName Name) { 2327 NameClassification Result(NC_FunctionTemplate); 2328 Result.Template = Name; 2329 return Result; 2330 } 2331 Concept(TemplateName Name)2332 static NameClassification Concept(TemplateName Name) { 2333 NameClassification Result(NC_Concept); 2334 Result.Template = Name; 2335 return Result; 2336 } 2337 UndeclaredTemplate(TemplateName Name)2338 static NameClassification UndeclaredTemplate(TemplateName Name) { 2339 NameClassification Result(NC_UndeclaredTemplate); 2340 Result.Template = Name; 2341 return Result; 2342 } 2343 getKind()2344 NameClassificationKind getKind() const { return Kind; } 2345 getExpression()2346 ExprResult getExpression() const { 2347 assert(Kind == NC_OverloadSet); 2348 return Expr; 2349 } 2350 getType()2351 ParsedType getType() const { 2352 assert(Kind == NC_Type); 2353 return Type; 2354 } 2355 getNonTypeDecl()2356 NamedDecl *getNonTypeDecl() const { 2357 assert(Kind == NC_NonType); 2358 return NonTypeDecl; 2359 } 2360 getTemplateName()2361 TemplateName getTemplateName() const { 2362 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || 2363 Kind == NC_VarTemplate || Kind == NC_Concept || 2364 Kind == NC_UndeclaredTemplate); 2365 return Template; 2366 } 2367 getTemplateNameKind()2368 TemplateNameKind getTemplateNameKind() const { 2369 switch (Kind) { 2370 case NC_TypeTemplate: 2371 return TNK_Type_template; 2372 case NC_FunctionTemplate: 2373 return TNK_Function_template; 2374 case NC_VarTemplate: 2375 return TNK_Var_template; 2376 case NC_Concept: 2377 return TNK_Concept_template; 2378 case NC_UndeclaredTemplate: 2379 return TNK_Undeclared_template; 2380 default: 2381 llvm_unreachable("unsupported name classification."); 2382 } 2383 } 2384 }; 2385 2386 /// Perform name lookup on the given name, classifying it based on 2387 /// the results of name lookup and the following token. 2388 /// 2389 /// This routine is used by the parser to resolve identifiers and help direct 2390 /// parsing. When the identifier cannot be found, this routine will attempt 2391 /// to correct the typo and classify based on the resulting name. 2392 /// 2393 /// \param S The scope in which we're performing name lookup. 2394 /// 2395 /// \param SS The nested-name-specifier that precedes the name. 2396 /// 2397 /// \param Name The identifier. If typo correction finds an alternative name, 2398 /// this pointer parameter will be updated accordingly. 2399 /// 2400 /// \param NameLoc The location of the identifier. 2401 /// 2402 /// \param NextToken The token following the identifier. Used to help 2403 /// disambiguate the name. 2404 /// 2405 /// \param CCC The correction callback, if typo correction is desired. 2406 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, 2407 IdentifierInfo *&Name, SourceLocation NameLoc, 2408 const Token &NextToken, 2409 CorrectionCandidateCallback *CCC = nullptr); 2410 2411 /// Act on the result of classifying a name as an undeclared (ADL-only) 2412 /// non-type declaration. 2413 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 2414 SourceLocation NameLoc); 2415 /// Act on the result of classifying a name as an undeclared member of a 2416 /// dependent base class. 2417 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 2418 IdentifierInfo *Name, 2419 SourceLocation NameLoc, 2420 bool IsAddressOfOperand); 2421 /// Act on the result of classifying a name as a specific non-type 2422 /// declaration. 2423 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 2424 NamedDecl *Found, 2425 SourceLocation NameLoc, 2426 const Token &NextToken); 2427 /// Act on the result of classifying a name as an overload set. 2428 ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet); 2429 2430 /// Describes the detailed kind of a template name. Used in diagnostics. 2431 enum class TemplateNameKindForDiagnostics { 2432 ClassTemplate, 2433 FunctionTemplate, 2434 VarTemplate, 2435 AliasTemplate, 2436 TemplateTemplateParam, 2437 Concept, 2438 DependentTemplate 2439 }; 2440 TemplateNameKindForDiagnostics 2441 getTemplateNameKindForDiagnostics(TemplateName Name); 2442 2443 /// Determine whether it's plausible that E was intended to be a 2444 /// template-name. mightBeIntendedToBeTemplateName(ExprResult E,bool & Dependent)2445 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) { 2446 if (!getLangOpts().CPlusPlus || E.isInvalid()) 2447 return false; 2448 Dependent = false; 2449 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get())) 2450 return !DRE->hasExplicitTemplateArgs(); 2451 if (auto *ME = dyn_cast<MemberExpr>(E.get())) 2452 return !ME->hasExplicitTemplateArgs(); 2453 Dependent = true; 2454 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get())) 2455 return !DSDRE->hasExplicitTemplateArgs(); 2456 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get())) 2457 return !DSME->hasExplicitTemplateArgs(); 2458 // Any additional cases recognized here should also be handled by 2459 // diagnoseExprIntendedAsTemplateName. 2460 return false; 2461 } 2462 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, 2463 SourceLocation Less, 2464 SourceLocation Greater); 2465 2466 Decl *ActOnDeclarator(Scope *S, Declarator &D); 2467 2468 NamedDecl *HandleDeclarator(Scope *S, Declarator &D, 2469 MultiTemplateParamsArg TemplateParameterLists); 2470 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S); 2471 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); 2472 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 2473 DeclarationName Name, SourceLocation Loc, 2474 bool IsTemplateId); 2475 void 2476 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, 2477 SourceLocation FallbackLoc, 2478 SourceLocation ConstQualLoc = SourceLocation(), 2479 SourceLocation VolatileQualLoc = SourceLocation(), 2480 SourceLocation RestrictQualLoc = SourceLocation(), 2481 SourceLocation AtomicQualLoc = SourceLocation(), 2482 SourceLocation UnalignedQualLoc = SourceLocation()); 2483 2484 static bool adjustContextForLocalExternDecl(DeclContext *&DC); 2485 void DiagnoseFunctionSpecifiers(const DeclSpec &DS); 2486 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D, 2487 const LookupResult &R); 2488 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R); 2489 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 2490 const LookupResult &R); 2491 void CheckShadow(Scope *S, VarDecl *D); 2492 2493 /// Warn if 'E', which is an expression that is about to be modified, refers 2494 /// to a shadowing declaration. 2495 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc); 2496 2497 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI); 2498 2499 private: 2500 /// Map of current shadowing declarations to shadowed declarations. Warn if 2501 /// it looks like the user is trying to modify the shadowing declaration. 2502 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls; 2503 2504 public: 2505 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); 2506 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope); 2507 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 2508 TypedefNameDecl *NewTD); 2509 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); 2510 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 2511 TypeSourceInfo *TInfo, 2512 LookupResult &Previous); 2513 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, 2514 LookupResult &Previous, bool &Redeclaration); 2515 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 2516 TypeSourceInfo *TInfo, 2517 LookupResult &Previous, 2518 MultiTemplateParamsArg TemplateParamLists, 2519 bool &AddToScope, 2520 ArrayRef<BindingDecl *> Bindings = None); 2521 NamedDecl * 2522 ActOnDecompositionDeclarator(Scope *S, Declarator &D, 2523 MultiTemplateParamsArg TemplateParamLists); 2524 // Returns true if the variable declaration is a redeclaration 2525 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); 2526 void CheckVariableDeclarationType(VarDecl *NewVD); 2527 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 2528 Expr *Init); 2529 void CheckCompleteVariableDeclaration(VarDecl *VD); 2530 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD); 2531 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); 2532 2533 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, 2534 TypeSourceInfo *TInfo, 2535 LookupResult &Previous, 2536 MultiTemplateParamsArg TemplateParamLists, 2537 bool &AddToScope); 2538 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); 2539 2540 enum class CheckConstexprKind { 2541 /// Diagnose issues that are non-constant or that are extensions. 2542 Diagnose, 2543 /// Identify whether this function satisfies the formal rules for constexpr 2544 /// functions in the current lanugage mode (with no extensions). 2545 CheckValid 2546 }; 2547 2548 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, 2549 CheckConstexprKind Kind); 2550 2551 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); 2552 void FindHiddenVirtualMethods(CXXMethodDecl *MD, 2553 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); 2554 void NoteHiddenVirtualMethods(CXXMethodDecl *MD, 2555 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); 2556 // Returns true if the function declaration is a redeclaration 2557 bool CheckFunctionDeclaration(Scope *S, 2558 FunctionDecl *NewFD, LookupResult &Previous, 2559 bool IsMemberSpecialization); 2560 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl); 2561 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 2562 QualType NewT, QualType OldT); 2563 void CheckMain(FunctionDecl *FD, const DeclSpec &D); 2564 void CheckMSVCRTEntryPoint(FunctionDecl *FD); 2565 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 2566 bool IsDefinition); 2567 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D); 2568 Decl *ActOnParamDeclarator(Scope *S, Declarator &D); 2569 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, 2570 SourceLocation Loc, 2571 QualType T); 2572 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, 2573 SourceLocation NameLoc, IdentifierInfo *Name, 2574 QualType T, TypeSourceInfo *TSInfo, 2575 StorageClass SC); 2576 void ActOnParamDefaultArgument(Decl *param, 2577 SourceLocation EqualLoc, 2578 Expr *defarg); 2579 void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, 2580 SourceLocation ArgLoc); 2581 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc); 2582 ExprResult ConvertParamDefaultArgument(const ParmVarDecl *Param, 2583 Expr *DefaultArg, 2584 SourceLocation EqualLoc); 2585 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, 2586 SourceLocation EqualLoc); 2587 2588 // Contexts where using non-trivial C union types can be disallowed. This is 2589 // passed to err_non_trivial_c_union_in_invalid_context. 2590 enum NonTrivialCUnionContext { 2591 // Function parameter. 2592 NTCUC_FunctionParam, 2593 // Function return. 2594 NTCUC_FunctionReturn, 2595 // Default-initialized object. 2596 NTCUC_DefaultInitializedObject, 2597 // Variable with automatic storage duration. 2598 NTCUC_AutoVar, 2599 // Initializer expression that might copy from another object. 2600 NTCUC_CopyInit, 2601 // Assignment. 2602 NTCUC_Assignment, 2603 // Compound literal. 2604 NTCUC_CompoundLiteral, 2605 // Block capture. 2606 NTCUC_BlockCapture, 2607 // lvalue-to-rvalue conversion of volatile type. 2608 NTCUC_LValueToRValueVolatile, 2609 }; 2610 2611 /// Emit diagnostics if the initializer or any of its explicit or 2612 /// implicitly-generated subexpressions require copying or 2613 /// default-initializing a type that is or contains a C union type that is 2614 /// non-trivial to copy or default-initialize. 2615 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc); 2616 2617 // These flags are passed to checkNonTrivialCUnion. 2618 enum NonTrivialCUnionKind { 2619 NTCUK_Init = 0x1, 2620 NTCUK_Destruct = 0x2, 2621 NTCUK_Copy = 0x4, 2622 }; 2623 2624 /// Emit diagnostics if a non-trivial C union type or a struct that contains 2625 /// a non-trivial C union is used in an invalid context. 2626 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 2627 NonTrivialCUnionContext UseContext, 2628 unsigned NonTrivialKind); 2629 2630 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit); 2631 void ActOnUninitializedDecl(Decl *dcl); 2632 void ActOnInitializerError(Decl *Dcl); 2633 2634 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc); 2635 void ActOnCXXForRangeDecl(Decl *D); 2636 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 2637 IdentifierInfo *Ident, 2638 ParsedAttributes &Attrs, 2639 SourceLocation AttrEnd); 2640 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); 2641 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); 2642 void CheckStaticLocalForDllExport(VarDecl *VD); 2643 void FinalizeDeclaration(Decl *D); 2644 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 2645 ArrayRef<Decl *> Group); 2646 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group); 2647 2648 /// Should be called on all declarations that might have attached 2649 /// documentation comments. 2650 void ActOnDocumentableDecl(Decl *D); 2651 void ActOnDocumentableDecls(ArrayRef<Decl *> Group); 2652 2653 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 2654 SourceLocation LocAfterDecls); 2655 void CheckForFunctionRedefinition( 2656 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr, 2657 SkipBodyInfo *SkipBody = nullptr); 2658 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D, 2659 MultiTemplateParamsArg TemplateParamLists, 2660 SkipBodyInfo *SkipBody = nullptr); 2661 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D, 2662 SkipBodyInfo *SkipBody = nullptr); 2663 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D); 2664 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr); 2665 ExprResult ActOnRequiresClause(ExprResult ConstraintExpr); 2666 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); isObjCMethodDecl(Decl * D)2667 bool isObjCMethodDecl(Decl *D) { 2668 return D && isa<ObjCMethodDecl>(D); 2669 } 2670 2671 /// Determine whether we can delay parsing the body of a function or 2672 /// function template until it is used, assuming we don't care about emitting 2673 /// code for that function. 2674 /// 2675 /// This will be \c false if we may need the body of the function in the 2676 /// middle of parsing an expression (where it's impractical to switch to 2677 /// parsing a different function), for instance, if it's constexpr in C++11 2678 /// or has an 'auto' return type in C++14. These cases are essentially bugs. 2679 bool canDelayFunctionBody(const Declarator &D); 2680 2681 /// Determine whether we can skip parsing the body of a function 2682 /// definition, assuming we don't care about analyzing its body or emitting 2683 /// code for that function. 2684 /// 2685 /// This will be \c false only if we may need the body of the function in 2686 /// order to parse the rest of the program (for instance, if it is 2687 /// \c constexpr in C++11 or has an 'auto' return type in C++14). 2688 bool canSkipFunctionBody(Decl *D); 2689 2690 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); 2691 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); 2692 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); 2693 Decl *ActOnSkippedFunctionBody(Decl *Decl); 2694 void ActOnFinishInlineFunctionDef(FunctionDecl *D); 2695 2696 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an 2697 /// attribute for which parsing is delayed. 2698 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); 2699 2700 /// Diagnose any unused parameters in the given sequence of 2701 /// ParmVarDecl pointers. 2702 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters); 2703 2704 /// Diagnose whether the size of parameters or return value of a 2705 /// function or obj-c method definition is pass-by-value and larger than a 2706 /// specified threshold. 2707 void 2708 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters, 2709 QualType ReturnTy, NamedDecl *D); 2710 2711 void DiagnoseInvalidJumps(Stmt *Body); 2712 Decl *ActOnFileScopeAsmDecl(Expr *expr, 2713 SourceLocation AsmLoc, 2714 SourceLocation RParenLoc); 2715 2716 /// Handle a C++11 empty-declaration and attribute-declaration. 2717 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, 2718 SourceLocation SemiLoc); 2719 2720 enum class ModuleDeclKind { 2721 Interface, ///< 'export module X;' 2722 Implementation, ///< 'module X;' 2723 }; 2724 2725 /// The parser has processed a module-declaration that begins the definition 2726 /// of a module interface or implementation. 2727 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, 2728 SourceLocation ModuleLoc, ModuleDeclKind MDK, 2729 ModuleIdPath Path, bool IsFirstDecl); 2730 2731 /// The parser has processed a global-module-fragment declaration that begins 2732 /// the definition of the global module fragment of the current module unit. 2733 /// \param ModuleLoc The location of the 'module' keyword. 2734 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc); 2735 2736 /// The parser has processed a private-module-fragment declaration that begins 2737 /// the definition of the private module fragment of the current module unit. 2738 /// \param ModuleLoc The location of the 'module' keyword. 2739 /// \param PrivateLoc The location of the 'private' keyword. 2740 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, 2741 SourceLocation PrivateLoc); 2742 2743 /// The parser has processed a module import declaration. 2744 /// 2745 /// \param StartLoc The location of the first token in the declaration. This 2746 /// could be the location of an '@', 'export', or 'import'. 2747 /// \param ExportLoc The location of the 'export' keyword, if any. 2748 /// \param ImportLoc The location of the 'import' keyword. 2749 /// \param Path The module access path. 2750 DeclResult ActOnModuleImport(SourceLocation StartLoc, 2751 SourceLocation ExportLoc, 2752 SourceLocation ImportLoc, ModuleIdPath Path); 2753 DeclResult ActOnModuleImport(SourceLocation StartLoc, 2754 SourceLocation ExportLoc, 2755 SourceLocation ImportLoc, Module *M, 2756 ModuleIdPath Path = {}); 2757 2758 /// The parser has processed a module import translated from a 2759 /// #include or similar preprocessing directive. 2760 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod); 2761 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod); 2762 2763 /// The parsed has entered a submodule. 2764 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod); 2765 /// The parser has left a submodule. 2766 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod); 2767 2768 /// Create an implicit import of the given module at the given 2769 /// source location, for error recovery, if possible. 2770 /// 2771 /// This routine is typically used when an entity found by name lookup 2772 /// is actually hidden within a module that we know about but the user 2773 /// has forgotten to import. 2774 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 2775 Module *Mod); 2776 2777 /// Kinds of missing import. Note, the values of these enumerators correspond 2778 /// to %select values in diagnostics. 2779 enum class MissingImportKind { 2780 Declaration, 2781 Definition, 2782 DefaultArgument, 2783 ExplicitSpecialization, 2784 PartialSpecialization 2785 }; 2786 2787 /// Diagnose that the specified declaration needs to be visible but 2788 /// isn't, and suggest a module import that would resolve the problem. 2789 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, 2790 MissingImportKind MIK, bool Recover = true); 2791 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, 2792 SourceLocation DeclLoc, ArrayRef<Module *> Modules, 2793 MissingImportKind MIK, bool Recover); 2794 2795 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 2796 SourceLocation LBraceLoc); 2797 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, 2798 SourceLocation RBraceLoc); 2799 2800 /// We've found a use of a templated declaration that would trigger an 2801 /// implicit instantiation. Check that any relevant explicit specializations 2802 /// and partial specializations are visible, and diagnose if not. 2803 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); 2804 2805 /// Retrieve a suitable printing policy for diagnostics. getPrintingPolicy()2806 PrintingPolicy getPrintingPolicy() const { 2807 return getPrintingPolicy(Context, PP); 2808 } 2809 2810 /// Retrieve a suitable printing policy for diagnostics. 2811 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, 2812 const Preprocessor &PP); 2813 2814 /// Scope actions. 2815 void ActOnPopScope(SourceLocation Loc, Scope *S); 2816 void ActOnTranslationUnitScope(Scope *S); 2817 2818 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 2819 RecordDecl *&AnonRecord); 2820 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 2821 MultiTemplateParamsArg TemplateParams, 2822 bool IsExplicitInstantiation, 2823 RecordDecl *&AnonRecord); 2824 2825 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 2826 AccessSpecifier AS, 2827 RecordDecl *Record, 2828 const PrintingPolicy &Policy); 2829 2830 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 2831 RecordDecl *Record); 2832 2833 /// Common ways to introduce type names without a tag for use in diagnostics. 2834 /// Keep in sync with err_tag_reference_non_tag. 2835 enum NonTagKind { 2836 NTK_NonStruct, 2837 NTK_NonClass, 2838 NTK_NonUnion, 2839 NTK_NonEnum, 2840 NTK_Typedef, 2841 NTK_TypeAlias, 2842 NTK_Template, 2843 NTK_TypeAliasTemplate, 2844 NTK_TemplateTemplateArgument, 2845 }; 2846 2847 /// Given a non-tag type declaration, returns an enum useful for indicating 2848 /// what kind of non-tag type this is. 2849 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK); 2850 2851 bool isAcceptableTagRedeclaration(const TagDecl *Previous, 2852 TagTypeKind NewTag, bool isDefinition, 2853 SourceLocation NewTagLoc, 2854 const IdentifierInfo *Name); 2855 2856 enum TagUseKind { 2857 TUK_Reference, // Reference to a tag: 'struct foo *X;' 2858 TUK_Declaration, // Fwd decl of a tag: 'struct foo;' 2859 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' 2860 TUK_Friend // Friend declaration: 'friend struct foo;' 2861 }; 2862 2863 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 2864 SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, 2865 SourceLocation NameLoc, const ParsedAttributesView &Attr, 2866 AccessSpecifier AS, SourceLocation ModulePrivateLoc, 2867 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, 2868 bool &IsDependent, SourceLocation ScopedEnumKWLoc, 2869 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 2870 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 2871 SkipBodyInfo *SkipBody = nullptr); 2872 2873 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 2874 unsigned TagSpec, SourceLocation TagLoc, 2875 CXXScopeSpec &SS, IdentifierInfo *Name, 2876 SourceLocation NameLoc, 2877 const ParsedAttributesView &Attr, 2878 MultiTemplateParamsArg TempParamLists); 2879 2880 TypeResult ActOnDependentTag(Scope *S, 2881 unsigned TagSpec, 2882 TagUseKind TUK, 2883 const CXXScopeSpec &SS, 2884 IdentifierInfo *Name, 2885 SourceLocation TagLoc, 2886 SourceLocation NameLoc); 2887 2888 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, 2889 IdentifierInfo *ClassName, 2890 SmallVectorImpl<Decl *> &Decls); 2891 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 2892 Declarator &D, Expr *BitfieldWidth); 2893 2894 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, 2895 Declarator &D, Expr *BitfieldWidth, 2896 InClassInitStyle InitStyle, 2897 AccessSpecifier AS); 2898 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, 2899 SourceLocation DeclStart, Declarator &D, 2900 Expr *BitfieldWidth, 2901 InClassInitStyle InitStyle, 2902 AccessSpecifier AS, 2903 const ParsedAttr &MSPropertyAttr); 2904 2905 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, 2906 TypeSourceInfo *TInfo, 2907 RecordDecl *Record, SourceLocation Loc, 2908 bool Mutable, Expr *BitfieldWidth, 2909 InClassInitStyle InitStyle, 2910 SourceLocation TSSL, 2911 AccessSpecifier AS, NamedDecl *PrevDecl, 2912 Declarator *D = nullptr); 2913 2914 bool CheckNontrivialField(FieldDecl *FD); 2915 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM); 2916 2917 enum TrivialABIHandling { 2918 /// The triviality of a method unaffected by "trivial_abi". 2919 TAH_IgnoreTrivialABI, 2920 2921 /// The triviality of a method affected by "trivial_abi". 2922 TAH_ConsiderTrivialABI 2923 }; 2924 2925 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 2926 TrivialABIHandling TAH = TAH_IgnoreTrivialABI, 2927 bool Diagnose = false); 2928 2929 /// For a defaulted function, the kind of defaulted function that it is. 2930 class DefaultedFunctionKind { 2931 CXXSpecialMember SpecialMember : 8; 2932 DefaultedComparisonKind Comparison : 8; 2933 2934 public: DefaultedFunctionKind()2935 DefaultedFunctionKind() 2936 : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) { 2937 } DefaultedFunctionKind(CXXSpecialMember CSM)2938 DefaultedFunctionKind(CXXSpecialMember CSM) 2939 : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {} DefaultedFunctionKind(DefaultedComparisonKind Comp)2940 DefaultedFunctionKind(DefaultedComparisonKind Comp) 2941 : SpecialMember(CXXInvalid), Comparison(Comp) {} 2942 isSpecialMember()2943 bool isSpecialMember() const { return SpecialMember != CXXInvalid; } isComparison()2944 bool isComparison() const { 2945 return Comparison != DefaultedComparisonKind::None; 2946 } 2947 2948 explicit operator bool() const { 2949 return isSpecialMember() || isComparison(); 2950 } 2951 asSpecialMember()2952 CXXSpecialMember asSpecialMember() const { return SpecialMember; } asComparison()2953 DefaultedComparisonKind asComparison() const { return Comparison; } 2954 2955 /// Get the index of this function kind for use in diagnostics. getDiagnosticIndex()2956 unsigned getDiagnosticIndex() const { 2957 static_assert(CXXInvalid > CXXDestructor, 2958 "invalid should have highest index"); 2959 static_assert((unsigned)DefaultedComparisonKind::None == 0, 2960 "none should be equal to zero"); 2961 return SpecialMember + (unsigned)Comparison; 2962 } 2963 }; 2964 2965 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD); 2966 getSpecialMember(const CXXMethodDecl * MD)2967 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) { 2968 return getDefaultedFunctionKind(MD).asSpecialMember(); 2969 } getDefaultedComparisonKind(const FunctionDecl * FD)2970 DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) { 2971 return getDefaultedFunctionKind(FD).asComparison(); 2972 } 2973 2974 void ActOnLastBitfield(SourceLocation DeclStart, 2975 SmallVectorImpl<Decl *> &AllIvarDecls); 2976 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, 2977 Declarator &D, Expr *BitfieldWidth, 2978 tok::ObjCKeywordKind visibility); 2979 2980 // This is used for both record definitions and ObjC interface declarations. 2981 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, 2982 ArrayRef<Decl *> Fields, SourceLocation LBrac, 2983 SourceLocation RBrac, const ParsedAttributesView &AttrList); 2984 2985 /// ActOnTagStartDefinition - Invoked when we have entered the 2986 /// scope of a tag's definition (e.g., for an enumeration, class, 2987 /// struct, or union). 2988 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); 2989 2990 /// Perform ODR-like check for C/ObjC when merging tag types from modules. 2991 /// Differently from C++, actually parse the body and reject / error out 2992 /// in case of a structural mismatch. 2993 bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 2994 SkipBodyInfo &SkipBody); 2995 2996 typedef void *SkippedDefinitionContext; 2997 2998 /// Invoked when we enter a tag definition that we're skipping. 2999 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD); 3000 3001 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl); 3002 3003 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a 3004 /// C++ record definition's base-specifiers clause and are starting its 3005 /// member declarations. 3006 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, 3007 SourceLocation FinalLoc, 3008 bool IsFinalSpelledSealed, 3009 SourceLocation LBraceLoc); 3010 3011 /// ActOnTagFinishDefinition - Invoked once we have finished parsing 3012 /// the definition of a tag (enumeration, class, struct, or union). 3013 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, 3014 SourceRange BraceRange); 3015 3016 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context); 3017 3018 void ActOnObjCContainerFinishDefinition(); 3019 3020 /// Invoked when we must temporarily exit the objective-c container 3021 /// scope for parsing/looking-up C constructs. 3022 /// 3023 /// Must be followed by a call to \see ActOnObjCReenterContainerContext 3024 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC); 3025 void ActOnObjCReenterContainerContext(DeclContext *DC); 3026 3027 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable 3028 /// error parsing the definition of a tag. 3029 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); 3030 3031 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, 3032 EnumConstantDecl *LastEnumConst, 3033 SourceLocation IdLoc, 3034 IdentifierInfo *Id, 3035 Expr *val); 3036 bool CheckEnumUnderlyingType(TypeSourceInfo *TI); 3037 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 3038 QualType EnumUnderlyingTy, bool IsFixed, 3039 const EnumDecl *Prev); 3040 3041 /// Determine whether the body of an anonymous enumeration should be skipped. 3042 /// \param II The name of the first enumerator. 3043 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 3044 SourceLocation IILoc); 3045 3046 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, 3047 SourceLocation IdLoc, IdentifierInfo *Id, 3048 const ParsedAttributesView &Attrs, 3049 SourceLocation EqualLoc, Expr *Val); 3050 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 3051 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S, 3052 const ParsedAttributesView &Attr); 3053 3054 /// Set the current declaration context until it gets popped. 3055 void PushDeclContext(Scope *S, DeclContext *DC); 3056 void PopDeclContext(); 3057 3058 /// EnterDeclaratorContext - Used when we must lookup names in the context 3059 /// of a declarator's nested name specifier. 3060 void EnterDeclaratorContext(Scope *S, DeclContext *DC); 3061 void ExitDeclaratorContext(Scope *S); 3062 3063 /// Enter a template parameter scope, after it's been associated with a particular 3064 /// DeclContext. Causes lookup within the scope to chain through enclosing contexts 3065 /// in the correct order. 3066 void EnterTemplatedContext(Scope *S, DeclContext *DC); 3067 3068 /// Push the parameters of D, which must be a function, into scope. 3069 void ActOnReenterFunctionContext(Scope* S, Decl* D); 3070 void ActOnExitFunctionContext(); 3071 3072 DeclContext *getFunctionLevelDeclContext(); 3073 3074 /// getCurFunctionDecl - If inside of a function body, this returns a pointer 3075 /// to the function decl for the function being parsed. If we're currently 3076 /// in a 'block', this returns the containing context. 3077 FunctionDecl *getCurFunctionDecl(); 3078 3079 /// getCurMethodDecl - If inside of a method body, this returns a pointer to 3080 /// the method decl for the method being parsed. If we're currently 3081 /// in a 'block', this returns the containing context. 3082 ObjCMethodDecl *getCurMethodDecl(); 3083 3084 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method 3085 /// or C function we're in, otherwise return null. If we're currently 3086 /// in a 'block', this returns the containing context. 3087 NamedDecl *getCurFunctionOrMethodDecl(); 3088 3089 /// Add this decl to the scope shadowed decl chains. 3090 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); 3091 3092 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true 3093 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns 3094 /// true if 'D' belongs to the given declaration context. 3095 /// 3096 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the 3097 /// enclosing namespace set of the context, rather than contained 3098 /// directly within it. 3099 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr, 3100 bool AllowInlineNamespace = false); 3101 3102 /// Finds the scope corresponding to the given decl context, if it 3103 /// happens to be an enclosing scope. Otherwise return NULL. 3104 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); 3105 3106 /// Subroutines of ActOnDeclarator(). 3107 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 3108 TypeSourceInfo *TInfo); 3109 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New); 3110 3111 /// Describes the kind of merge to perform for availability 3112 /// attributes (including "deprecated", "unavailable", and "availability"). 3113 enum AvailabilityMergeKind { 3114 /// Don't merge availability attributes at all. 3115 AMK_None, 3116 /// Merge availability attributes for a redeclaration, which requires 3117 /// an exact match. 3118 AMK_Redeclaration, 3119 /// Merge availability attributes for an override, which requires 3120 /// an exact match or a weakening of constraints. 3121 AMK_Override, 3122 /// Merge availability attributes for an implementation of 3123 /// a protocol requirement. 3124 AMK_ProtocolImplementation, 3125 }; 3126 3127 /// Describes the kind of priority given to an availability attribute. 3128 /// 3129 /// The sum of priorities deteremines the final priority of the attribute. 3130 /// The final priority determines how the attribute will be merged. 3131 /// An attribute with a lower priority will always remove higher priority 3132 /// attributes for the specified platform when it is being applied. An 3133 /// attribute with a higher priority will not be applied if the declaration 3134 /// already has an availability attribute with a lower priority for the 3135 /// specified platform. The final prirority values are not expected to match 3136 /// the values in this enumeration, but instead should be treated as a plain 3137 /// integer value. This enumeration just names the priority weights that are 3138 /// used to calculate that final vaue. 3139 enum AvailabilityPriority : int { 3140 /// The availability attribute was specified explicitly next to the 3141 /// declaration. 3142 AP_Explicit = 0, 3143 3144 /// The availability attribute was applied using '#pragma clang attribute'. 3145 AP_PragmaClangAttribute = 1, 3146 3147 /// The availability attribute for a specific platform was inferred from 3148 /// an availability attribute for another platform. 3149 AP_InferredFromOtherPlatform = 2 3150 }; 3151 3152 /// Attribute merging methods. Return true if a new attribute was added. 3153 AvailabilityAttr * 3154 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, 3155 IdentifierInfo *Platform, bool Implicit, 3156 VersionTuple Introduced, VersionTuple Deprecated, 3157 VersionTuple Obsoleted, bool IsUnavailable, 3158 StringRef Message, bool IsStrict, StringRef Replacement, 3159 AvailabilityMergeKind AMK, int Priority); 3160 TypeVisibilityAttr * 3161 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, 3162 TypeVisibilityAttr::VisibilityType Vis); 3163 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, 3164 VisibilityAttr::VisibilityType Vis); 3165 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, 3166 StringRef UuidAsWritten, MSGuidDecl *GuidDecl); 3167 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI); 3168 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI); 3169 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D, 3170 const AttributeCommonInfo &CI, 3171 bool BestCase, 3172 MSInheritanceModel Model); 3173 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, 3174 IdentifierInfo *Format, int FormatIdx, 3175 int FirstArg); 3176 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, 3177 StringRef Name); 3178 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, 3179 StringRef Name); 3180 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, 3181 const AttributeCommonInfo &CI, 3182 const IdentifierInfo *Ident); 3183 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI); 3184 NoSpeculativeLoadHardeningAttr * 3185 mergeNoSpeculativeLoadHardeningAttr(Decl *D, 3186 const NoSpeculativeLoadHardeningAttr &AL); 3187 SpeculativeLoadHardeningAttr * 3188 mergeSpeculativeLoadHardeningAttr(Decl *D, 3189 const SpeculativeLoadHardeningAttr &AL); 3190 SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA, 3191 StringRef Name); 3192 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, 3193 const AttributeCommonInfo &CI); 3194 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL); 3195 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, 3196 const InternalLinkageAttr &AL); 3197 CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL); 3198 CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL); 3199 WebAssemblyImportNameAttr *mergeImportNameAttr( 3200 Decl *D, const WebAssemblyImportNameAttr &AL); 3201 WebAssemblyImportModuleAttr *mergeImportModuleAttr( 3202 Decl *D, const WebAssemblyImportModuleAttr &AL); 3203 3204 void mergeDeclAttributes(NamedDecl *New, Decl *Old, 3205 AvailabilityMergeKind AMK = AMK_Redeclaration); 3206 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 3207 LookupResult &OldDecls); 3208 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, 3209 bool MergeTypeWithOld); 3210 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3211 Scope *S, bool MergeTypeWithOld); 3212 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); 3213 void MergeVarDecl(VarDecl *New, LookupResult &Previous); 3214 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld); 3215 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); 3216 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn); 3217 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New); 3218 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); 3219 3220 // AssignmentAction - This is used by all the assignment diagnostic functions 3221 // to represent what is actually causing the operation 3222 enum AssignmentAction { 3223 AA_Assigning, 3224 AA_Passing, 3225 AA_Returning, 3226 AA_Converting, 3227 AA_Initializing, 3228 AA_Sending, 3229 AA_Casting, 3230 AA_Passing_CFAudited 3231 }; 3232 3233 /// C++ Overloading. 3234 enum OverloadKind { 3235 /// This is a legitimate overload: the existing declarations are 3236 /// functions or function templates with different signatures. 3237 Ovl_Overload, 3238 3239 /// This is not an overload because the signature exactly matches 3240 /// an existing declaration. 3241 Ovl_Match, 3242 3243 /// This is not an overload because the lookup results contain a 3244 /// non-function. 3245 Ovl_NonFunction 3246 }; 3247 OverloadKind CheckOverload(Scope *S, 3248 FunctionDecl *New, 3249 const LookupResult &OldDecls, 3250 NamedDecl *&OldDecl, 3251 bool IsForUsingDecl); 3252 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl, 3253 bool ConsiderCudaAttrs = true, 3254 bool ConsiderRequiresClauses = true); 3255 3256 enum class AllowedExplicit { 3257 /// Allow no explicit functions to be used. 3258 None, 3259 /// Allow explicit conversion functions but not explicit constructors. 3260 Conversions, 3261 /// Allow both explicit conversion functions and explicit constructors. 3262 All 3263 }; 3264 3265 ImplicitConversionSequence 3266 TryImplicitConversion(Expr *From, QualType ToType, 3267 bool SuppressUserConversions, 3268 AllowedExplicit AllowExplicit, 3269 bool InOverloadResolution, 3270 bool CStyle, 3271 bool AllowObjCWritebackConversion); 3272 3273 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); 3274 bool IsFloatingPointPromotion(QualType FromType, QualType ToType); 3275 bool IsComplexPromotion(QualType FromType, QualType ToType); 3276 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 3277 bool InOverloadResolution, 3278 QualType& ConvertedType, bool &IncompatibleObjC); 3279 bool isObjCPointerConversion(QualType FromType, QualType ToType, 3280 QualType& ConvertedType, bool &IncompatibleObjC); 3281 bool isObjCWritebackConversion(QualType FromType, QualType ToType, 3282 QualType &ConvertedType); 3283 bool IsBlockPointerConversion(QualType FromType, QualType ToType, 3284 QualType& ConvertedType); 3285 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 3286 const FunctionProtoType *NewType, 3287 unsigned *ArgPos = nullptr); 3288 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 3289 QualType FromType, QualType ToType); 3290 3291 void maybeExtendBlockObject(ExprResult &E); 3292 CastKind PrepareCastToObjCObjectPointer(ExprResult &E); 3293 bool CheckPointerConversion(Expr *From, QualType ToType, 3294 CastKind &Kind, 3295 CXXCastPath& BasePath, 3296 bool IgnoreBaseAccess, 3297 bool Diagnose = true); 3298 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, 3299 bool InOverloadResolution, 3300 QualType &ConvertedType); 3301 bool CheckMemberPointerConversion(Expr *From, QualType ToType, 3302 CastKind &Kind, 3303 CXXCastPath &BasePath, 3304 bool IgnoreBaseAccess); 3305 bool IsQualificationConversion(QualType FromType, QualType ToType, 3306 bool CStyle, bool &ObjCLifetimeConversion); 3307 bool IsFunctionConversion(QualType FromType, QualType ToType, 3308 QualType &ResultTy); 3309 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); 3310 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg); 3311 3312 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, 3313 const VarDecl *NRVOCandidate, 3314 QualType ResultType, 3315 Expr *Value, 3316 bool AllowNRVO = true); 3317 3318 bool CanPerformAggregateInitializationForOverloadResolution( 3319 const InitializedEntity &Entity, InitListExpr *From); 3320 3321 bool IsStringInit(Expr *Init, const ArrayType *AT); 3322 3323 bool CanPerformCopyInitialization(const InitializedEntity &Entity, 3324 ExprResult Init); 3325 ExprResult PerformCopyInitialization(const InitializedEntity &Entity, 3326 SourceLocation EqualLoc, 3327 ExprResult Init, 3328 bool TopLevelOfInitList = false, 3329 bool AllowExplicit = false); 3330 ExprResult PerformObjectArgumentInitialization(Expr *From, 3331 NestedNameSpecifier *Qualifier, 3332 NamedDecl *FoundDecl, 3333 CXXMethodDecl *Method); 3334 3335 /// Check that the lifetime of the initializer (and its subobjects) is 3336 /// sufficient for initializing the entity, and perform lifetime extension 3337 /// (when permitted) if not. 3338 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init); 3339 3340 ExprResult PerformContextuallyConvertToBool(Expr *From); 3341 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); 3342 3343 /// Contexts in which a converted constant expression is required. 3344 enum CCEKind { 3345 CCEK_CaseValue, ///< Expression in a case label. 3346 CCEK_Enumerator, ///< Enumerator value with fixed underlying type. 3347 CCEK_TemplateArg, ///< Value of a non-type template parameter. 3348 CCEK_ArrayBound, ///< Array bound in array declarator or new-expression. 3349 CCEK_ConstexprIf, ///< Condition in a constexpr if statement. 3350 CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier. 3351 }; 3352 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, 3353 llvm::APSInt &Value, CCEKind CCE); 3354 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, 3355 APValue &Value, CCEKind CCE, 3356 NamedDecl *Dest = nullptr); 3357 3358 /// Abstract base class used to perform a contextual implicit 3359 /// conversion from an expression to any type passing a filter. 3360 class ContextualImplicitConverter { 3361 public: 3362 bool Suppress; 3363 bool SuppressConversion; 3364 3365 ContextualImplicitConverter(bool Suppress = false, 3366 bool SuppressConversion = false) Suppress(Suppress)3367 : Suppress(Suppress), SuppressConversion(SuppressConversion) {} 3368 3369 /// Determine whether the specified type is a valid destination type 3370 /// for this conversion. 3371 virtual bool match(QualType T) = 0; 3372 3373 /// Emits a diagnostic complaining that the expression does not have 3374 /// integral or enumeration type. 3375 virtual SemaDiagnosticBuilder 3376 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0; 3377 3378 /// Emits a diagnostic when the expression has incomplete class type. 3379 virtual SemaDiagnosticBuilder 3380 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; 3381 3382 /// Emits a diagnostic when the only matching conversion function 3383 /// is explicit. 3384 virtual SemaDiagnosticBuilder diagnoseExplicitConv( 3385 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; 3386 3387 /// Emits a note for the explicit conversion function. 3388 virtual SemaDiagnosticBuilder 3389 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; 3390 3391 /// Emits a diagnostic when there are multiple possible conversion 3392 /// functions. 3393 virtual SemaDiagnosticBuilder 3394 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0; 3395 3396 /// Emits a note for one of the candidate conversions. 3397 virtual SemaDiagnosticBuilder 3398 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; 3399 3400 /// Emits a diagnostic when we picked a conversion function 3401 /// (for cases when we are not allowed to pick a conversion function). 3402 virtual SemaDiagnosticBuilder diagnoseConversion( 3403 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; 3404 ~ContextualImplicitConverter()3405 virtual ~ContextualImplicitConverter() {} 3406 }; 3407 3408 class ICEConvertDiagnoser : public ContextualImplicitConverter { 3409 bool AllowScopedEnumerations; 3410 3411 public: ICEConvertDiagnoser(bool AllowScopedEnumerations,bool Suppress,bool SuppressConversion)3412 ICEConvertDiagnoser(bool AllowScopedEnumerations, 3413 bool Suppress, bool SuppressConversion) 3414 : ContextualImplicitConverter(Suppress, SuppressConversion), 3415 AllowScopedEnumerations(AllowScopedEnumerations) {} 3416 3417 /// Match an integral or (possibly scoped) enumeration type. 3418 bool match(QualType T) override; 3419 3420 SemaDiagnosticBuilder diagnoseNoMatch(Sema & S,SourceLocation Loc,QualType T)3421 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override { 3422 return diagnoseNotInt(S, Loc, T); 3423 } 3424 3425 /// Emits a diagnostic complaining that the expression does not have 3426 /// integral or enumeration type. 3427 virtual SemaDiagnosticBuilder 3428 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0; 3429 }; 3430 3431 /// Perform a contextual implicit conversion. 3432 ExprResult PerformContextualImplicitConversion( 3433 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter); 3434 3435 3436 enum ObjCSubscriptKind { 3437 OS_Array, 3438 OS_Dictionary, 3439 OS_Error 3440 }; 3441 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); 3442 3443 // Note that LK_String is intentionally after the other literals, as 3444 // this is used for diagnostics logic. 3445 enum ObjCLiteralKind { 3446 LK_Array, 3447 LK_Dictionary, 3448 LK_Numeric, 3449 LK_Boxed, 3450 LK_String, 3451 LK_Block, 3452 LK_None 3453 }; 3454 ObjCLiteralKind CheckLiteralKind(Expr *FromE); 3455 3456 ExprResult PerformObjectMemberConversion(Expr *From, 3457 NestedNameSpecifier *Qualifier, 3458 NamedDecl *FoundDecl, 3459 NamedDecl *Member); 3460 3461 // Members have to be NamespaceDecl* or TranslationUnitDecl*. 3462 // TODO: make this is a typesafe union. 3463 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet; 3464 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet; 3465 3466 using ADLCallKind = CallExpr::ADLCallKind; 3467 3468 void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, 3469 ArrayRef<Expr *> Args, 3470 OverloadCandidateSet &CandidateSet, 3471 bool SuppressUserConversions = false, 3472 bool PartialOverloading = false, 3473 bool AllowExplicit = true, 3474 bool AllowExplicitConversion = false, 3475 ADLCallKind IsADLCandidate = ADLCallKind::NotADL, 3476 ConversionSequenceList EarlyConversions = None, 3477 OverloadCandidateParamOrder PO = {}); 3478 void AddFunctionCandidates(const UnresolvedSetImpl &Functions, 3479 ArrayRef<Expr *> Args, 3480 OverloadCandidateSet &CandidateSet, 3481 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, 3482 bool SuppressUserConversions = false, 3483 bool PartialOverloading = false, 3484 bool FirstArgumentIsBase = false); 3485 void AddMethodCandidate(DeclAccessPair FoundDecl, 3486 QualType ObjectType, 3487 Expr::Classification ObjectClassification, 3488 ArrayRef<Expr *> Args, 3489 OverloadCandidateSet& CandidateSet, 3490 bool SuppressUserConversion = false, 3491 OverloadCandidateParamOrder PO = {}); 3492 void AddMethodCandidate(CXXMethodDecl *Method, 3493 DeclAccessPair FoundDecl, 3494 CXXRecordDecl *ActingContext, QualType ObjectType, 3495 Expr::Classification ObjectClassification, 3496 ArrayRef<Expr *> Args, 3497 OverloadCandidateSet& CandidateSet, 3498 bool SuppressUserConversions = false, 3499 bool PartialOverloading = false, 3500 ConversionSequenceList EarlyConversions = None, 3501 OverloadCandidateParamOrder PO = {}); 3502 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 3503 DeclAccessPair FoundDecl, 3504 CXXRecordDecl *ActingContext, 3505 TemplateArgumentListInfo *ExplicitTemplateArgs, 3506 QualType ObjectType, 3507 Expr::Classification ObjectClassification, 3508 ArrayRef<Expr *> Args, 3509 OverloadCandidateSet& CandidateSet, 3510 bool SuppressUserConversions = false, 3511 bool PartialOverloading = false, 3512 OverloadCandidateParamOrder PO = {}); 3513 void AddTemplateOverloadCandidate( 3514 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 3515 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 3516 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, 3517 bool PartialOverloading = false, bool AllowExplicit = true, 3518 ADLCallKind IsADLCandidate = ADLCallKind::NotADL, 3519 OverloadCandidateParamOrder PO = {}); 3520 bool CheckNonDependentConversions( 3521 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 3522 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 3523 ConversionSequenceList &Conversions, bool SuppressUserConversions, 3524 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(), 3525 Expr::Classification ObjectClassification = {}, 3526 OverloadCandidateParamOrder PO = {}); 3527 void AddConversionCandidate( 3528 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 3529 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 3530 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 3531 bool AllowExplicit, bool AllowResultConversion = true); 3532 void AddTemplateConversionCandidate( 3533 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 3534 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 3535 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 3536 bool AllowExplicit, bool AllowResultConversion = true); 3537 void AddSurrogateCandidate(CXXConversionDecl *Conversion, 3538 DeclAccessPair FoundDecl, 3539 CXXRecordDecl *ActingContext, 3540 const FunctionProtoType *Proto, 3541 Expr *Object, ArrayRef<Expr *> Args, 3542 OverloadCandidateSet& CandidateSet); 3543 void AddNonMemberOperatorCandidates( 3544 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, 3545 OverloadCandidateSet &CandidateSet, 3546 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); 3547 void AddMemberOperatorCandidates(OverloadedOperatorKind Op, 3548 SourceLocation OpLoc, ArrayRef<Expr *> Args, 3549 OverloadCandidateSet &CandidateSet, 3550 OverloadCandidateParamOrder PO = {}); 3551 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 3552 OverloadCandidateSet& CandidateSet, 3553 bool IsAssignmentOperator = false, 3554 unsigned NumContextualBoolArguments = 0); 3555 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 3556 SourceLocation OpLoc, ArrayRef<Expr *> Args, 3557 OverloadCandidateSet& CandidateSet); 3558 void AddArgumentDependentLookupCandidates(DeclarationName Name, 3559 SourceLocation Loc, 3560 ArrayRef<Expr *> Args, 3561 TemplateArgumentListInfo *ExplicitTemplateArgs, 3562 OverloadCandidateSet& CandidateSet, 3563 bool PartialOverloading = false); 3564 3565 // Emit as a 'note' the specific overload candidate 3566 void NoteOverloadCandidate( 3567 NamedDecl *Found, FunctionDecl *Fn, 3568 OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(), 3569 QualType DestType = QualType(), bool TakingAddress = false); 3570 3571 // Emit as a series of 'note's all template and non-templates identified by 3572 // the expression Expr 3573 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(), 3574 bool TakingAddress = false); 3575 3576 /// Check the enable_if expressions on the given function. Returns the first 3577 /// failing attribute, or NULL if they were all successful. 3578 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, 3579 ArrayRef<Expr *> Args, 3580 bool MissingImplicitThis = false); 3581 3582 /// Find the failed Boolean condition within a given Boolean 3583 /// constant expression, and describe it with a string. 3584 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond); 3585 3586 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any 3587 /// non-ArgDependent DiagnoseIfAttrs. 3588 /// 3589 /// Argument-dependent diagnose_if attributes should be checked each time a 3590 /// function is used as a direct callee of a function call. 3591 /// 3592 /// Returns true if any errors were emitted. 3593 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 3594 const Expr *ThisArg, 3595 ArrayRef<const Expr *> Args, 3596 SourceLocation Loc); 3597 3598 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any 3599 /// ArgDependent DiagnoseIfAttrs. 3600 /// 3601 /// Argument-independent diagnose_if attributes should be checked on every use 3602 /// of a function. 3603 /// 3604 /// Returns true if any errors were emitted. 3605 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 3606 SourceLocation Loc); 3607 3608 /// Returns whether the given function's address can be taken or not, 3609 /// optionally emitting a diagnostic if the address can't be taken. 3610 /// 3611 /// Returns false if taking the address of the function is illegal. 3612 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 3613 bool Complain = false, 3614 SourceLocation Loc = SourceLocation()); 3615 3616 // [PossiblyAFunctionType] --> [Return] 3617 // NonFunctionType --> NonFunctionType 3618 // R (A) --> R(A) 3619 // R (*)(A) --> R (A) 3620 // R (&)(A) --> R (A) 3621 // R (S::*)(A) --> R (A) 3622 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); 3623 3624 FunctionDecl * 3625 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 3626 QualType TargetType, 3627 bool Complain, 3628 DeclAccessPair &Found, 3629 bool *pHadMultipleCandidates = nullptr); 3630 3631 FunctionDecl * 3632 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult); 3633 3634 bool resolveAndFixAddressOfSingleOverloadCandidate( 3635 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false); 3636 3637 FunctionDecl * 3638 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 3639 bool Complain = false, 3640 DeclAccessPair *Found = nullptr); 3641 3642 bool ResolveAndFixSingleFunctionTemplateSpecialization( 3643 ExprResult &SrcExpr, 3644 bool DoFunctionPointerConverion = false, 3645 bool Complain = false, 3646 SourceRange OpRangeForComplaining = SourceRange(), 3647 QualType DestTypeForComplaining = QualType(), 3648 unsigned DiagIDForComplaining = 0); 3649 3650 3651 Expr *FixOverloadedFunctionReference(Expr *E, 3652 DeclAccessPair FoundDecl, 3653 FunctionDecl *Fn); 3654 ExprResult FixOverloadedFunctionReference(ExprResult, 3655 DeclAccessPair FoundDecl, 3656 FunctionDecl *Fn); 3657 3658 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 3659 ArrayRef<Expr *> Args, 3660 OverloadCandidateSet &CandidateSet, 3661 bool PartialOverloading = false); 3662 void AddOverloadedCallCandidates( 3663 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, 3664 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet); 3665 3666 // An enum used to represent the different possible results of building a 3667 // range-based for loop. 3668 enum ForRangeStatus { 3669 FRS_Success, 3670 FRS_NoViableFunction, 3671 FRS_DiagnosticIssued 3672 }; 3673 3674 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, 3675 SourceLocation RangeLoc, 3676 const DeclarationNameInfo &NameInfo, 3677 LookupResult &MemberLookup, 3678 OverloadCandidateSet *CandidateSet, 3679 Expr *Range, ExprResult *CallExpr); 3680 3681 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, 3682 UnresolvedLookupExpr *ULE, 3683 SourceLocation LParenLoc, 3684 MultiExprArg Args, 3685 SourceLocation RParenLoc, 3686 Expr *ExecConfig, 3687 bool AllowTypoCorrection=true, 3688 bool CalleesAddressIsTaken=false); 3689 3690 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, 3691 MultiExprArg Args, SourceLocation RParenLoc, 3692 OverloadCandidateSet *CandidateSet, 3693 ExprResult *Result); 3694 3695 ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, 3696 NestedNameSpecifierLoc NNSLoc, 3697 DeclarationNameInfo DNI, 3698 const UnresolvedSetImpl &Fns, 3699 bool PerformADL = true); 3700 3701 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, 3702 UnaryOperatorKind Opc, 3703 const UnresolvedSetImpl &Fns, 3704 Expr *input, bool RequiresADL = true); 3705 3706 void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 3707 OverloadedOperatorKind Op, 3708 const UnresolvedSetImpl &Fns, 3709 ArrayRef<Expr *> Args, bool RequiresADL = true); 3710 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, 3711 BinaryOperatorKind Opc, 3712 const UnresolvedSetImpl &Fns, 3713 Expr *LHS, Expr *RHS, 3714 bool RequiresADL = true, 3715 bool AllowRewrittenCandidates = true, 3716 FunctionDecl *DefaultedFn = nullptr); 3717 ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, 3718 const UnresolvedSetImpl &Fns, 3719 Expr *LHS, Expr *RHS, 3720 FunctionDecl *DefaultedFn); 3721 3722 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 3723 SourceLocation RLoc, 3724 Expr *Base,Expr *Idx); 3725 3726 ExprResult 3727 BuildCallToMemberFunction(Scope *S, Expr *MemExpr, 3728 SourceLocation LParenLoc, 3729 MultiExprArg Args, 3730 SourceLocation RParenLoc); 3731 ExprResult 3732 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, 3733 MultiExprArg Args, 3734 SourceLocation RParenLoc); 3735 3736 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, 3737 SourceLocation OpLoc, 3738 bool *NoArrowOperatorFound = nullptr); 3739 3740 /// CheckCallReturnType - Checks that a call expression's return type is 3741 /// complete. Returns true on failure. The location passed in is the location 3742 /// that best represents the call. 3743 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 3744 CallExpr *CE, FunctionDecl *FD); 3745 3746 /// Helpers for dealing with blocks and functions. 3747 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 3748 bool CheckParameterNames); 3749 void CheckCXXDefaultArguments(FunctionDecl *FD); 3750 void CheckExtraCXXDefaultArguments(Declarator &D); 3751 Scope *getNonFieldDeclScope(Scope *S); 3752 3753 /// \name Name lookup 3754 /// 3755 /// These routines provide name lookup that is used during semantic 3756 /// analysis to resolve the various kinds of names (identifiers, 3757 /// overloaded operator names, constructor names, etc.) into zero or 3758 /// more declarations within a particular scope. The major entry 3759 /// points are LookupName, which performs unqualified name lookup, 3760 /// and LookupQualifiedName, which performs qualified name lookup. 3761 /// 3762 /// All name lookup is performed based on some specific criteria, 3763 /// which specify what names will be visible to name lookup and how 3764 /// far name lookup should work. These criteria are important both 3765 /// for capturing language semantics (certain lookups will ignore 3766 /// certain names, for example) and for performance, since name 3767 /// lookup is often a bottleneck in the compilation of C++. Name 3768 /// lookup criteria is specified via the LookupCriteria enumeration. 3769 /// 3770 /// The results of name lookup can vary based on the kind of name 3771 /// lookup performed, the current language, and the translation 3772 /// unit. In C, for example, name lookup will either return nothing 3773 /// (no entity found) or a single declaration. In C++, name lookup 3774 /// can additionally refer to a set of overloaded functions or 3775 /// result in an ambiguity. All of the possible results of name 3776 /// lookup are captured by the LookupResult class, which provides 3777 /// the ability to distinguish among them. 3778 //@{ 3779 3780 /// Describes the kind of name lookup to perform. 3781 enum LookupNameKind { 3782 /// Ordinary name lookup, which finds ordinary names (functions, 3783 /// variables, typedefs, etc.) in C and most kinds of names 3784 /// (functions, variables, members, types, etc.) in C++. 3785 LookupOrdinaryName = 0, 3786 /// Tag name lookup, which finds the names of enums, classes, 3787 /// structs, and unions. 3788 LookupTagName, 3789 /// Label name lookup. 3790 LookupLabel, 3791 /// Member name lookup, which finds the names of 3792 /// class/struct/union members. 3793 LookupMemberName, 3794 /// Look up of an operator name (e.g., operator+) for use with 3795 /// operator overloading. This lookup is similar to ordinary name 3796 /// lookup, but will ignore any declarations that are class members. 3797 LookupOperatorName, 3798 /// Look up a name following ~ in a destructor name. This is an ordinary 3799 /// lookup, but prefers tags to typedefs. 3800 LookupDestructorName, 3801 /// Look up of a name that precedes the '::' scope resolution 3802 /// operator in C++. This lookup completely ignores operator, object, 3803 /// function, and enumerator names (C++ [basic.lookup.qual]p1). 3804 LookupNestedNameSpecifierName, 3805 /// Look up a namespace name within a C++ using directive or 3806 /// namespace alias definition, ignoring non-namespace names (C++ 3807 /// [basic.lookup.udir]p1). 3808 LookupNamespaceName, 3809 /// Look up all declarations in a scope with the given name, 3810 /// including resolved using declarations. This is appropriate 3811 /// for checking redeclarations for a using declaration. 3812 LookupUsingDeclName, 3813 /// Look up an ordinary name that is going to be redeclared as a 3814 /// name with linkage. This lookup ignores any declarations that 3815 /// are outside of the current scope unless they have linkage. See 3816 /// C99 6.2.2p4-5 and C++ [basic.link]p6. 3817 LookupRedeclarationWithLinkage, 3818 /// Look up a friend of a local class. This lookup does not look 3819 /// outside the innermost non-class scope. See C++11 [class.friend]p11. 3820 LookupLocalFriendName, 3821 /// Look up the name of an Objective-C protocol. 3822 LookupObjCProtocolName, 3823 /// Look up implicit 'self' parameter of an objective-c method. 3824 LookupObjCImplicitSelfParam, 3825 /// Look up the name of an OpenMP user-defined reduction operation. 3826 LookupOMPReductionName, 3827 /// Look up the name of an OpenMP user-defined mapper. 3828 LookupOMPMapperName, 3829 /// Look up any declaration with any name. 3830 LookupAnyName 3831 }; 3832 3833 /// Specifies whether (or how) name lookup is being performed for a 3834 /// redeclaration (vs. a reference). 3835 enum RedeclarationKind { 3836 /// The lookup is a reference to this name that is not for the 3837 /// purpose of redeclaring the name. 3838 NotForRedeclaration = 0, 3839 /// The lookup results will be used for redeclaration of a name, 3840 /// if an entity by that name already exists and is visible. 3841 ForVisibleRedeclaration, 3842 /// The lookup results will be used for redeclaration of a name 3843 /// with external linkage; non-visible lookup results with external linkage 3844 /// may also be found. 3845 ForExternalRedeclaration 3846 }; 3847 forRedeclarationInCurContext()3848 RedeclarationKind forRedeclarationInCurContext() { 3849 // A declaration with an owning module for linkage can never link against 3850 // anything that is not visible. We don't need to check linkage here; if 3851 // the context has internal linkage, redeclaration lookup won't find things 3852 // from other TUs, and we can't safely compute linkage yet in general. 3853 if (cast<Decl>(CurContext) 3854 ->getOwningModuleForLinkage(/*IgnoreLinkage*/true)) 3855 return ForVisibleRedeclaration; 3856 return ForExternalRedeclaration; 3857 } 3858 3859 /// The possible outcomes of name lookup for a literal operator. 3860 enum LiteralOperatorLookupResult { 3861 /// The lookup resulted in an error. 3862 LOLR_Error, 3863 /// The lookup found no match but no diagnostic was issued. 3864 LOLR_ErrorNoDiagnostic, 3865 /// The lookup found a single 'cooked' literal operator, which 3866 /// expects a normal literal to be built and passed to it. 3867 LOLR_Cooked, 3868 /// The lookup found a single 'raw' literal operator, which expects 3869 /// a string literal containing the spelling of the literal token. 3870 LOLR_Raw, 3871 /// The lookup found an overload set of literal operator templates, 3872 /// which expect the characters of the spelling of the literal token to be 3873 /// passed as a non-type template argument pack. 3874 LOLR_Template, 3875 /// The lookup found an overload set of literal operator templates, 3876 /// which expect the character type and characters of the spelling of the 3877 /// string literal token to be passed as template arguments. 3878 LOLR_StringTemplatePack, 3879 }; 3880 3881 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, 3882 CXXSpecialMember SM, 3883 bool ConstArg, 3884 bool VolatileArg, 3885 bool RValueThis, 3886 bool ConstThis, 3887 bool VolatileThis); 3888 3889 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator; 3890 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)> 3891 TypoRecoveryCallback; 3892 3893 private: 3894 bool CppLookupName(LookupResult &R, Scope *S); 3895 3896 struct TypoExprState { 3897 std::unique_ptr<TypoCorrectionConsumer> Consumer; 3898 TypoDiagnosticGenerator DiagHandler; 3899 TypoRecoveryCallback RecoveryHandler; 3900 TypoExprState(); 3901 TypoExprState(TypoExprState &&other) noexcept; 3902 TypoExprState &operator=(TypoExprState &&other) noexcept; 3903 }; 3904 3905 /// The set of unhandled TypoExprs and their associated state. 3906 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos; 3907 3908 /// Creates a new TypoExpr AST node. 3909 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, 3910 TypoDiagnosticGenerator TDG, 3911 TypoRecoveryCallback TRC, SourceLocation TypoLoc); 3912 3913 // The set of known/encountered (unique, canonicalized) NamespaceDecls. 3914 // 3915 // The boolean value will be true to indicate that the namespace was loaded 3916 // from an AST/PCH file, or false otherwise. 3917 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces; 3918 3919 /// Whether we have already loaded known namespaces from an extenal 3920 /// source. 3921 bool LoadedExternalKnownNamespaces; 3922 3923 /// Helper for CorrectTypo and CorrectTypoDelayed used to create and 3924 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction 3925 /// should be skipped entirely. 3926 std::unique_ptr<TypoCorrectionConsumer> 3927 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo, 3928 Sema::LookupNameKind LookupKind, Scope *S, 3929 CXXScopeSpec *SS, 3930 CorrectionCandidateCallback &CCC, 3931 DeclContext *MemberContext, bool EnteringContext, 3932 const ObjCObjectPointerType *OPT, 3933 bool ErrorRecovery); 3934 3935 public: 3936 const TypoExprState &getTypoExprState(TypoExpr *TE) const; 3937 3938 /// Clears the state of the given TypoExpr. 3939 void clearDelayedTypo(TypoExpr *TE); 3940 3941 /// Look up a name, looking for a single declaration. Return 3942 /// null if the results were absent, ambiguous, or overloaded. 3943 /// 3944 /// It is preferable to use the elaborated form and explicitly handle 3945 /// ambiguity and overloaded. 3946 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, 3947 SourceLocation Loc, 3948 LookupNameKind NameKind, 3949 RedeclarationKind Redecl 3950 = NotForRedeclaration); 3951 bool LookupBuiltin(LookupResult &R); 3952 void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID); 3953 bool LookupName(LookupResult &R, Scope *S, 3954 bool AllowBuiltinCreation = false); 3955 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 3956 bool InUnqualifiedLookup = false); 3957 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 3958 CXXScopeSpec &SS); 3959 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 3960 bool AllowBuiltinCreation = false, 3961 bool EnteringContext = false); 3962 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, 3963 RedeclarationKind Redecl 3964 = NotForRedeclaration); 3965 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class); 3966 3967 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, 3968 UnresolvedSetImpl &Functions); 3969 3970 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, 3971 SourceLocation GnuLabelLoc = SourceLocation()); 3972 3973 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); 3974 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); 3975 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, 3976 unsigned Quals); 3977 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, 3978 bool RValueThis, unsigned ThisQuals); 3979 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, 3980 unsigned Quals); 3981 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, 3982 bool RValueThis, unsigned ThisQuals); 3983 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); 3984 3985 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id); 3986 LiteralOperatorLookupResult 3987 LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys, 3988 bool AllowRaw, bool AllowTemplate, 3989 bool AllowStringTemplate, bool DiagnoseMissing, 3990 StringLiteral *StringLit = nullptr); 3991 bool isKnownName(StringRef name); 3992 3993 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs. 3994 enum class FunctionEmissionStatus { 3995 Emitted, 3996 CUDADiscarded, // Discarded due to CUDA/HIP hostness 3997 OMPDiscarded, // Discarded due to OpenMP hostness 3998 TemplateDiscarded, // Discarded due to uninstantiated templates 3999 Unknown, 4000 }; 4001 FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl, 4002 bool Final = false); 4003 4004 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check. 4005 bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee); 4006 4007 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, 4008 ArrayRef<Expr *> Args, ADLResult &Functions); 4009 4010 void LookupVisibleDecls(Scope *S, LookupNameKind Kind, 4011 VisibleDeclConsumer &Consumer, 4012 bool IncludeGlobalScope = true, 4013 bool LoadExternal = true); 4014 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, 4015 VisibleDeclConsumer &Consumer, 4016 bool IncludeGlobalScope = true, 4017 bool IncludeDependentBases = false, 4018 bool LoadExternal = true); 4019 4020 enum CorrectTypoKind { 4021 CTK_NonError, // CorrectTypo used in a non error recovery situation. 4022 CTK_ErrorRecovery // CorrectTypo used in normal error recovery. 4023 }; 4024 4025 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, 4026 Sema::LookupNameKind LookupKind, 4027 Scope *S, CXXScopeSpec *SS, 4028 CorrectionCandidateCallback &CCC, 4029 CorrectTypoKind Mode, 4030 DeclContext *MemberContext = nullptr, 4031 bool EnteringContext = false, 4032 const ObjCObjectPointerType *OPT = nullptr, 4033 bool RecordFailure = true); 4034 4035 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo, 4036 Sema::LookupNameKind LookupKind, Scope *S, 4037 CXXScopeSpec *SS, 4038 CorrectionCandidateCallback &CCC, 4039 TypoDiagnosticGenerator TDG, 4040 TypoRecoveryCallback TRC, CorrectTypoKind Mode, 4041 DeclContext *MemberContext = nullptr, 4042 bool EnteringContext = false, 4043 const ObjCObjectPointerType *OPT = nullptr); 4044 4045 /// Process any TypoExprs in the given Expr and its children, 4046 /// generating diagnostics as appropriate and returning a new Expr if there 4047 /// were typos that were all successfully corrected and ExprError if one or 4048 /// more typos could not be corrected. 4049 /// 4050 /// \param E The Expr to check for TypoExprs. 4051 /// 4052 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its 4053 /// initializer. 4054 /// 4055 /// \param RecoverUncorrectedTypos If true, when typo correction fails, it 4056 /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs. 4057 /// 4058 /// \param Filter A function applied to a newly rebuilt Expr to determine if 4059 /// it is an acceptable/usable result from a single combination of typo 4060 /// corrections. As long as the filter returns ExprError, different 4061 /// combinations of corrections will be tried until all are exhausted. 4062 ExprResult CorrectDelayedTyposInExpr( 4063 Expr *E, VarDecl *InitDecl = nullptr, 4064 bool RecoverUncorrectedTypos = false, 4065 llvm::function_ref<ExprResult(Expr *)> Filter = 4066 [](Expr *E) -> ExprResult { return E; }); 4067 4068 ExprResult CorrectDelayedTyposInExpr( 4069 ExprResult ER, VarDecl *InitDecl = nullptr, 4070 bool RecoverUncorrectedTypos = false, 4071 llvm::function_ref<ExprResult(Expr *)> Filter = 4072 [](Expr *E) -> ExprResult { return E; }) { 4073 return ER.isInvalid() 4074 ? ER 4075 : CorrectDelayedTyposInExpr(ER.get(), InitDecl, 4076 RecoverUncorrectedTypos, Filter); 4077 } 4078 4079 void diagnoseTypo(const TypoCorrection &Correction, 4080 const PartialDiagnostic &TypoDiag, 4081 bool ErrorRecovery = true); 4082 4083 void diagnoseTypo(const TypoCorrection &Correction, 4084 const PartialDiagnostic &TypoDiag, 4085 const PartialDiagnostic &PrevNote, 4086 bool ErrorRecovery = true); 4087 4088 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F); 4089 4090 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, 4091 ArrayRef<Expr *> Args, 4092 AssociatedNamespaceSet &AssociatedNamespaces, 4093 AssociatedClassSet &AssociatedClasses); 4094 4095 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 4096 bool ConsiderLinkage, bool AllowInlineNamespace); 4097 4098 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old); 4099 4100 void DiagnoseAmbiguousLookup(LookupResult &Result); 4101 //@} 4102 4103 /// Attempts to produce a RecoveryExpr after some AST node cannot be created. 4104 ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 4105 ArrayRef<Expr *> SubExprs, 4106 QualType T = QualType()); 4107 4108 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, 4109 SourceLocation IdLoc, 4110 bool TypoCorrection = false); 4111 FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, 4112 SourceLocation Loc); 4113 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 4114 Scope *S, bool ForRedeclaration, 4115 SourceLocation Loc); 4116 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, 4117 Scope *S); 4118 void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 4119 FunctionDecl *FD); 4120 void AddKnownFunctionAttributes(FunctionDecl *FD); 4121 4122 // More parsing and symbol table subroutines. 4123 4124 void ProcessPragmaWeak(Scope *S, Decl *D); 4125 // Decl attributes - this routine is the top level dispatcher. 4126 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); 4127 // Helper for delayed processing of attributes. 4128 void ProcessDeclAttributeDelayed(Decl *D, 4129 const ParsedAttributesView &AttrList); 4130 void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL, 4131 bool IncludeCXX11Attributes = true); 4132 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, 4133 const ParsedAttributesView &AttrList); 4134 4135 void checkUnusedDeclAttributes(Declarator &D); 4136 4137 /// Determine if type T is a valid subject for a nonnull and similar 4138 /// attributes. By default, we look through references (the behavior used by 4139 /// nonnull), but if the second parameter is true, then we treat a reference 4140 /// type as valid. 4141 bool isValidPointerAttrType(QualType T, bool RefOkay = false); 4142 4143 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value); 4144 bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, 4145 const FunctionDecl *FD = nullptr); 4146 bool CheckAttrTarget(const ParsedAttr &CurrAttr); 4147 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr); 4148 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum, 4149 StringRef &Str, 4150 SourceLocation *ArgLocation = nullptr); 4151 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str); 4152 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str); 4153 bool checkMSInheritanceAttrOnDefinition( 4154 CXXRecordDecl *RD, SourceRange Range, bool BestCase, 4155 MSInheritanceModel SemanticSpelling); 4156 4157 void CheckAlignasUnderalignment(Decl *D); 4158 4159 /// Adjust the calling convention of a method to be the ABI default if it 4160 /// wasn't specified explicitly. This handles method types formed from 4161 /// function type typedefs and typename template arguments. 4162 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, 4163 SourceLocation Loc); 4164 4165 // Check if there is an explicit attribute, but only look through parens. 4166 // The intent is to look for an attribute on the current declarator, but not 4167 // one that came from a typedef. 4168 bool hasExplicitCallingConv(QualType T); 4169 4170 /// Get the outermost AttributedType node that sets a calling convention. 4171 /// Valid types should not have multiple attributes with different CCs. 4172 const AttributedType *getCallingConvAttributedType(QualType T) const; 4173 4174 /// Stmt attributes - this routine is the top level dispatcher. 4175 StmtResult ProcessStmtAttributes(Stmt *Stmt, 4176 const ParsedAttributesView &Attrs, 4177 SourceRange Range); 4178 4179 void WarnConflictingTypedMethods(ObjCMethodDecl *Method, 4180 ObjCMethodDecl *MethodDecl, 4181 bool IsProtocolMethodDecl); 4182 4183 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, 4184 ObjCMethodDecl *Overridden, 4185 bool IsProtocolMethodDecl); 4186 4187 /// WarnExactTypedMethods - This routine issues a warning if method 4188 /// implementation declaration matches exactly that of its declaration. 4189 void WarnExactTypedMethods(ObjCMethodDecl *Method, 4190 ObjCMethodDecl *MethodDecl, 4191 bool IsProtocolMethodDecl); 4192 4193 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet; 4194 4195 /// CheckImplementationIvars - This routine checks if the instance variables 4196 /// listed in the implelementation match those listed in the interface. 4197 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, 4198 ObjCIvarDecl **Fields, unsigned nIvars, 4199 SourceLocation Loc); 4200 4201 /// ImplMethodsVsClassMethods - This is main routine to warn if any method 4202 /// remains unimplemented in the class or category \@implementation. 4203 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, 4204 ObjCContainerDecl* IDecl, 4205 bool IncompleteImpl = false); 4206 4207 /// DiagnoseUnimplementedProperties - This routine warns on those properties 4208 /// which must be implemented by this implementation. 4209 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, 4210 ObjCContainerDecl *CDecl, 4211 bool SynthesizeProperties); 4212 4213 /// Diagnose any null-resettable synthesized setters. 4214 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl); 4215 4216 /// DefaultSynthesizeProperties - This routine default synthesizes all 4217 /// properties which must be synthesized in the class's \@implementation. 4218 void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl, 4219 ObjCInterfaceDecl *IDecl, 4220 SourceLocation AtEnd); 4221 void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd); 4222 4223 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is 4224 /// an ivar synthesized for 'Method' and 'Method' is a property accessor 4225 /// declared in class 'IFace'. 4226 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, 4227 ObjCMethodDecl *Method, ObjCIvarDecl *IV); 4228 4229 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which 4230 /// backs the property is not used in the property's accessor. 4231 void DiagnoseUnusedBackingIvarInAccessor(Scope *S, 4232 const ObjCImplementationDecl *ImplD); 4233 4234 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and 4235 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL. 4236 /// It also returns ivar's property on success. 4237 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, 4238 const ObjCPropertyDecl *&PDecl) const; 4239 4240 /// Called by ActOnProperty to handle \@property declarations in 4241 /// class extensions. 4242 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S, 4243 SourceLocation AtLoc, 4244 SourceLocation LParenLoc, 4245 FieldDeclarator &FD, 4246 Selector GetterSel, 4247 SourceLocation GetterNameLoc, 4248 Selector SetterSel, 4249 SourceLocation SetterNameLoc, 4250 const bool isReadWrite, 4251 unsigned &Attributes, 4252 const unsigned AttributesAsWritten, 4253 QualType T, 4254 TypeSourceInfo *TSI, 4255 tok::ObjCKeywordKind MethodImplKind); 4256 4257 /// Called by ActOnProperty and HandlePropertyInClassExtension to 4258 /// handle creating the ObjcPropertyDecl for a category or \@interface. 4259 ObjCPropertyDecl *CreatePropertyDecl(Scope *S, 4260 ObjCContainerDecl *CDecl, 4261 SourceLocation AtLoc, 4262 SourceLocation LParenLoc, 4263 FieldDeclarator &FD, 4264 Selector GetterSel, 4265 SourceLocation GetterNameLoc, 4266 Selector SetterSel, 4267 SourceLocation SetterNameLoc, 4268 const bool isReadWrite, 4269 const unsigned Attributes, 4270 const unsigned AttributesAsWritten, 4271 QualType T, 4272 TypeSourceInfo *TSI, 4273 tok::ObjCKeywordKind MethodImplKind, 4274 DeclContext *lexicalDC = nullptr); 4275 4276 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via 4277 /// warning) when atomic property has one but not the other user-declared 4278 /// setter or getter. 4279 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, 4280 ObjCInterfaceDecl* IDecl); 4281 4282 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); 4283 4284 void DiagnoseMissingDesignatedInitOverrides( 4285 const ObjCImplementationDecl *ImplD, 4286 const ObjCInterfaceDecl *IFD); 4287 4288 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); 4289 4290 enum MethodMatchStrategy { 4291 MMS_loose, 4292 MMS_strict 4293 }; 4294 4295 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns 4296 /// true, or false, accordingly. 4297 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, 4298 const ObjCMethodDecl *PrevMethod, 4299 MethodMatchStrategy strategy = MMS_strict); 4300 4301 /// MatchAllMethodDeclarations - Check methods declaraed in interface or 4302 /// or protocol against those declared in their implementations. 4303 void MatchAllMethodDeclarations(const SelectorSet &InsMap, 4304 const SelectorSet &ClsMap, 4305 SelectorSet &InsMapSeen, 4306 SelectorSet &ClsMapSeen, 4307 ObjCImplDecl* IMPDecl, 4308 ObjCContainerDecl* IDecl, 4309 bool &IncompleteImpl, 4310 bool ImmediateClass, 4311 bool WarnCategoryMethodImpl=false); 4312 4313 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in 4314 /// category matches with those implemented in its primary class and 4315 /// warns each time an exact match is found. 4316 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); 4317 4318 /// Add the given method to the list of globally-known methods. 4319 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); 4320 4321 /// Returns default addr space for method qualifiers. 4322 LangAS getDefaultCXXMethodAddrSpace() const; 4323 4324 private: 4325 /// AddMethodToGlobalPool - Add an instance or factory method to the global 4326 /// pool. See descriptoin of AddInstanceMethodToGlobalPool. 4327 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); 4328 4329 /// LookupMethodInGlobalPool - Returns the instance or factory method and 4330 /// optionally warns if there are multiple signatures. 4331 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, 4332 bool receiverIdOrClass, 4333 bool instance); 4334 4335 public: 4336 /// - Returns instance or factory methods in global method pool for 4337 /// given selector. It checks the desired kind first, if none is found, and 4338 /// parameter checkTheOther is set, it then checks the other kind. If no such 4339 /// method or only one method is found, function returns false; otherwise, it 4340 /// returns true. 4341 bool 4342 CollectMultipleMethodsInGlobalPool(Selector Sel, 4343 SmallVectorImpl<ObjCMethodDecl*>& Methods, 4344 bool InstanceFirst, bool CheckTheOther, 4345 const ObjCObjectType *TypeBound = nullptr); 4346 4347 bool 4348 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, 4349 SourceRange R, bool receiverIdOrClass, 4350 SmallVectorImpl<ObjCMethodDecl*>& Methods); 4351 4352 void 4353 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, 4354 Selector Sel, SourceRange R, 4355 bool receiverIdOrClass); 4356 4357 private: 4358 /// - Returns a selector which best matches given argument list or 4359 /// nullptr if none could be found 4360 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args, 4361 bool IsInstance, 4362 SmallVectorImpl<ObjCMethodDecl*>& Methods); 4363 4364 4365 /// Record the typo correction failure and return an empty correction. 4366 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc, 4367 bool RecordFailure = true) { 4368 if (RecordFailure) 4369 TypoCorrectionFailures[Typo].insert(TypoLoc); 4370 return TypoCorrection(); 4371 } 4372 4373 public: 4374 /// AddInstanceMethodToGlobalPool - All instance methods in a translation 4375 /// unit are added to a global pool. This allows us to efficiently associate 4376 /// a selector with a method declaraation for purposes of typechecking 4377 /// messages sent to "id" (where the class of the object is unknown). 4378 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 4379 AddMethodToGlobalPool(Method, impl, /*instance*/true); 4380 } 4381 4382 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. 4383 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 4384 AddMethodToGlobalPool(Method, impl, /*instance*/false); 4385 } 4386 4387 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global 4388 /// pool. 4389 void AddAnyMethodToGlobalPool(Decl *D); 4390 4391 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if 4392 /// there are multiple signatures. 4393 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, 4394 bool receiverIdOrClass=false) { 4395 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 4396 /*instance*/true); 4397 } 4398 4399 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if 4400 /// there are multiple signatures. 4401 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, 4402 bool receiverIdOrClass=false) { 4403 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 4404 /*instance*/false); 4405 } 4406 4407 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel, 4408 QualType ObjectType=QualType()); 4409 /// LookupImplementedMethodInGlobalPool - Returns the method which has an 4410 /// implementation. 4411 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); 4412 4413 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require 4414 /// initialization. 4415 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, 4416 SmallVectorImpl<ObjCIvarDecl*> &Ivars); 4417 4418 //===--------------------------------------------------------------------===// 4419 // Statement Parsing Callbacks: SemaStmt.cpp. 4420 public: 4421 class FullExprArg { 4422 public: FullExprArg()4423 FullExprArg() : E(nullptr) { } FullExprArg(Sema & actions)4424 FullExprArg(Sema &actions) : E(nullptr) { } 4425 release()4426 ExprResult release() { 4427 return E; 4428 } 4429 get()4430 Expr *get() const { return E; } 4431 4432 Expr *operator->() { 4433 return E; 4434 } 4435 4436 private: 4437 // FIXME: No need to make the entire Sema class a friend when it's just 4438 // Sema::MakeFullExpr that needs access to the constructor below. 4439 friend class Sema; 4440 FullExprArg(Expr * expr)4441 explicit FullExprArg(Expr *expr) : E(expr) {} 4442 4443 Expr *E; 4444 }; 4445 MakeFullExpr(Expr * Arg)4446 FullExprArg MakeFullExpr(Expr *Arg) { 4447 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation()); 4448 } MakeFullExpr(Expr * Arg,SourceLocation CC)4449 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { 4450 return FullExprArg( 4451 ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get()); 4452 } MakeFullDiscardedValueExpr(Expr * Arg)4453 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { 4454 ExprResult FE = 4455 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), 4456 /*DiscardedValue*/ true); 4457 return FullExprArg(FE.get()); 4458 } 4459 4460 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true); 4461 StmtResult ActOnExprStmtError(); 4462 4463 StmtResult ActOnNullStmt(SourceLocation SemiLoc, 4464 bool HasLeadingEmptyMacro = false); 4465 4466 void ActOnStartOfCompoundStmt(bool IsStmtExpr); 4467 void ActOnAfterCompoundStatementLeadingPragmas(); 4468 void ActOnFinishOfCompoundStmt(); 4469 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, 4470 ArrayRef<Stmt *> Elts, bool isStmtExpr); 4471 4472 /// A RAII object to enter scope of a compound statement. 4473 class CompoundScopeRAII { 4474 public: S(S)4475 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) { 4476 S.ActOnStartOfCompoundStmt(IsStmtExpr); 4477 } 4478 ~CompoundScopeRAII()4479 ~CompoundScopeRAII() { 4480 S.ActOnFinishOfCompoundStmt(); 4481 } 4482 4483 private: 4484 Sema &S; 4485 }; 4486 4487 /// An RAII helper that pops function a function scope on exit. 4488 struct FunctionScopeRAII { 4489 Sema &S; 4490 bool Active; FunctionScopeRAIIFunctionScopeRAII4491 FunctionScopeRAII(Sema &S) : S(S), Active(true) {} ~FunctionScopeRAIIFunctionScopeRAII4492 ~FunctionScopeRAII() { 4493 if (Active) 4494 S.PopFunctionScopeInfo(); 4495 } disableFunctionScopeRAII4496 void disable() { Active = false; } 4497 }; 4498 4499 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, 4500 SourceLocation StartLoc, 4501 SourceLocation EndLoc); 4502 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); 4503 StmtResult ActOnForEachLValueExpr(Expr *E); 4504 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val); 4505 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS, 4506 SourceLocation DotDotDotLoc, ExprResult RHS, 4507 SourceLocation ColonLoc); 4508 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); 4509 4510 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, 4511 SourceLocation ColonLoc, 4512 Stmt *SubStmt, Scope *CurScope); 4513 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, 4514 SourceLocation ColonLoc, Stmt *SubStmt); 4515 4516 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc, 4517 ArrayRef<const Attr*> Attrs, 4518 Stmt *SubStmt); 4519 4520 class ConditionResult; 4521 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, 4522 SourceLocation LParenLoc, Stmt *InitStmt, 4523 ConditionResult Cond, SourceLocation RParenLoc, 4524 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); 4525 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr, 4526 SourceLocation LParenLoc, Stmt *InitStmt, 4527 ConditionResult Cond, SourceLocation RParenLoc, 4528 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); 4529 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, 4530 SourceLocation LParenLoc, Stmt *InitStmt, 4531 ConditionResult Cond, 4532 SourceLocation RParenLoc); 4533 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, 4534 Stmt *Switch, Stmt *Body); 4535 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc, 4536 ConditionResult Cond, SourceLocation RParenLoc, 4537 Stmt *Body); 4538 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 4539 SourceLocation WhileLoc, SourceLocation CondLParen, 4540 Expr *Cond, SourceLocation CondRParen); 4541 4542 StmtResult ActOnForStmt(SourceLocation ForLoc, 4543 SourceLocation LParenLoc, 4544 Stmt *First, 4545 ConditionResult Second, 4546 FullExprArg Third, 4547 SourceLocation RParenLoc, 4548 Stmt *Body); 4549 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, 4550 Expr *collection); 4551 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, 4552 Stmt *First, Expr *collection, 4553 SourceLocation RParenLoc); 4554 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body); 4555 4556 enum BuildForRangeKind { 4557 /// Initial building of a for-range statement. 4558 BFRK_Build, 4559 /// Instantiation or recovery rebuild of a for-range statement. Don't 4560 /// attempt any typo-correction. 4561 BFRK_Rebuild, 4562 /// Determining whether a for-range statement could be built. Avoid any 4563 /// unnecessary or irreversible actions. 4564 BFRK_Check 4565 }; 4566 4567 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, 4568 SourceLocation CoawaitLoc, 4569 Stmt *InitStmt, 4570 Stmt *LoopVar, 4571 SourceLocation ColonLoc, Expr *Collection, 4572 SourceLocation RParenLoc, 4573 BuildForRangeKind Kind); 4574 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, 4575 SourceLocation CoawaitLoc, 4576 Stmt *InitStmt, 4577 SourceLocation ColonLoc, 4578 Stmt *RangeDecl, Stmt *Begin, Stmt *End, 4579 Expr *Cond, Expr *Inc, 4580 Stmt *LoopVarDecl, 4581 SourceLocation RParenLoc, 4582 BuildForRangeKind Kind); 4583 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); 4584 4585 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, 4586 SourceLocation LabelLoc, 4587 LabelDecl *TheDecl); 4588 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, 4589 SourceLocation StarLoc, 4590 Expr *DestExp); 4591 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); 4592 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); 4593 4594 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, 4595 CapturedRegionKind Kind, unsigned NumParams); 4596 typedef std::pair<StringRef, QualType> CapturedParamNameType; 4597 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, 4598 CapturedRegionKind Kind, 4599 ArrayRef<CapturedParamNameType> Params, 4600 unsigned OpenMPCaptureLevel = 0); 4601 StmtResult ActOnCapturedRegionEnd(Stmt *S); 4602 void ActOnCapturedRegionError(); 4603 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, 4604 SourceLocation Loc, 4605 unsigned NumParams); 4606 4607 enum CopyElisionSemanticsKind { 4608 CES_Strict = 0, 4609 CES_AllowParameters = 1, 4610 CES_AllowDifferentTypes = 2, 4611 CES_AllowExceptionVariables = 4, 4612 CES_FormerDefault = (CES_AllowParameters), 4613 CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes), 4614 CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes | 4615 CES_AllowExceptionVariables), 4616 }; 4617 4618 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E, 4619 CopyElisionSemanticsKind CESK); 4620 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD, 4621 CopyElisionSemanticsKind CESK); 4622 4623 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, 4624 Scope *CurScope); 4625 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); 4626 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); 4627 4628 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, 4629 bool IsVolatile, unsigned NumOutputs, 4630 unsigned NumInputs, IdentifierInfo **Names, 4631 MultiExprArg Constraints, MultiExprArg Exprs, 4632 Expr *AsmString, MultiExprArg Clobbers, 4633 unsigned NumLabels, 4634 SourceLocation RParenLoc); 4635 4636 void FillInlineAsmIdentifierInfo(Expr *Res, 4637 llvm::InlineAsmIdentifierInfo &Info); 4638 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, 4639 SourceLocation TemplateKWLoc, 4640 UnqualifiedId &Id, 4641 bool IsUnevaluatedContext); 4642 bool LookupInlineAsmField(StringRef Base, StringRef Member, 4643 unsigned &Offset, SourceLocation AsmLoc); 4644 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, 4645 SourceLocation AsmLoc); 4646 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, 4647 ArrayRef<Token> AsmToks, 4648 StringRef AsmString, 4649 unsigned NumOutputs, unsigned NumInputs, 4650 ArrayRef<StringRef> Constraints, 4651 ArrayRef<StringRef> Clobbers, 4652 ArrayRef<Expr*> Exprs, 4653 SourceLocation EndLoc); 4654 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName, 4655 SourceLocation Location, 4656 bool AlwaysCreate); 4657 4658 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, 4659 SourceLocation StartLoc, 4660 SourceLocation IdLoc, IdentifierInfo *Id, 4661 bool Invalid = false); 4662 4663 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); 4664 4665 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, 4666 Decl *Parm, Stmt *Body); 4667 4668 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); 4669 4670 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 4671 MultiStmtArg Catch, Stmt *Finally); 4672 4673 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); 4674 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 4675 Scope *CurScope); 4676 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, 4677 Expr *operand); 4678 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, 4679 Expr *SynchExpr, 4680 Stmt *SynchBody); 4681 4682 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); 4683 4684 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, 4685 SourceLocation StartLoc, 4686 SourceLocation IdLoc, 4687 IdentifierInfo *Id); 4688 4689 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); 4690 4691 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, 4692 Decl *ExDecl, Stmt *HandlerBlock); 4693 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 4694 ArrayRef<Stmt *> Handlers); 4695 4696 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? 4697 SourceLocation TryLoc, Stmt *TryBlock, 4698 Stmt *Handler); 4699 StmtResult ActOnSEHExceptBlock(SourceLocation Loc, 4700 Expr *FilterExpr, 4701 Stmt *Block); 4702 void ActOnStartSEHFinallyBlock(); 4703 void ActOnAbortSEHFinallyBlock(); 4704 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block); 4705 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope); 4706 4707 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); 4708 4709 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; 4710 4711 /// If it's a file scoped decl that must warn if not used, keep track 4712 /// of it. 4713 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); 4714 4715 /// DiagnoseUnusedExprResult - If the statement passed in is an expression 4716 /// whose result is unused, warn. 4717 void DiagnoseUnusedExprResult(const Stmt *S); 4718 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D); 4719 void DiagnoseUnusedDecl(const NamedDecl *ND); 4720 4721 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null 4722 /// statement as a \p Body, and it is located on the same line. 4723 /// 4724 /// This helps prevent bugs due to typos, such as: 4725 /// if (condition); 4726 /// do_stuff(); 4727 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 4728 const Stmt *Body, 4729 unsigned DiagID); 4730 4731 /// Warn if a for/while loop statement \p S, which is followed by 4732 /// \p PossibleBody, has a suspicious null statement as a body. 4733 void DiagnoseEmptyLoopBody(const Stmt *S, 4734 const Stmt *PossibleBody); 4735 4736 /// Warn if a value is moved to itself. 4737 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 4738 SourceLocation OpLoc); 4739 4740 /// Warn if we're implicitly casting from a _Nullable pointer type to a 4741 /// _Nonnull one. 4742 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, 4743 SourceLocation Loc); 4744 4745 /// Warn when implicitly casting 0 to nullptr. 4746 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E); 4747 PushParsingDeclaration(sema::DelayedDiagnosticPool & pool)4748 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { 4749 return DelayedDiagnostics.push(pool); 4750 } 4751 void PopParsingDeclaration(ParsingDeclState state, Decl *decl); 4752 4753 typedef ProcessingContextState ParsingClassState; PushParsingClass()4754 ParsingClassState PushParsingClass() { 4755 ParsingClassDepth++; 4756 return DelayedDiagnostics.pushUndelayed(); 4757 } PopParsingClass(ParsingClassState state)4758 void PopParsingClass(ParsingClassState state) { 4759 ParsingClassDepth--; 4760 DelayedDiagnostics.popUndelayed(state); 4761 } 4762 4763 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); 4764 4765 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 4766 const ObjCInterfaceDecl *UnknownObjCClass, 4767 bool ObjCPropertyAccess, 4768 bool AvoidPartialAvailabilityChecks = false, 4769 ObjCInterfaceDecl *ClassReceiver = nullptr); 4770 4771 bool makeUnavailableInSystemHeader(SourceLocation loc, 4772 UnavailableAttr::ImplicitReason reason); 4773 4774 /// Issue any -Wunguarded-availability warnings in \c FD 4775 void DiagnoseUnguardedAvailabilityViolations(Decl *FD); 4776 4777 void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 4778 4779 //===--------------------------------------------------------------------===// 4780 // Expression Parsing Callbacks: SemaExpr.cpp. 4781 4782 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid); 4783 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 4784 const ObjCInterfaceDecl *UnknownObjCClass = nullptr, 4785 bool ObjCPropertyAccess = false, 4786 bool AvoidPartialAvailabilityChecks = false, 4787 ObjCInterfaceDecl *ClassReciever = nullptr); 4788 void NoteDeletedFunction(FunctionDecl *FD); 4789 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD); 4790 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, 4791 ObjCMethodDecl *Getter, 4792 SourceLocation Loc); 4793 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 4794 ArrayRef<Expr *> Args); 4795 4796 void PushExpressionEvaluationContext( 4797 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, 4798 ExpressionEvaluationContextRecord::ExpressionKind Type = 4799 ExpressionEvaluationContextRecord::EK_Other); 4800 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; 4801 void PushExpressionEvaluationContext( 4802 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 4803 ExpressionEvaluationContextRecord::ExpressionKind Type = 4804 ExpressionEvaluationContextRecord::EK_Other); 4805 void PopExpressionEvaluationContext(); 4806 4807 void DiscardCleanupsInEvaluationContext(); 4808 4809 ExprResult TransformToPotentiallyEvaluated(Expr *E); 4810 ExprResult HandleExprEvaluationContextForTypeof(Expr *E); 4811 4812 ExprResult CheckUnevaluatedOperand(Expr *E); 4813 void CheckUnusedVolatileAssignment(Expr *E); 4814 4815 ExprResult ActOnConstantExpression(ExprResult Res); 4816 4817 // Functions for marking a declaration referenced. These functions also 4818 // contain the relevant logic for marking if a reference to a function or 4819 // variable is an odr-use (in the C++11 sense). There are separate variants 4820 // for expressions referring to a decl; these exist because odr-use marking 4821 // needs to be delayed for some constant variables when we build one of the 4822 // named expressions. 4823 // 4824 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and 4825 // should usually be true. This only needs to be set to false if the lack of 4826 // odr-use cannot be determined from the current context (for instance, 4827 // because the name denotes a virtual function and was written without an 4828 // explicit nested-name-specifier). 4829 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse); 4830 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 4831 bool MightBeOdrUse = true); 4832 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); 4833 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr); 4834 void MarkMemberReferenced(MemberExpr *E); 4835 void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E); 4836 void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc, 4837 unsigned CapturingScopeIndex); 4838 4839 ExprResult CheckLValueToRValueConversionOperand(Expr *E); 4840 void CleanupVarDeclMarking(); 4841 4842 enum TryCaptureKind { 4843 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef 4844 }; 4845 4846 /// Try to capture the given variable. 4847 /// 4848 /// \param Var The variable to capture. 4849 /// 4850 /// \param Loc The location at which the capture occurs. 4851 /// 4852 /// \param Kind The kind of capture, which may be implicit (for either a 4853 /// block or a lambda), or explicit by-value or by-reference (for a lambda). 4854 /// 4855 /// \param EllipsisLoc The location of the ellipsis, if one is provided in 4856 /// an explicit lambda capture. 4857 /// 4858 /// \param BuildAndDiagnose Whether we are actually supposed to add the 4859 /// captures or diagnose errors. If false, this routine merely check whether 4860 /// the capture can occur without performing the capture itself or complaining 4861 /// if the variable cannot be captured. 4862 /// 4863 /// \param CaptureType Will be set to the type of the field used to capture 4864 /// this variable in the innermost block or lambda. Only valid when the 4865 /// variable can be captured. 4866 /// 4867 /// \param DeclRefType Will be set to the type of a reference to the capture 4868 /// from within the current scope. Only valid when the variable can be 4869 /// captured. 4870 /// 4871 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index 4872 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. 4873 /// This is useful when enclosing lambdas must speculatively capture 4874 /// variables that may or may not be used in certain specializations of 4875 /// a nested generic lambda. 4876 /// 4877 /// \returns true if an error occurred (i.e., the variable cannot be 4878 /// captured) and false if the capture succeeded. 4879 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, 4880 SourceLocation EllipsisLoc, bool BuildAndDiagnose, 4881 QualType &CaptureType, 4882 QualType &DeclRefType, 4883 const unsigned *const FunctionScopeIndexToStopAt); 4884 4885 /// Try to capture the given variable. 4886 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 4887 TryCaptureKind Kind = TryCapture_Implicit, 4888 SourceLocation EllipsisLoc = SourceLocation()); 4889 4890 /// Checks if the variable must be captured. 4891 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc); 4892 4893 /// Given a variable, determine the type that a reference to that 4894 /// variable will have in the given scope. 4895 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); 4896 4897 /// Mark all of the declarations referenced within a particular AST node as 4898 /// referenced. Used when template instantiation instantiates a non-dependent 4899 /// type -- entities referenced by the type are now referenced. 4900 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); 4901 void MarkDeclarationsReferencedInExpr(Expr *E, 4902 bool SkipLocalVariables = false); 4903 4904 /// Try to recover by turning the given expression into a 4905 /// call. Returns true if recovery was attempted or an error was 4906 /// emitted; this may also leave the ExprResult invalid. 4907 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, 4908 bool ForceComplain = false, 4909 bool (*IsPlausibleResult)(QualType) = nullptr); 4910 4911 /// Figure out if an expression could be turned into a call. 4912 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, 4913 UnresolvedSetImpl &NonTemplateOverloads); 4914 4915 /// Try to convert an expression \p E to type \p Ty. Returns the result of the 4916 /// conversion. 4917 ExprResult tryConvertExprToType(Expr *E, QualType Ty); 4918 4919 /// Conditionally issue a diagnostic based on the current 4920 /// evaluation context. 4921 /// 4922 /// \param Statement If Statement is non-null, delay reporting the 4923 /// diagnostic until the function body is parsed, and then do a basic 4924 /// reachability analysis to determine if the statement is reachable. 4925 /// If it is unreachable, the diagnostic will not be emitted. 4926 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 4927 const PartialDiagnostic &PD); 4928 /// Similar, but diagnostic is only produced if all the specified statements 4929 /// are reachable. 4930 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 4931 const PartialDiagnostic &PD); 4932 4933 // Primary Expressions. 4934 SourceRange getExprRange(Expr *E) const; 4935 4936 ExprResult ActOnIdExpression( 4937 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 4938 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, 4939 CorrectionCandidateCallback *CCC = nullptr, 4940 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr); 4941 4942 void DecomposeUnqualifiedId(const UnqualifiedId &Id, 4943 TemplateArgumentListInfo &Buffer, 4944 DeclarationNameInfo &NameInfo, 4945 const TemplateArgumentListInfo *&TemplateArgs); 4946 4947 bool DiagnoseDependentMemberLookup(LookupResult &R); 4948 4949 bool 4950 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 4951 CorrectionCandidateCallback &CCC, 4952 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, 4953 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr); 4954 4955 DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 4956 IdentifierInfo *II); 4957 ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV); 4958 4959 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, 4960 IdentifierInfo *II, 4961 bool AllowBuiltinCreation=false); 4962 4963 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, 4964 SourceLocation TemplateKWLoc, 4965 const DeclarationNameInfo &NameInfo, 4966 bool isAddressOfOperand, 4967 const TemplateArgumentListInfo *TemplateArgs); 4968 4969 /// If \p D cannot be odr-used in the current expression evaluation context, 4970 /// return a reason explaining why. Otherwise, return NOUR_None. 4971 NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D); 4972 4973 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 4974 SourceLocation Loc, 4975 const CXXScopeSpec *SS = nullptr); 4976 DeclRefExpr * 4977 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 4978 const DeclarationNameInfo &NameInfo, 4979 const CXXScopeSpec *SS = nullptr, 4980 NamedDecl *FoundD = nullptr, 4981 SourceLocation TemplateKWLoc = SourceLocation(), 4982 const TemplateArgumentListInfo *TemplateArgs = nullptr); 4983 DeclRefExpr * 4984 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 4985 const DeclarationNameInfo &NameInfo, 4986 NestedNameSpecifierLoc NNS, 4987 NamedDecl *FoundD = nullptr, 4988 SourceLocation TemplateKWLoc = SourceLocation(), 4989 const TemplateArgumentListInfo *TemplateArgs = nullptr); 4990 4991 ExprResult 4992 BuildAnonymousStructUnionMemberReference( 4993 const CXXScopeSpec &SS, 4994 SourceLocation nameLoc, 4995 IndirectFieldDecl *indirectField, 4996 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none), 4997 Expr *baseObjectExpr = nullptr, 4998 SourceLocation opLoc = SourceLocation()); 4999 5000 ExprResult BuildPossibleImplicitMemberExpr( 5001 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, 5002 const TemplateArgumentListInfo *TemplateArgs, const Scope *S, 5003 UnresolvedLookupExpr *AsULE = nullptr); 5004 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, 5005 SourceLocation TemplateKWLoc, 5006 LookupResult &R, 5007 const TemplateArgumentListInfo *TemplateArgs, 5008 bool IsDefiniteInstance, 5009 const Scope *S); 5010 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, 5011 const LookupResult &R, 5012 bool HasTrailingLParen); 5013 5014 ExprResult 5015 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 5016 const DeclarationNameInfo &NameInfo, 5017 bool IsAddressOfOperand, const Scope *S, 5018 TypeSourceInfo **RecoveryTSI = nullptr); 5019 5020 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, 5021 SourceLocation TemplateKWLoc, 5022 const DeclarationNameInfo &NameInfo, 5023 const TemplateArgumentListInfo *TemplateArgs); 5024 5025 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, 5026 LookupResult &R, 5027 bool NeedsADL, 5028 bool AcceptInvalidDecl = false); 5029 ExprResult BuildDeclarationNameExpr( 5030 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 5031 NamedDecl *FoundD = nullptr, 5032 const TemplateArgumentListInfo *TemplateArgs = nullptr, 5033 bool AcceptInvalidDecl = false); 5034 5035 ExprResult BuildLiteralOperatorCall(LookupResult &R, 5036 DeclarationNameInfo &SuffixInfo, 5037 ArrayRef<Expr *> Args, 5038 SourceLocation LitEndLoc, 5039 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); 5040 5041 ExprResult BuildPredefinedExpr(SourceLocation Loc, 5042 PredefinedExpr::IdentKind IK); 5043 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); 5044 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); 5045 5046 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc); 5047 5048 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr); 5049 ExprResult ActOnCharacterConstant(const Token &Tok, 5050 Scope *UDLScope = nullptr); 5051 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); 5052 ExprResult ActOnParenListExpr(SourceLocation L, 5053 SourceLocation R, 5054 MultiExprArg Val); 5055 5056 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 5057 /// fragments (e.g. "foo" "bar" L"baz"). 5058 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks, 5059 Scope *UDLScope = nullptr); 5060 5061 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, 5062 SourceLocation DefaultLoc, 5063 SourceLocation RParenLoc, 5064 Expr *ControllingExpr, 5065 ArrayRef<ParsedType> ArgTypes, 5066 ArrayRef<Expr *> ArgExprs); 5067 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, 5068 SourceLocation DefaultLoc, 5069 SourceLocation RParenLoc, 5070 Expr *ControllingExpr, 5071 ArrayRef<TypeSourceInfo *> Types, 5072 ArrayRef<Expr *> Exprs); 5073 5074 // Binary/Unary Operators. 'Tok' is the token for the operator. 5075 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 5076 Expr *InputExpr); 5077 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, 5078 UnaryOperatorKind Opc, Expr *Input); 5079 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 5080 tok::TokenKind Op, Expr *Input); 5081 5082 bool isQualifiedMemberAccess(Expr *E); 5083 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc); 5084 5085 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 5086 SourceLocation OpLoc, 5087 UnaryExprOrTypeTrait ExprKind, 5088 SourceRange R); 5089 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 5090 UnaryExprOrTypeTrait ExprKind); 5091 ExprResult 5092 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 5093 UnaryExprOrTypeTrait ExprKind, 5094 bool IsType, void *TyOrEx, 5095 SourceRange ArgRange); 5096 5097 ExprResult CheckPlaceholderExpr(Expr *E); 5098 bool CheckVecStepExpr(Expr *E); 5099 5100 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); 5101 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, 5102 SourceRange ExprRange, 5103 UnaryExprOrTypeTrait ExprKind); 5104 ExprResult ActOnSizeofParameterPackExpr(Scope *S, 5105 SourceLocation OpLoc, 5106 IdentifierInfo &Name, 5107 SourceLocation NameLoc, 5108 SourceLocation RParenLoc); 5109 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 5110 tok::TokenKind Kind, Expr *Input); 5111 5112 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, 5113 Expr *Idx, SourceLocation RLoc); 5114 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5115 Expr *Idx, SourceLocation RLoc); 5116 5117 ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 5118 Expr *ColumnIdx, 5119 SourceLocation RBLoc); 5120 5121 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 5122 Expr *LowerBound, 5123 SourceLocation ColonLocFirst, 5124 SourceLocation ColonLocSecond, 5125 Expr *Length, Expr *Stride, 5126 SourceLocation RBLoc); 5127 ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5128 SourceLocation RParenLoc, 5129 ArrayRef<Expr *> Dims, 5130 ArrayRef<SourceRange> Brackets); 5131 5132 /// Data structure for iterator expression. 5133 struct OMPIteratorData { 5134 IdentifierInfo *DeclIdent = nullptr; 5135 SourceLocation DeclIdentLoc; 5136 ParsedType Type; 5137 OMPIteratorExpr::IteratorRange Range; 5138 SourceLocation AssignLoc; 5139 SourceLocation ColonLoc; 5140 SourceLocation SecColonLoc; 5141 }; 5142 5143 ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5144 SourceLocation LLoc, SourceLocation RLoc, 5145 ArrayRef<OMPIteratorData> Data); 5146 5147 // This struct is for use by ActOnMemberAccess to allow 5148 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after 5149 // changing the access operator from a '.' to a '->' (to see if that is the 5150 // change needed to fix an error about an unknown member, e.g. when the class 5151 // defines a custom operator->). 5152 struct ActOnMemberAccessExtraArgs { 5153 Scope *S; 5154 UnqualifiedId &Id; 5155 Decl *ObjCImpDecl; 5156 }; 5157 5158 ExprResult BuildMemberReferenceExpr( 5159 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, 5160 CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 5161 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, 5162 const TemplateArgumentListInfo *TemplateArgs, 5163 const Scope *S, 5164 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); 5165 5166 ExprResult 5167 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, 5168 bool IsArrow, const CXXScopeSpec &SS, 5169 SourceLocation TemplateKWLoc, 5170 NamedDecl *FirstQualifierInScope, LookupResult &R, 5171 const TemplateArgumentListInfo *TemplateArgs, 5172 const Scope *S, 5173 bool SuppressQualifierCheck = false, 5174 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); 5175 5176 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, 5177 SourceLocation OpLoc, 5178 const CXXScopeSpec &SS, FieldDecl *Field, 5179 DeclAccessPair FoundDecl, 5180 const DeclarationNameInfo &MemberNameInfo); 5181 5182 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); 5183 5184 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, 5185 const CXXScopeSpec &SS, 5186 const LookupResult &R); 5187 5188 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, 5189 bool IsArrow, SourceLocation OpLoc, 5190 const CXXScopeSpec &SS, 5191 SourceLocation TemplateKWLoc, 5192 NamedDecl *FirstQualifierInScope, 5193 const DeclarationNameInfo &NameInfo, 5194 const TemplateArgumentListInfo *TemplateArgs); 5195 5196 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, 5197 SourceLocation OpLoc, 5198 tok::TokenKind OpKind, 5199 CXXScopeSpec &SS, 5200 SourceLocation TemplateKWLoc, 5201 UnqualifiedId &Member, 5202 Decl *ObjCImpDecl); 5203 5204 MemberExpr * 5205 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, 5206 const CXXScopeSpec *SS, SourceLocation TemplateKWLoc, 5207 ValueDecl *Member, DeclAccessPair FoundDecl, 5208 bool HadMultipleCandidates, 5209 const DeclarationNameInfo &MemberNameInfo, QualType Ty, 5210 ExprValueKind VK, ExprObjectKind OK, 5211 const TemplateArgumentListInfo *TemplateArgs = nullptr); 5212 MemberExpr * 5213 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, 5214 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, 5215 ValueDecl *Member, DeclAccessPair FoundDecl, 5216 bool HadMultipleCandidates, 5217 const DeclarationNameInfo &MemberNameInfo, QualType Ty, 5218 ExprValueKind VK, ExprObjectKind OK, 5219 const TemplateArgumentListInfo *TemplateArgs = nullptr); 5220 5221 void ActOnDefaultCtorInitializers(Decl *CDtorDecl); 5222 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5223 FunctionDecl *FDecl, 5224 const FunctionProtoType *Proto, 5225 ArrayRef<Expr *> Args, 5226 SourceLocation RParenLoc, 5227 bool ExecConfig = false); 5228 void CheckStaticArrayArgument(SourceLocation CallLoc, 5229 ParmVarDecl *Param, 5230 const Expr *ArgExpr); 5231 5232 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5233 /// This provides the location of the left/right parens and a list of comma 5234 /// locations. 5235 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 5236 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5237 Expr *ExecConfig = nullptr); 5238 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 5239 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5240 Expr *ExecConfig = nullptr, 5241 bool IsExecConfig = false); 5242 enum class AtomicArgumentOrder { API, AST }; 5243 ExprResult 5244 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 5245 SourceLocation RParenLoc, MultiExprArg Args, 5246 AtomicExpr::AtomicOp Op, 5247 AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API); 5248 ExprResult 5249 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, 5250 ArrayRef<Expr *> Arg, SourceLocation RParenLoc, 5251 Expr *Config = nullptr, bool IsExecConfig = false, 5252 ADLCallKind UsesADL = ADLCallKind::NotADL); 5253 5254 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 5255 MultiExprArg ExecConfig, 5256 SourceLocation GGGLoc); 5257 5258 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5259 Declarator &D, ParsedType &Ty, 5260 SourceLocation RParenLoc, Expr *CastExpr); 5261 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, 5262 TypeSourceInfo *Ty, 5263 SourceLocation RParenLoc, 5264 Expr *Op); 5265 CastKind PrepareScalarCast(ExprResult &src, QualType destType); 5266 5267 /// Build an altivec or OpenCL literal. 5268 ExprResult BuildVectorLiteral(SourceLocation LParenLoc, 5269 SourceLocation RParenLoc, Expr *E, 5270 TypeSourceInfo *TInfo); 5271 5272 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); 5273 5274 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, 5275 ParsedType Ty, 5276 SourceLocation RParenLoc, 5277 Expr *InitExpr); 5278 5279 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, 5280 TypeSourceInfo *TInfo, 5281 SourceLocation RParenLoc, 5282 Expr *LiteralExpr); 5283 5284 ExprResult ActOnInitList(SourceLocation LBraceLoc, 5285 MultiExprArg InitArgList, 5286 SourceLocation RBraceLoc); 5287 5288 ExprResult BuildInitList(SourceLocation LBraceLoc, 5289 MultiExprArg InitArgList, 5290 SourceLocation RBraceLoc); 5291 5292 ExprResult ActOnDesignatedInitializer(Designation &Desig, 5293 SourceLocation EqualOrColonLoc, 5294 bool GNUSyntax, 5295 ExprResult Init); 5296 5297 private: 5298 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind); 5299 5300 public: 5301 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, 5302 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); 5303 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, 5304 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); 5305 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, 5306 Expr *LHSExpr, Expr *RHSExpr); 5307 void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 5308 UnresolvedSetImpl &Functions); 5309 5310 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc); 5311 5312 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 5313 /// in the case of a the GNU conditional expr extension. 5314 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, 5315 SourceLocation ColonLoc, 5316 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); 5317 5318 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 5319 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 5320 LabelDecl *TheDecl); 5321 5322 void ActOnStartStmtExpr(); 5323 ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 5324 SourceLocation RPLoc); 5325 ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 5326 SourceLocation RPLoc, unsigned TemplateDepth); 5327 // Handle the final expression in a statement expression. 5328 ExprResult ActOnStmtExprResult(ExprResult E); 5329 void ActOnStmtExprError(); 5330 5331 // __builtin_offsetof(type, identifier(.identifier|[expr])*) 5332 struct OffsetOfComponent { 5333 SourceLocation LocStart, LocEnd; 5334 bool isBrackets; // true if [expr], false if .ident 5335 union { 5336 IdentifierInfo *IdentInfo; 5337 Expr *E; 5338 } U; 5339 }; 5340 5341 /// __builtin_offsetof(type, a.b[123][456].c) 5342 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 5343 TypeSourceInfo *TInfo, 5344 ArrayRef<OffsetOfComponent> Components, 5345 SourceLocation RParenLoc); 5346 ExprResult ActOnBuiltinOffsetOf(Scope *S, 5347 SourceLocation BuiltinLoc, 5348 SourceLocation TypeLoc, 5349 ParsedType ParsedArgTy, 5350 ArrayRef<OffsetOfComponent> Components, 5351 SourceLocation RParenLoc); 5352 5353 // __builtin_choose_expr(constExpr, expr1, expr2) 5354 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, 5355 Expr *CondExpr, Expr *LHSExpr, 5356 Expr *RHSExpr, SourceLocation RPLoc); 5357 5358 // __builtin_va_arg(expr, type) 5359 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 5360 SourceLocation RPLoc); 5361 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, 5362 TypeSourceInfo *TInfo, SourceLocation RPLoc); 5363 5364 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(), 5365 // __builtin_COLUMN() 5366 ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 5367 SourceLocation BuiltinLoc, 5368 SourceLocation RPLoc); 5369 5370 // Build a potentially resolved SourceLocExpr. 5371 ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 5372 SourceLocation BuiltinLoc, SourceLocation RPLoc, 5373 DeclContext *ParentContext); 5374 5375 // __null 5376 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); 5377 5378 bool CheckCaseExpression(Expr *E); 5379 5380 /// Describes the result of an "if-exists" condition check. 5381 enum IfExistsResult { 5382 /// The symbol exists. 5383 IER_Exists, 5384 5385 /// The symbol does not exist. 5386 IER_DoesNotExist, 5387 5388 /// The name is a dependent name, so the results will differ 5389 /// from one instantiation to the next. 5390 IER_Dependent, 5391 5392 /// An error occurred. 5393 IER_Error 5394 }; 5395 5396 IfExistsResult 5397 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, 5398 const DeclarationNameInfo &TargetNameInfo); 5399 5400 IfExistsResult 5401 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, 5402 bool IsIfExists, CXXScopeSpec &SS, 5403 UnqualifiedId &Name); 5404 5405 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, 5406 bool IsIfExists, 5407 NestedNameSpecifierLoc QualifierLoc, 5408 DeclarationNameInfo NameInfo, 5409 Stmt *Nested); 5410 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, 5411 bool IsIfExists, 5412 CXXScopeSpec &SS, UnqualifiedId &Name, 5413 Stmt *Nested); 5414 5415 //===------------------------- "Block" Extension ------------------------===// 5416 5417 /// ActOnBlockStart - This callback is invoked when a block literal is 5418 /// started. 5419 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); 5420 5421 /// ActOnBlockArguments - This callback allows processing of block arguments. 5422 /// If there are no arguments, this is still invoked. 5423 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 5424 Scope *CurScope); 5425 5426 /// ActOnBlockError - If there is an error parsing a block, this callback 5427 /// is invoked to pop the information about the block from the action impl. 5428 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); 5429 5430 /// ActOnBlockStmtExpr - This is called when the body of a block statement 5431 /// literal was successfully completed. ^(int x){...} 5432 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, 5433 Scope *CurScope); 5434 5435 //===---------------------------- Clang Extensions ----------------------===// 5436 5437 /// __builtin_convertvector(...) 5438 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5439 SourceLocation BuiltinLoc, 5440 SourceLocation RParenLoc); 5441 5442 //===---------------------------- OpenCL Features -----------------------===// 5443 5444 /// __builtin_astype(...) 5445 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5446 SourceLocation BuiltinLoc, 5447 SourceLocation RParenLoc); 5448 5449 //===---------------------------- C++ Features --------------------------===// 5450 5451 // Act on C++ namespaces 5452 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, 5453 SourceLocation NamespaceLoc, 5454 SourceLocation IdentLoc, IdentifierInfo *Ident, 5455 SourceLocation LBrace, 5456 const ParsedAttributesView &AttrList, 5457 UsingDirectiveDecl *&UsingDecl); 5458 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); 5459 5460 NamespaceDecl *getStdNamespace() const; 5461 NamespaceDecl *getOrCreateStdNamespace(); 5462 5463 NamespaceDecl *lookupStdExperimentalNamespace(); 5464 5465 CXXRecordDecl *getStdBadAlloc() const; 5466 EnumDecl *getStdAlignValT() const; 5467 5468 private: 5469 // A cache representing if we've fully checked the various comparison category 5470 // types stored in ASTContext. The bit-index corresponds to the integer value 5471 // of a ComparisonCategoryType enumerator. 5472 llvm::SmallBitVector FullyCheckedComparisonCategories; 5473 5474 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 5475 CXXScopeSpec &SS, 5476 ParsedType TemplateTypeTy, 5477 IdentifierInfo *MemberOrBase); 5478 5479 public: 5480 enum class ComparisonCategoryUsage { 5481 /// The '<=>' operator was used in an expression and a builtin operator 5482 /// was selected. 5483 OperatorInExpression, 5484 /// A defaulted 'operator<=>' needed the comparison category. This 5485 /// typically only applies to 'std::strong_ordering', due to the implicit 5486 /// fallback return value. 5487 DefaultedOperator, 5488 }; 5489 5490 /// Lookup the specified comparison category types in the standard 5491 /// library, an check the VarDecls possibly returned by the operator<=> 5492 /// builtins for that type. 5493 /// 5494 /// \return The type of the comparison category type corresponding to the 5495 /// specified Kind, or a null type if an error occurs 5496 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, 5497 SourceLocation Loc, 5498 ComparisonCategoryUsage Usage); 5499 5500 /// Tests whether Ty is an instance of std::initializer_list and, if 5501 /// it is and Element is not NULL, assigns the element type to Element. 5502 bool isStdInitializerList(QualType Ty, QualType *Element); 5503 5504 /// Looks for the std::initializer_list template and instantiates it 5505 /// with Element, or emits an error if it's not found. 5506 /// 5507 /// \returns The instantiated template, or null on error. 5508 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); 5509 5510 /// Determine whether Ctor is an initializer-list constructor, as 5511 /// defined in [dcl.init.list]p2. 5512 bool isInitListConstructor(const FunctionDecl *Ctor); 5513 5514 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, 5515 SourceLocation NamespcLoc, CXXScopeSpec &SS, 5516 SourceLocation IdentLoc, 5517 IdentifierInfo *NamespcName, 5518 const ParsedAttributesView &AttrList); 5519 5520 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); 5521 5522 Decl *ActOnNamespaceAliasDef(Scope *CurScope, 5523 SourceLocation NamespaceLoc, 5524 SourceLocation AliasLoc, 5525 IdentifierInfo *Alias, 5526 CXXScopeSpec &SS, 5527 SourceLocation IdentLoc, 5528 IdentifierInfo *Ident); 5529 5530 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); 5531 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, 5532 const LookupResult &PreviousDecls, 5533 UsingShadowDecl *&PrevShadow); 5534 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD, 5535 NamedDecl *Target, 5536 UsingShadowDecl *PrevDecl); 5537 5538 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 5539 bool HasTypenameKeyword, 5540 const CXXScopeSpec &SS, 5541 SourceLocation NameLoc, 5542 const LookupResult &Previous); 5543 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, 5544 bool HasTypename, 5545 const CXXScopeSpec &SS, 5546 const DeclarationNameInfo &NameInfo, 5547 SourceLocation NameLoc); 5548 5549 NamedDecl *BuildUsingDeclaration( 5550 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 5551 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 5552 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 5553 const ParsedAttributesView &AttrList, bool IsInstantiation); 5554 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 5555 ArrayRef<NamedDecl *> Expansions); 5556 5557 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); 5558 5559 /// Given a derived-class using shadow declaration for a constructor and the 5560 /// correspnding base class constructor, find or create the implicit 5561 /// synthesized derived class constructor to use for this initialization. 5562 CXXConstructorDecl * 5563 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, 5564 ConstructorUsingShadowDecl *DerivedShadow); 5565 5566 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, 5567 SourceLocation UsingLoc, 5568 SourceLocation TypenameLoc, CXXScopeSpec &SS, 5569 UnqualifiedId &Name, SourceLocation EllipsisLoc, 5570 const ParsedAttributesView &AttrList); 5571 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, 5572 MultiTemplateParamsArg TemplateParams, 5573 SourceLocation UsingLoc, UnqualifiedId &Name, 5574 const ParsedAttributesView &AttrList, 5575 TypeResult Type, Decl *DeclFromDeclSpec); 5576 5577 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 5578 /// including handling of its default argument expressions. 5579 /// 5580 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind 5581 ExprResult 5582 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 5583 NamedDecl *FoundDecl, 5584 CXXConstructorDecl *Constructor, MultiExprArg Exprs, 5585 bool HadMultipleCandidates, bool IsListInitialization, 5586 bool IsStdInitListInitialization, 5587 bool RequiresZeroInit, unsigned ConstructKind, 5588 SourceRange ParenRange); 5589 5590 /// Build a CXXConstructExpr whose constructor has already been resolved if 5591 /// it denotes an inherited constructor. 5592 ExprResult 5593 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 5594 CXXConstructorDecl *Constructor, bool Elidable, 5595 MultiExprArg Exprs, 5596 bool HadMultipleCandidates, bool IsListInitialization, 5597 bool IsStdInitListInitialization, 5598 bool RequiresZeroInit, unsigned ConstructKind, 5599 SourceRange ParenRange); 5600 5601 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if 5602 // the constructor can be elidable? 5603 ExprResult 5604 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 5605 NamedDecl *FoundDecl, 5606 CXXConstructorDecl *Constructor, bool Elidable, 5607 MultiExprArg Exprs, bool HadMultipleCandidates, 5608 bool IsListInitialization, 5609 bool IsStdInitListInitialization, bool RequiresZeroInit, 5610 unsigned ConstructKind, SourceRange ParenRange); 5611 5612 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field); 5613 5614 5615 /// Instantiate or parse a C++ default argument expression as necessary. 5616 /// Return true on error. 5617 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5618 ParmVarDecl *Param); 5619 5620 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating 5621 /// the default expr if needed. 5622 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5623 FunctionDecl *FD, 5624 ParmVarDecl *Param); 5625 5626 /// FinalizeVarWithDestructor - Prepare for calling destructor on the 5627 /// constructed variable. 5628 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); 5629 5630 /// Helper class that collects exception specifications for 5631 /// implicitly-declared special member functions. 5632 class ImplicitExceptionSpecification { 5633 // Pointer to allow copying 5634 Sema *Self; 5635 // We order exception specifications thus: 5636 // noexcept is the most restrictive, but is only used in C++11. 5637 // throw() comes next. 5638 // Then a throw(collected exceptions) 5639 // Finally no specification, which is expressed as noexcept(false). 5640 // throw(...) is used instead if any called function uses it. 5641 ExceptionSpecificationType ComputedEST; 5642 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; 5643 SmallVector<QualType, 4> Exceptions; 5644 ClearExceptions()5645 void ClearExceptions() { 5646 ExceptionsSeen.clear(); 5647 Exceptions.clear(); 5648 } 5649 5650 public: ImplicitExceptionSpecification(Sema & Self)5651 explicit ImplicitExceptionSpecification(Sema &Self) 5652 : Self(&Self), ComputedEST(EST_BasicNoexcept) { 5653 if (!Self.getLangOpts().CPlusPlus11) 5654 ComputedEST = EST_DynamicNone; 5655 } 5656 5657 /// Get the computed exception specification type. getExceptionSpecType()5658 ExceptionSpecificationType getExceptionSpecType() const { 5659 assert(!isComputedNoexcept(ComputedEST) && 5660 "noexcept(expr) should not be a possible result"); 5661 return ComputedEST; 5662 } 5663 5664 /// The number of exceptions in the exception specification. size()5665 unsigned size() const { return Exceptions.size(); } 5666 5667 /// The set of exceptions in the exception specification. data()5668 const QualType *data() const { return Exceptions.data(); } 5669 5670 /// Integrate another called method into the collected data. 5671 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); 5672 5673 /// Integrate an invoked expression into the collected data. CalledExpr(Expr * E)5674 void CalledExpr(Expr *E) { CalledStmt(E); } 5675 5676 /// Integrate an invoked statement into the collected data. 5677 void CalledStmt(Stmt *S); 5678 5679 /// Overwrite an EPI's exception specification with this 5680 /// computed exception specification. getExceptionSpec()5681 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const { 5682 FunctionProtoType::ExceptionSpecInfo ESI; 5683 ESI.Type = getExceptionSpecType(); 5684 if (ESI.Type == EST_Dynamic) { 5685 ESI.Exceptions = Exceptions; 5686 } else if (ESI.Type == EST_None) { 5687 /// C++11 [except.spec]p14: 5688 /// The exception-specification is noexcept(false) if the set of 5689 /// potential exceptions of the special member function contains "any" 5690 ESI.Type = EST_NoexceptFalse; 5691 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(), 5692 tok::kw_false).get(); 5693 } 5694 return ESI; 5695 } 5696 }; 5697 5698 /// Evaluate the implicit exception specification for a defaulted 5699 /// special member function. 5700 void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD); 5701 5702 /// Check the given noexcept-specifier, convert its expression, and compute 5703 /// the appropriate ExceptionSpecificationType. 5704 ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr, 5705 ExceptionSpecificationType &EST); 5706 5707 /// Check the given exception-specification and update the 5708 /// exception specification information with the results. 5709 void checkExceptionSpecification(bool IsTopLevel, 5710 ExceptionSpecificationType EST, 5711 ArrayRef<ParsedType> DynamicExceptions, 5712 ArrayRef<SourceRange> DynamicExceptionRanges, 5713 Expr *NoexceptExpr, 5714 SmallVectorImpl<QualType> &Exceptions, 5715 FunctionProtoType::ExceptionSpecInfo &ESI); 5716 5717 /// Determine if we're in a case where we need to (incorrectly) eagerly 5718 /// parse an exception specification to work around a libstdc++ bug. 5719 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D); 5720 5721 /// Add an exception-specification to the given member function 5722 /// (or member function template). The exception-specification was parsed 5723 /// after the method itself was declared. 5724 void actOnDelayedExceptionSpecification(Decl *Method, 5725 ExceptionSpecificationType EST, 5726 SourceRange SpecificationRange, 5727 ArrayRef<ParsedType> DynamicExceptions, 5728 ArrayRef<SourceRange> DynamicExceptionRanges, 5729 Expr *NoexceptExpr); 5730 5731 class InheritedConstructorInfo; 5732 5733 /// Determine if a special member function should have a deleted 5734 /// definition when it is defaulted. 5735 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5736 InheritedConstructorInfo *ICI = nullptr, 5737 bool Diagnose = false); 5738 5739 /// Produce notes explaining why a defaulted function was defined as deleted. 5740 void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD); 5741 5742 /// Declare the implicit default constructor for the given class. 5743 /// 5744 /// \param ClassDecl The class declaration into which the implicit 5745 /// default constructor will be added. 5746 /// 5747 /// \returns The implicitly-declared default constructor. 5748 CXXConstructorDecl *DeclareImplicitDefaultConstructor( 5749 CXXRecordDecl *ClassDecl); 5750 5751 /// DefineImplicitDefaultConstructor - Checks for feasibility of 5752 /// defining this constructor as the default constructor. 5753 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 5754 CXXConstructorDecl *Constructor); 5755 5756 /// Declare the implicit destructor for the given class. 5757 /// 5758 /// \param ClassDecl The class declaration into which the implicit 5759 /// destructor will be added. 5760 /// 5761 /// \returns The implicitly-declared destructor. 5762 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); 5763 5764 /// DefineImplicitDestructor - Checks for feasibility of 5765 /// defining this destructor as the default destructor. 5766 void DefineImplicitDestructor(SourceLocation CurrentLocation, 5767 CXXDestructorDecl *Destructor); 5768 5769 /// Build an exception spec for destructors that don't have one. 5770 /// 5771 /// C++11 says that user-defined destructors with no exception spec get one 5772 /// that looks as if the destructor was implicitly declared. 5773 void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor); 5774 5775 /// Define the specified inheriting constructor. 5776 void DefineInheritingConstructor(SourceLocation UseLoc, 5777 CXXConstructorDecl *Constructor); 5778 5779 /// Declare the implicit copy constructor for the given class. 5780 /// 5781 /// \param ClassDecl The class declaration into which the implicit 5782 /// copy constructor will be added. 5783 /// 5784 /// \returns The implicitly-declared copy constructor. 5785 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); 5786 5787 /// DefineImplicitCopyConstructor - Checks for feasibility of 5788 /// defining this constructor as the copy constructor. 5789 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 5790 CXXConstructorDecl *Constructor); 5791 5792 /// Declare the implicit move constructor for the given class. 5793 /// 5794 /// \param ClassDecl The Class declaration into which the implicit 5795 /// move constructor will be added. 5796 /// 5797 /// \returns The implicitly-declared move constructor, or NULL if it wasn't 5798 /// declared. 5799 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); 5800 5801 /// DefineImplicitMoveConstructor - Checks for feasibility of 5802 /// defining this constructor as the move constructor. 5803 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 5804 CXXConstructorDecl *Constructor); 5805 5806 /// Declare the implicit copy assignment operator for the given class. 5807 /// 5808 /// \param ClassDecl The class declaration into which the implicit 5809 /// copy assignment operator will be added. 5810 /// 5811 /// \returns The implicitly-declared copy assignment operator. 5812 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); 5813 5814 /// Defines an implicitly-declared copy assignment operator. 5815 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 5816 CXXMethodDecl *MethodDecl); 5817 5818 /// Declare the implicit move assignment operator for the given class. 5819 /// 5820 /// \param ClassDecl The Class declaration into which the implicit 5821 /// move assignment operator will be added. 5822 /// 5823 /// \returns The implicitly-declared move assignment operator, or NULL if it 5824 /// wasn't declared. 5825 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); 5826 5827 /// Defines an implicitly-declared move assignment operator. 5828 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 5829 CXXMethodDecl *MethodDecl); 5830 5831 /// Force the declaration of any implicitly-declared members of this 5832 /// class. 5833 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); 5834 5835 /// Check a completed declaration of an implicit special member. 5836 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD); 5837 5838 /// Determine whether the given function is an implicitly-deleted 5839 /// special member function. 5840 bool isImplicitlyDeleted(FunctionDecl *FD); 5841 5842 /// Check whether 'this' shows up in the type of a static member 5843 /// function after the (naturally empty) cv-qualifier-seq would be. 5844 /// 5845 /// \returns true if an error occurred. 5846 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); 5847 5848 /// Whether this' shows up in the exception specification of a static 5849 /// member function. 5850 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); 5851 5852 /// Check whether 'this' shows up in the attributes of the given 5853 /// static member function. 5854 /// 5855 /// \returns true if an error occurred. 5856 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); 5857 5858 /// MaybeBindToTemporary - If the passed in expression has a record type with 5859 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise 5860 /// it simply returns the passed in expression. 5861 ExprResult MaybeBindToTemporary(Expr *E); 5862 5863 /// Wrap the expression in a ConstantExpr if it is a potential immediate 5864 /// invocation. 5865 ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl); 5866 5867 bool CompleteConstructorCall(CXXConstructorDecl *Constructor, 5868 MultiExprArg ArgsPtr, 5869 SourceLocation Loc, 5870 SmallVectorImpl<Expr*> &ConvertedArgs, 5871 bool AllowExplicit = false, 5872 bool IsListInitialization = false); 5873 5874 ParsedType getInheritingConstructorName(CXXScopeSpec &SS, 5875 SourceLocation NameLoc, 5876 IdentifierInfo &Name); 5877 5878 ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc, 5879 Scope *S, CXXScopeSpec &SS, 5880 bool EnteringContext); 5881 ParsedType getDestructorName(SourceLocation TildeLoc, 5882 IdentifierInfo &II, SourceLocation NameLoc, 5883 Scope *S, CXXScopeSpec &SS, 5884 ParsedType ObjectType, 5885 bool EnteringContext); 5886 5887 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, 5888 ParsedType ObjectType); 5889 5890 // Checks that reinterpret casts don't have undefined behavior. 5891 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, 5892 bool IsDereference, SourceRange Range); 5893 5894 /// ActOnCXXNamedCast - Parse 5895 /// {dynamic,static,reinterpret,const,addrspace}_cast's. 5896 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, 5897 tok::TokenKind Kind, 5898 SourceLocation LAngleBracketLoc, 5899 Declarator &D, 5900 SourceLocation RAngleBracketLoc, 5901 SourceLocation LParenLoc, 5902 Expr *E, 5903 SourceLocation RParenLoc); 5904 5905 ExprResult BuildCXXNamedCast(SourceLocation OpLoc, 5906 tok::TokenKind Kind, 5907 TypeSourceInfo *Ty, 5908 Expr *E, 5909 SourceRange AngleBrackets, 5910 SourceRange Parens); 5911 5912 ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl, 5913 ExprResult Operand, 5914 SourceLocation RParenLoc); 5915 5916 ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI, 5917 Expr *Operand, SourceLocation RParenLoc); 5918 5919 ExprResult BuildCXXTypeId(QualType TypeInfoType, 5920 SourceLocation TypeidLoc, 5921 TypeSourceInfo *Operand, 5922 SourceLocation RParenLoc); 5923 ExprResult BuildCXXTypeId(QualType TypeInfoType, 5924 SourceLocation TypeidLoc, 5925 Expr *Operand, 5926 SourceLocation RParenLoc); 5927 5928 /// ActOnCXXTypeid - Parse typeid( something ). 5929 ExprResult ActOnCXXTypeid(SourceLocation OpLoc, 5930 SourceLocation LParenLoc, bool isType, 5931 void *TyOrExpr, 5932 SourceLocation RParenLoc); 5933 5934 ExprResult BuildCXXUuidof(QualType TypeInfoType, 5935 SourceLocation TypeidLoc, 5936 TypeSourceInfo *Operand, 5937 SourceLocation RParenLoc); 5938 ExprResult BuildCXXUuidof(QualType TypeInfoType, 5939 SourceLocation TypeidLoc, 5940 Expr *Operand, 5941 SourceLocation RParenLoc); 5942 5943 /// ActOnCXXUuidof - Parse __uuidof( something ). 5944 ExprResult ActOnCXXUuidof(SourceLocation OpLoc, 5945 SourceLocation LParenLoc, bool isType, 5946 void *TyOrExpr, 5947 SourceLocation RParenLoc); 5948 5949 /// Handle a C++1z fold-expression: ( expr op ... op expr ). 5950 ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS, 5951 tok::TokenKind Operator, 5952 SourceLocation EllipsisLoc, Expr *RHS, 5953 SourceLocation RParenLoc); 5954 ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, 5955 SourceLocation LParenLoc, Expr *LHS, 5956 BinaryOperatorKind Operator, 5957 SourceLocation EllipsisLoc, Expr *RHS, 5958 SourceLocation RParenLoc, 5959 Optional<unsigned> NumExpansions); 5960 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, 5961 BinaryOperatorKind Operator); 5962 5963 //// ActOnCXXThis - Parse 'this' pointer. 5964 ExprResult ActOnCXXThis(SourceLocation loc); 5965 5966 /// Build a CXXThisExpr and mark it referenced in the current context. 5967 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit); 5968 void MarkThisReferenced(CXXThisExpr *This); 5969 5970 /// Try to retrieve the type of the 'this' pointer. 5971 /// 5972 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. 5973 QualType getCurrentThisType(); 5974 5975 /// When non-NULL, the C++ 'this' expression is allowed despite the 5976 /// current context not being a non-static member function. In such cases, 5977 /// this provides the type used for 'this'. 5978 QualType CXXThisTypeOverride; 5979 5980 /// RAII object used to temporarily allow the C++ 'this' expression 5981 /// to be used, with the given qualifiers on the current class type. 5982 class CXXThisScopeRAII { 5983 Sema &S; 5984 QualType OldCXXThisTypeOverride; 5985 bool Enabled; 5986 5987 public: 5988 /// Introduce a new scope where 'this' may be allowed (when enabled), 5989 /// using the given declaration (which is either a class template or a 5990 /// class) along with the given qualifiers. 5991 /// along with the qualifiers placed on '*this'. 5992 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, 5993 bool Enabled = true); 5994 5995 ~CXXThisScopeRAII(); 5996 }; 5997 5998 /// Make sure the value of 'this' is actually available in the current 5999 /// context, if it is a potentially evaluated context. 6000 /// 6001 /// \param Loc The location at which the capture of 'this' occurs. 6002 /// 6003 /// \param Explicit Whether 'this' is explicitly captured in a lambda 6004 /// capture list. 6005 /// 6006 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index 6007 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. 6008 /// This is useful when enclosing lambdas must speculatively capture 6009 /// 'this' that may or may not be used in certain specializations of 6010 /// a nested generic lambda (depending on whether the name resolves to 6011 /// a non-static member function or a static function). 6012 /// \return returns 'true' if failed, 'false' if success. 6013 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false, 6014 bool BuildAndDiagnose = true, 6015 const unsigned *const FunctionScopeIndexToStopAt = nullptr, 6016 bool ByCopy = false); 6017 6018 /// Determine whether the given type is the type of *this that is used 6019 /// outside of the body of a member function for a type that is currently 6020 /// being defined. 6021 bool isThisOutsideMemberFunctionBody(QualType BaseType); 6022 6023 /// ActOnCXXBoolLiteral - Parse {true,false} literals. 6024 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 6025 6026 6027 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 6028 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 6029 6030 ExprResult 6031 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs, 6032 SourceLocation AtLoc, SourceLocation RParen); 6033 6034 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 6035 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); 6036 6037 //// ActOnCXXThrow - Parse throw expressions. 6038 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); 6039 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, 6040 bool IsThrownVarInScope); 6041 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E); 6042 6043 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 6044 /// Can be interpreted either as function-style casting ("int(x)") 6045 /// or class type construction ("ClassType(x,y,z)") 6046 /// or creation of a value-initialized type ("int()"). 6047 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, 6048 SourceLocation LParenOrBraceLoc, 6049 MultiExprArg Exprs, 6050 SourceLocation RParenOrBraceLoc, 6051 bool ListInitialization); 6052 6053 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, 6054 SourceLocation LParenLoc, 6055 MultiExprArg Exprs, 6056 SourceLocation RParenLoc, 6057 bool ListInitialization); 6058 6059 /// ActOnCXXNew - Parsed a C++ 'new' expression. 6060 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 6061 SourceLocation PlacementLParen, 6062 MultiExprArg PlacementArgs, 6063 SourceLocation PlacementRParen, 6064 SourceRange TypeIdParens, Declarator &D, 6065 Expr *Initializer); 6066 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, 6067 SourceLocation PlacementLParen, 6068 MultiExprArg PlacementArgs, 6069 SourceLocation PlacementRParen, 6070 SourceRange TypeIdParens, 6071 QualType AllocType, 6072 TypeSourceInfo *AllocTypeInfo, 6073 Optional<Expr *> ArraySize, 6074 SourceRange DirectInitRange, 6075 Expr *Initializer); 6076 6077 /// Determine whether \p FD is an aligned allocation or deallocation 6078 /// function that is unavailable. 6079 bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const; 6080 6081 /// Produce diagnostics if \p FD is an aligned allocation or deallocation 6082 /// function that is unavailable. 6083 void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, 6084 SourceLocation Loc); 6085 6086 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, 6087 SourceRange R); 6088 6089 /// The scope in which to find allocation functions. 6090 enum AllocationFunctionScope { 6091 /// Only look for allocation functions in the global scope. 6092 AFS_Global, 6093 /// Only look for allocation functions in the scope of the 6094 /// allocated class. 6095 AFS_Class, 6096 /// Look for allocation functions in both the global scope 6097 /// and in the scope of the allocated class. 6098 AFS_Both 6099 }; 6100 6101 /// Finds the overloads of operator new and delete that are appropriate 6102 /// for the allocation. 6103 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 6104 AllocationFunctionScope NewScope, 6105 AllocationFunctionScope DeleteScope, 6106 QualType AllocType, bool IsArray, 6107 bool &PassAlignment, MultiExprArg PlaceArgs, 6108 FunctionDecl *&OperatorNew, 6109 FunctionDecl *&OperatorDelete, 6110 bool Diagnose = true); 6111 void DeclareGlobalNewDelete(); 6112 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, 6113 ArrayRef<QualType> Params); 6114 6115 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 6116 DeclarationName Name, FunctionDecl* &Operator, 6117 bool Diagnose = true); 6118 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc, 6119 bool CanProvideSize, 6120 bool Overaligned, 6121 DeclarationName Name); 6122 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc, 6123 CXXRecordDecl *RD); 6124 6125 /// ActOnCXXDelete - Parsed a C++ 'delete' expression 6126 ExprResult ActOnCXXDelete(SourceLocation StartLoc, 6127 bool UseGlobal, bool ArrayForm, 6128 Expr *Operand); 6129 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, 6130 bool IsDelete, bool CallCanBeVirtual, 6131 bool WarnOnNonAbstractTypes, 6132 SourceLocation DtorLoc); 6133 6134 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, 6135 Expr *Operand, SourceLocation RParen); 6136 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 6137 SourceLocation RParen); 6138 6139 /// Parsed one of the type trait support pseudo-functions. 6140 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 6141 ArrayRef<ParsedType> Args, 6142 SourceLocation RParenLoc); 6143 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 6144 ArrayRef<TypeSourceInfo *> Args, 6145 SourceLocation RParenLoc); 6146 6147 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support 6148 /// pseudo-functions. 6149 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, 6150 SourceLocation KWLoc, 6151 ParsedType LhsTy, 6152 Expr *DimExpr, 6153 SourceLocation RParen); 6154 6155 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, 6156 SourceLocation KWLoc, 6157 TypeSourceInfo *TSInfo, 6158 Expr *DimExpr, 6159 SourceLocation RParen); 6160 6161 /// ActOnExpressionTrait - Parsed one of the unary type trait support 6162 /// pseudo-functions. 6163 ExprResult ActOnExpressionTrait(ExpressionTrait OET, 6164 SourceLocation KWLoc, 6165 Expr *Queried, 6166 SourceLocation RParen); 6167 6168 ExprResult BuildExpressionTrait(ExpressionTrait OET, 6169 SourceLocation KWLoc, 6170 Expr *Queried, 6171 SourceLocation RParen); 6172 6173 ExprResult ActOnStartCXXMemberReference(Scope *S, 6174 Expr *Base, 6175 SourceLocation OpLoc, 6176 tok::TokenKind OpKind, 6177 ParsedType &ObjectType, 6178 bool &MayBePseudoDestructor); 6179 6180 ExprResult BuildPseudoDestructorExpr(Expr *Base, 6181 SourceLocation OpLoc, 6182 tok::TokenKind OpKind, 6183 const CXXScopeSpec &SS, 6184 TypeSourceInfo *ScopeType, 6185 SourceLocation CCLoc, 6186 SourceLocation TildeLoc, 6187 PseudoDestructorTypeStorage DestroyedType); 6188 6189 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 6190 SourceLocation OpLoc, 6191 tok::TokenKind OpKind, 6192 CXXScopeSpec &SS, 6193 UnqualifiedId &FirstTypeName, 6194 SourceLocation CCLoc, 6195 SourceLocation TildeLoc, 6196 UnqualifiedId &SecondTypeName); 6197 6198 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 6199 SourceLocation OpLoc, 6200 tok::TokenKind OpKind, 6201 SourceLocation TildeLoc, 6202 const DeclSpec& DS); 6203 6204 /// MaybeCreateExprWithCleanups - If the current full-expression 6205 /// requires any cleanups, surround it with a ExprWithCleanups node. 6206 /// Otherwise, just returns the passed-in expression. 6207 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); 6208 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); 6209 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); 6210 6211 MaterializeTemporaryExpr * 6212 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, 6213 bool BoundToLvalueReference); 6214 ActOnFinishFullExpr(Expr * Expr,bool DiscardedValue)6215 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) { 6216 return ActOnFinishFullExpr( 6217 Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue); 6218 } 6219 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, 6220 bool DiscardedValue, bool IsConstexpr = false); 6221 StmtResult ActOnFinishFullStmt(Stmt *Stmt); 6222 6223 // Marks SS invalid if it represents an incomplete type. 6224 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); 6225 6226 DeclContext *computeDeclContext(QualType T); 6227 DeclContext *computeDeclContext(const CXXScopeSpec &SS, 6228 bool EnteringContext = false); 6229 bool isDependentScopeSpecifier(const CXXScopeSpec &SS); 6230 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); 6231 6232 /// The parser has parsed a global nested-name-specifier '::'. 6233 /// 6234 /// \param CCLoc The location of the '::'. 6235 /// 6236 /// \param SS The nested-name-specifier, which will be updated in-place 6237 /// to reflect the parsed nested-name-specifier. 6238 /// 6239 /// \returns true if an error occurred, false otherwise. 6240 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS); 6241 6242 /// The parser has parsed a '__super' nested-name-specifier. 6243 /// 6244 /// \param SuperLoc The location of the '__super' keyword. 6245 /// 6246 /// \param ColonColonLoc The location of the '::'. 6247 /// 6248 /// \param SS The nested-name-specifier, which will be updated in-place 6249 /// to reflect the parsed nested-name-specifier. 6250 /// 6251 /// \returns true if an error occurred, false otherwise. 6252 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, 6253 SourceLocation ColonColonLoc, CXXScopeSpec &SS); 6254 6255 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, 6256 bool *CanCorrect = nullptr); 6257 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); 6258 6259 /// Keeps information about an identifier in a nested-name-spec. 6260 /// 6261 struct NestedNameSpecInfo { 6262 /// The type of the object, if we're parsing nested-name-specifier in 6263 /// a member access expression. 6264 ParsedType ObjectType; 6265 6266 /// The identifier preceding the '::'. 6267 IdentifierInfo *Identifier; 6268 6269 /// The location of the identifier. 6270 SourceLocation IdentifierLoc; 6271 6272 /// The location of the '::'. 6273 SourceLocation CCLoc; 6274 6275 /// Creates info object for the most typical case. 6276 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, 6277 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType()) ObjectTypeNestedNameSpecInfo6278 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc), 6279 CCLoc(ColonColonLoc) { 6280 } 6281 NestedNameSpecInfoNestedNameSpecInfo6282 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, 6283 SourceLocation ColonColonLoc, QualType ObjectType) 6284 : ObjectType(ParsedType::make(ObjectType)), Identifier(II), 6285 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { 6286 } 6287 }; 6288 6289 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, 6290 NestedNameSpecInfo &IdInfo); 6291 6292 bool BuildCXXNestedNameSpecifier(Scope *S, 6293 NestedNameSpecInfo &IdInfo, 6294 bool EnteringContext, 6295 CXXScopeSpec &SS, 6296 NamedDecl *ScopeLookupResult, 6297 bool ErrorRecoveryLookup, 6298 bool *IsCorrectedToColon = nullptr, 6299 bool OnlyNamespace = false); 6300 6301 /// The parser has parsed a nested-name-specifier 'identifier::'. 6302 /// 6303 /// \param S The scope in which this nested-name-specifier occurs. 6304 /// 6305 /// \param IdInfo Parser information about an identifier in the 6306 /// nested-name-spec. 6307 /// 6308 /// \param EnteringContext Whether we're entering the context nominated by 6309 /// this nested-name-specifier. 6310 /// 6311 /// \param SS The nested-name-specifier, which is both an input 6312 /// parameter (the nested-name-specifier before this type) and an 6313 /// output parameter (containing the full nested-name-specifier, 6314 /// including this new type). 6315 /// 6316 /// \param ErrorRecoveryLookup If true, then this method is called to improve 6317 /// error recovery. In this case do not emit error message. 6318 /// 6319 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':' 6320 /// are allowed. The bool value pointed by this parameter is set to 'true' 6321 /// if the identifier is treated as if it was followed by ':', not '::'. 6322 /// 6323 /// \param OnlyNamespace If true, only considers namespaces in lookup. 6324 /// 6325 /// \returns true if an error occurred, false otherwise. 6326 bool ActOnCXXNestedNameSpecifier(Scope *S, 6327 NestedNameSpecInfo &IdInfo, 6328 bool EnteringContext, 6329 CXXScopeSpec &SS, 6330 bool ErrorRecoveryLookup = false, 6331 bool *IsCorrectedToColon = nullptr, 6332 bool OnlyNamespace = false); 6333 6334 ExprResult ActOnDecltypeExpression(Expr *E); 6335 6336 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, 6337 const DeclSpec &DS, 6338 SourceLocation ColonColonLoc); 6339 6340 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, 6341 NestedNameSpecInfo &IdInfo, 6342 bool EnteringContext); 6343 6344 /// The parser has parsed a nested-name-specifier 6345 /// 'template[opt] template-name < template-args >::'. 6346 /// 6347 /// \param S The scope in which this nested-name-specifier occurs. 6348 /// 6349 /// \param SS The nested-name-specifier, which is both an input 6350 /// parameter (the nested-name-specifier before this type) and an 6351 /// output parameter (containing the full nested-name-specifier, 6352 /// including this new type). 6353 /// 6354 /// \param TemplateKWLoc the location of the 'template' keyword, if any. 6355 /// \param TemplateName the template name. 6356 /// \param TemplateNameLoc The location of the template name. 6357 /// \param LAngleLoc The location of the opening angle bracket ('<'). 6358 /// \param TemplateArgs The template arguments. 6359 /// \param RAngleLoc The location of the closing angle bracket ('>'). 6360 /// \param CCLoc The location of the '::'. 6361 /// 6362 /// \param EnteringContext Whether we're entering the context of the 6363 /// nested-name-specifier. 6364 /// 6365 /// 6366 /// \returns true if an error occurred, false otherwise. 6367 bool ActOnCXXNestedNameSpecifier(Scope *S, 6368 CXXScopeSpec &SS, 6369 SourceLocation TemplateKWLoc, 6370 TemplateTy TemplateName, 6371 SourceLocation TemplateNameLoc, 6372 SourceLocation LAngleLoc, 6373 ASTTemplateArgsPtr TemplateArgs, 6374 SourceLocation RAngleLoc, 6375 SourceLocation CCLoc, 6376 bool EnteringContext); 6377 6378 /// Given a C++ nested-name-specifier, produce an annotation value 6379 /// that the parser can use later to reconstruct the given 6380 /// nested-name-specifier. 6381 /// 6382 /// \param SS A nested-name-specifier. 6383 /// 6384 /// \returns A pointer containing all of the information in the 6385 /// nested-name-specifier \p SS. 6386 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); 6387 6388 /// Given an annotation pointer for a nested-name-specifier, restore 6389 /// the nested-name-specifier structure. 6390 /// 6391 /// \param Annotation The annotation pointer, produced by 6392 /// \c SaveNestedNameSpecifierAnnotation(). 6393 /// 6394 /// \param AnnotationRange The source range corresponding to the annotation. 6395 /// 6396 /// \param SS The nested-name-specifier that will be updated with the contents 6397 /// of the annotation pointer. 6398 void RestoreNestedNameSpecifierAnnotation(void *Annotation, 6399 SourceRange AnnotationRange, 6400 CXXScopeSpec &SS); 6401 6402 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 6403 6404 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global 6405 /// scope or nested-name-specifier) is parsed, part of a declarator-id. 6406 /// After this method is called, according to [C++ 3.4.3p3], names should be 6407 /// looked up in the declarator-id's scope, until the declarator is parsed and 6408 /// ActOnCXXExitDeclaratorScope is called. 6409 /// The 'SS' should be a non-empty valid CXXScopeSpec. 6410 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); 6411 6412 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously 6413 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same 6414 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. 6415 /// Used to indicate that names should revert to being looked up in the 6416 /// defining scope. 6417 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 6418 6419 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an 6420 /// initializer for the declaration 'Dcl'. 6421 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 6422 /// static data member of class X, names should be looked up in the scope of 6423 /// class X. 6424 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); 6425 6426 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 6427 /// initializer for the declaration 'Dcl'. 6428 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); 6429 6430 /// Create a new lambda closure type. 6431 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, 6432 TypeSourceInfo *Info, 6433 bool KnownDependent, 6434 LambdaCaptureDefault CaptureDefault); 6435 6436 /// Start the definition of a lambda expression. 6437 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class, 6438 SourceRange IntroducerRange, 6439 TypeSourceInfo *MethodType, 6440 SourceLocation EndLoc, 6441 ArrayRef<ParmVarDecl *> Params, 6442 ConstexprSpecKind ConstexprKind, 6443 Expr *TrailingRequiresClause); 6444 6445 /// Number lambda for linkage purposes if necessary. 6446 void handleLambdaNumbering( 6447 CXXRecordDecl *Class, CXXMethodDecl *Method, 6448 Optional<std::tuple<unsigned, bool, Decl *>> Mangling = None); 6449 6450 /// Endow the lambda scope info with the relevant properties. 6451 void buildLambdaScope(sema::LambdaScopeInfo *LSI, 6452 CXXMethodDecl *CallOperator, 6453 SourceRange IntroducerRange, 6454 LambdaCaptureDefault CaptureDefault, 6455 SourceLocation CaptureDefaultLoc, 6456 bool ExplicitParams, 6457 bool ExplicitResultType, 6458 bool Mutable); 6459 6460 /// Perform initialization analysis of the init-capture and perform 6461 /// any implicit conversions such as an lvalue-to-rvalue conversion if 6462 /// not being used to initialize a reference. actOnLambdaInitCaptureInitialization(SourceLocation Loc,bool ByRef,SourceLocation EllipsisLoc,IdentifierInfo * Id,LambdaCaptureInitKind InitKind,Expr * & Init)6463 ParsedType actOnLambdaInitCaptureInitialization( 6464 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, 6465 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) { 6466 return ParsedType::make(buildLambdaInitCaptureInitialization( 6467 Loc, ByRef, EllipsisLoc, None, Id, 6468 InitKind != LambdaCaptureInitKind::CopyInit, Init)); 6469 } 6470 QualType buildLambdaInitCaptureInitialization( 6471 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, 6472 Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit, 6473 Expr *&Init); 6474 6475 /// Create a dummy variable within the declcontext of the lambda's 6476 /// call operator, for name lookup purposes for a lambda init capture. 6477 /// 6478 /// CodeGen handles emission of lambda captures, ignoring these dummy 6479 /// variables appropriately. 6480 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc, 6481 QualType InitCaptureType, 6482 SourceLocation EllipsisLoc, 6483 IdentifierInfo *Id, 6484 unsigned InitStyle, Expr *Init); 6485 6486 /// Add an init-capture to a lambda scope. 6487 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var); 6488 6489 /// Note that we have finished the explicit captures for the 6490 /// given lambda. 6491 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); 6492 6493 /// \brief This is called after parsing the explicit template parameter list 6494 /// on a lambda (if it exists) in C++2a. 6495 void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc, 6496 ArrayRef<NamedDecl *> TParams, 6497 SourceLocation RAngleLoc, 6498 ExprResult RequiresClause); 6499 6500 /// Introduce the lambda parameters into scope. 6501 void addLambdaParameters( 6502 ArrayRef<LambdaIntroducer::LambdaCapture> Captures, 6503 CXXMethodDecl *CallOperator, Scope *CurScope); 6504 6505 /// Deduce a block or lambda's return type based on the return 6506 /// statements present in the body. 6507 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); 6508 6509 /// ActOnStartOfLambdaDefinition - This is called just before we start 6510 /// parsing the body of a lambda; it analyzes the explicit captures and 6511 /// arguments, and sets up various data-structures for the body of the 6512 /// lambda. 6513 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, 6514 Declarator &ParamInfo, Scope *CurScope); 6515 6516 /// ActOnLambdaError - If there is an error parsing a lambda, this callback 6517 /// is invoked to pop the information about the lambda. 6518 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, 6519 bool IsInstantiation = false); 6520 6521 /// ActOnLambdaExpr - This is called when the body of a lambda expression 6522 /// was successfully completed. 6523 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, 6524 Scope *CurScope); 6525 6526 /// Does copying/destroying the captured variable have side effects? 6527 bool CaptureHasSideEffects(const sema::Capture &From); 6528 6529 /// Diagnose if an explicit lambda capture is unused. Returns true if a 6530 /// diagnostic is emitted. 6531 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, 6532 const sema::Capture &From); 6533 6534 /// Build a FieldDecl suitable to hold the given capture. 6535 FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture); 6536 6537 /// Initialize the given capture with a suitable expression. 6538 ExprResult BuildCaptureInit(const sema::Capture &Capture, 6539 SourceLocation ImplicitCaptureLoc, 6540 bool IsOpenMPMapping = false); 6541 6542 /// Complete a lambda-expression having processed and attached the 6543 /// lambda body. 6544 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, 6545 sema::LambdaScopeInfo *LSI); 6546 6547 /// Get the return type to use for a lambda's conversion function(s) to 6548 /// function pointer type, given the type of the call operator. 6549 QualType 6550 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType, 6551 CallingConv CC); 6552 6553 /// Define the "body" of the conversion from a lambda object to a 6554 /// function pointer. 6555 /// 6556 /// This routine doesn't actually define a sensible body; rather, it fills 6557 /// in the initialization expression needed to copy the lambda object into 6558 /// the block, and IR generation actually generates the real body of the 6559 /// block pointer conversion. 6560 void DefineImplicitLambdaToFunctionPointerConversion( 6561 SourceLocation CurrentLoc, CXXConversionDecl *Conv); 6562 6563 /// Define the "body" of the conversion from a lambda object to a 6564 /// block pointer. 6565 /// 6566 /// This routine doesn't actually define a sensible body; rather, it fills 6567 /// in the initialization expression needed to copy the lambda object into 6568 /// the block, and IR generation actually generates the real body of the 6569 /// block pointer conversion. 6570 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, 6571 CXXConversionDecl *Conv); 6572 6573 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, 6574 SourceLocation ConvLocation, 6575 CXXConversionDecl *Conv, 6576 Expr *Src); 6577 6578 /// Check whether the given expression is a valid constraint expression. 6579 /// A diagnostic is emitted if it is not, false is returned, and 6580 /// PossibleNonPrimary will be set to true if the failure might be due to a 6581 /// non-primary expression being used as an atomic constraint. 6582 bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(), 6583 bool *PossibleNonPrimary = nullptr, 6584 bool IsTrailingRequiresClause = false); 6585 6586 private: 6587 /// Caches pairs of template-like decls whose associated constraints were 6588 /// checked for subsumption and whether or not the first's constraints did in 6589 /// fact subsume the second's. 6590 llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache; 6591 /// Caches the normalized associated constraints of declarations (concepts or 6592 /// constrained declarations). If an error occurred while normalizing the 6593 /// associated constraints of the template or concept, nullptr will be cached 6594 /// here. 6595 llvm::DenseMap<NamedDecl *, NormalizedConstraint *> 6596 NormalizationCache; 6597 6598 llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &> 6599 SatisfactionCache; 6600 6601 public: 6602 const NormalizedConstraint * 6603 getNormalizedAssociatedConstraints( 6604 NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints); 6605 6606 /// \brief Check whether the given declaration's associated constraints are 6607 /// at least as constrained than another declaration's according to the 6608 /// partial ordering of constraints. 6609 /// 6610 /// \param Result If no error occurred, receives the result of true if D1 is 6611 /// at least constrained than D2, and false otherwise. 6612 /// 6613 /// \returns true if an error occurred, false otherwise. 6614 bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1, 6615 NamedDecl *D2, ArrayRef<const Expr *> AC2, 6616 bool &Result); 6617 6618 /// If D1 was not at least as constrained as D2, but would've been if a pair 6619 /// of atomic constraints involved had been declared in a concept and not 6620 /// repeated in two separate places in code. 6621 /// \returns true if such a diagnostic was emitted, false otherwise. 6622 bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1, 6623 ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2); 6624 6625 /// \brief Check whether the given list of constraint expressions are 6626 /// satisfied (as if in a 'conjunction') given template arguments. 6627 /// \param Template the template-like entity that triggered the constraints 6628 /// check (either a concept or a constrained entity). 6629 /// \param ConstraintExprs a list of constraint expressions, treated as if 6630 /// they were 'AND'ed together. 6631 /// \param TemplateArgs the list of template arguments to substitute into the 6632 /// constraint expression. 6633 /// \param TemplateIDRange The source range of the template id that 6634 /// caused the constraints check. 6635 /// \param Satisfaction if true is returned, will contain details of the 6636 /// satisfaction, with enough information to diagnose an unsatisfied 6637 /// expression. 6638 /// \returns true if an error occurred and satisfaction could not be checked, 6639 /// false otherwise. 6640 bool CheckConstraintSatisfaction( 6641 const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs, 6642 ArrayRef<TemplateArgument> TemplateArgs, 6643 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction); 6644 6645 /// \brief Check whether the given non-dependent constraint expression is 6646 /// satisfied. Returns false and updates Satisfaction with the satisfaction 6647 /// verdict if successful, emits a diagnostic and returns true if an error 6648 /// occured and satisfaction could not be determined. 6649 /// 6650 /// \returns true if an error occurred, false otherwise. 6651 bool CheckConstraintSatisfaction(const Expr *ConstraintExpr, 6652 ConstraintSatisfaction &Satisfaction); 6653 6654 /// Check whether the given function decl's trailing requires clause is 6655 /// satisfied, if any. Returns false and updates Satisfaction with the 6656 /// satisfaction verdict if successful, emits a diagnostic and returns true if 6657 /// an error occured and satisfaction could not be determined. 6658 /// 6659 /// \returns true if an error occurred, false otherwise. 6660 bool CheckFunctionConstraints(const FunctionDecl *FD, 6661 ConstraintSatisfaction &Satisfaction, 6662 SourceLocation UsageLoc = SourceLocation()); 6663 6664 6665 /// \brief Ensure that the given template arguments satisfy the constraints 6666 /// associated with the given template, emitting a diagnostic if they do not. 6667 /// 6668 /// \param Template The template to which the template arguments are being 6669 /// provided. 6670 /// 6671 /// \param TemplateArgs The converted, canonicalized template arguments. 6672 /// 6673 /// \param TemplateIDRange The source range of the template id that 6674 /// caused the constraints check. 6675 /// 6676 /// \returns true if the constrains are not satisfied or could not be checked 6677 /// for satisfaction, false if the constraints are satisfied. 6678 bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, 6679 ArrayRef<TemplateArgument> TemplateArgs, 6680 SourceRange TemplateIDRange); 6681 6682 /// \brief Emit diagnostics explaining why a constraint expression was deemed 6683 /// unsatisfied. 6684 /// \param First whether this is the first time an unsatisfied constraint is 6685 /// diagnosed for this error. 6686 void 6687 DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, 6688 bool First = true); 6689 6690 /// \brief Emit diagnostics explaining why a constraint expression was deemed 6691 /// unsatisfied. 6692 void 6693 DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction, 6694 bool First = true); 6695 6696 // ParseObjCStringLiteral - Parse Objective-C string literals. 6697 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, 6698 ArrayRef<Expr *> Strings); 6699 6700 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); 6701 6702 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the 6703 /// numeric literal expression. Type of the expression will be "NSNumber *" 6704 /// or "id" if NSNumber is unavailable. 6705 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); 6706 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, 6707 bool Value); 6708 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); 6709 6710 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the 6711 /// '@' prefixed parenthesized expression. The type of the expression will 6712 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type 6713 /// of ValueType, which is allowed to be a built-in numeric type, "char *", 6714 /// "const char *" or C structure with attribute 'objc_boxable'. 6715 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); 6716 6717 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, 6718 Expr *IndexExpr, 6719 ObjCMethodDecl *getterMethod, 6720 ObjCMethodDecl *setterMethod); 6721 6722 ExprResult BuildObjCDictionaryLiteral(SourceRange SR, 6723 MutableArrayRef<ObjCDictionaryElement> Elements); 6724 6725 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, 6726 TypeSourceInfo *EncodedTypeInfo, 6727 SourceLocation RParenLoc); 6728 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, 6729 CXXConversionDecl *Method, 6730 bool HadMultipleCandidates); 6731 6732 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, 6733 SourceLocation EncodeLoc, 6734 SourceLocation LParenLoc, 6735 ParsedType Ty, 6736 SourceLocation RParenLoc); 6737 6738 /// ParseObjCSelectorExpression - Build selector expression for \@selector 6739 ExprResult ParseObjCSelectorExpression(Selector Sel, 6740 SourceLocation AtLoc, 6741 SourceLocation SelLoc, 6742 SourceLocation LParenLoc, 6743 SourceLocation RParenLoc, 6744 bool WarnMultipleSelectors); 6745 6746 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol 6747 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, 6748 SourceLocation AtLoc, 6749 SourceLocation ProtoLoc, 6750 SourceLocation LParenLoc, 6751 SourceLocation ProtoIdLoc, 6752 SourceLocation RParenLoc); 6753 6754 //===--------------------------------------------------------------------===// 6755 // C++ Declarations 6756 // 6757 Decl *ActOnStartLinkageSpecification(Scope *S, 6758 SourceLocation ExternLoc, 6759 Expr *LangStr, 6760 SourceLocation LBraceLoc); 6761 Decl *ActOnFinishLinkageSpecification(Scope *S, 6762 Decl *LinkageSpec, 6763 SourceLocation RBraceLoc); 6764 6765 6766 //===--------------------------------------------------------------------===// 6767 // C++ Classes 6768 // 6769 CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS); 6770 bool isCurrentClassName(const IdentifierInfo &II, Scope *S, 6771 const CXXScopeSpec *SS = nullptr); 6772 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS); 6773 6774 bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 6775 SourceLocation ColonLoc, 6776 const ParsedAttributesView &Attrs); 6777 6778 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, 6779 Declarator &D, 6780 MultiTemplateParamsArg TemplateParameterLists, 6781 Expr *BitfieldWidth, const VirtSpecifiers &VS, 6782 InClassInitStyle InitStyle); 6783 6784 void ActOnStartCXXInClassMemberInitializer(); 6785 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, 6786 SourceLocation EqualLoc, 6787 Expr *Init); 6788 6789 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 6790 Scope *S, 6791 CXXScopeSpec &SS, 6792 IdentifierInfo *MemberOrBase, 6793 ParsedType TemplateTypeTy, 6794 const DeclSpec &DS, 6795 SourceLocation IdLoc, 6796 SourceLocation LParenLoc, 6797 ArrayRef<Expr *> Args, 6798 SourceLocation RParenLoc, 6799 SourceLocation EllipsisLoc); 6800 6801 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 6802 Scope *S, 6803 CXXScopeSpec &SS, 6804 IdentifierInfo *MemberOrBase, 6805 ParsedType TemplateTypeTy, 6806 const DeclSpec &DS, 6807 SourceLocation IdLoc, 6808 Expr *InitList, 6809 SourceLocation EllipsisLoc); 6810 6811 MemInitResult BuildMemInitializer(Decl *ConstructorD, 6812 Scope *S, 6813 CXXScopeSpec &SS, 6814 IdentifierInfo *MemberOrBase, 6815 ParsedType TemplateTypeTy, 6816 const DeclSpec &DS, 6817 SourceLocation IdLoc, 6818 Expr *Init, 6819 SourceLocation EllipsisLoc); 6820 6821 MemInitResult BuildMemberInitializer(ValueDecl *Member, 6822 Expr *Init, 6823 SourceLocation IdLoc); 6824 6825 MemInitResult BuildBaseInitializer(QualType BaseType, 6826 TypeSourceInfo *BaseTInfo, 6827 Expr *Init, 6828 CXXRecordDecl *ClassDecl, 6829 SourceLocation EllipsisLoc); 6830 6831 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, 6832 Expr *Init, 6833 CXXRecordDecl *ClassDecl); 6834 6835 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, 6836 CXXCtorInitializer *Initializer); 6837 6838 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 6839 ArrayRef<CXXCtorInitializer *> Initializers = None); 6840 6841 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); 6842 6843 6844 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, 6845 /// mark all the non-trivial destructors of its members and bases as 6846 /// referenced. 6847 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, 6848 CXXRecordDecl *Record); 6849 6850 /// Mark destructors of virtual bases of this class referenced. In the Itanium 6851 /// C++ ABI, this is done when emitting a destructor for any non-abstract 6852 /// class. In the Microsoft C++ ABI, this is done any time a class's 6853 /// destructor is referenced. 6854 void MarkVirtualBaseDestructorsReferenced( 6855 SourceLocation Location, CXXRecordDecl *ClassDecl, 6856 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr); 6857 6858 /// Do semantic checks to allow the complete destructor variant to be emitted 6859 /// when the destructor is defined in another translation unit. In the Itanium 6860 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they 6861 /// can be emitted in separate TUs. To emit the complete variant, run a subset 6862 /// of the checks performed when emitting a regular destructor. 6863 void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, 6864 CXXDestructorDecl *Dtor); 6865 6866 /// The list of classes whose vtables have been used within 6867 /// this translation unit, and the source locations at which the 6868 /// first use occurred. 6869 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; 6870 6871 /// The list of vtables that are required but have not yet been 6872 /// materialized. 6873 SmallVector<VTableUse, 16> VTableUses; 6874 6875 /// The set of classes whose vtables have been used within 6876 /// this translation unit, and a bit that will be true if the vtable is 6877 /// required to be emitted (otherwise, it should be emitted only if needed 6878 /// by code generation). 6879 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; 6880 6881 /// Load any externally-stored vtable uses. 6882 void LoadExternalVTableUses(); 6883 6884 /// Note that the vtable for the given class was used at the 6885 /// given location. 6886 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 6887 bool DefinitionRequired = false); 6888 6889 /// Mark the exception specifications of all virtual member functions 6890 /// in the given class as needed. 6891 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 6892 const CXXRecordDecl *RD); 6893 6894 /// MarkVirtualMembersReferenced - Will mark all members of the given 6895 /// CXXRecordDecl referenced. 6896 void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, 6897 bool ConstexprOnly = false); 6898 6899 /// Define all of the vtables that have been used in this 6900 /// translation unit and reference any virtual members used by those 6901 /// vtables. 6902 /// 6903 /// \returns true if any work was done, false otherwise. 6904 bool DefineUsedVTables(); 6905 6906 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); 6907 6908 void ActOnMemInitializers(Decl *ConstructorDecl, 6909 SourceLocation ColonLoc, 6910 ArrayRef<CXXCtorInitializer*> MemInits, 6911 bool AnyErrors); 6912 6913 /// Check class-level dllimport/dllexport attribute. The caller must 6914 /// ensure that referenceDLLExportedClassMethods is called some point later 6915 /// when all outer classes of Class are complete. 6916 void checkClassLevelDLLAttribute(CXXRecordDecl *Class); 6917 void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class); 6918 6919 void referenceDLLExportedClassMethods(); 6920 6921 void propagateDLLAttrToBaseClassTemplate( 6922 CXXRecordDecl *Class, Attr *ClassAttr, 6923 ClassTemplateSpecializationDecl *BaseTemplateSpec, 6924 SourceLocation BaseLoc); 6925 6926 /// Add gsl::Pointer attribute to std::container::iterator 6927 /// \param ND The declaration that introduces the name 6928 /// std::container::iterator. \param UnderlyingRecord The record named by ND. 6929 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord); 6930 6931 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types. 6932 void inferGslOwnerPointerAttribute(CXXRecordDecl *Record); 6933 6934 /// Add [[gsl::Pointer]] attributes for std:: types. 6935 void inferGslPointerAttribute(TypedefNameDecl *TD); 6936 6937 void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record); 6938 6939 /// Check that the C++ class annoated with "trivial_abi" satisfies all the 6940 /// conditions that are needed for the attribute to have an effect. 6941 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD); 6942 6943 void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, 6944 Decl *TagDecl, SourceLocation LBrac, 6945 SourceLocation RBrac, 6946 const ParsedAttributesView &AttrList); 6947 void ActOnFinishCXXMemberDecls(); 6948 void ActOnFinishCXXNonNestedClass(); 6949 6950 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param); 6951 unsigned ActOnReenterTemplateScope(Decl *Template, 6952 llvm::function_ref<Scope *()> EnterScope); 6953 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); 6954 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 6955 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); 6956 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); 6957 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 6958 void ActOnFinishDelayedMemberInitializers(Decl *Record); 6959 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, 6960 CachedTokens &Toks); 6961 void UnmarkAsLateParsedTemplate(FunctionDecl *FD); 6962 bool IsInsideALocalClassWithinATemplateFunction(); 6963 6964 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 6965 Expr *AssertExpr, 6966 Expr *AssertMessageExpr, 6967 SourceLocation RParenLoc); 6968 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 6969 Expr *AssertExpr, 6970 StringLiteral *AssertMessageExpr, 6971 SourceLocation RParenLoc, 6972 bool Failed); 6973 6974 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, 6975 SourceLocation FriendLoc, 6976 TypeSourceInfo *TSInfo); 6977 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 6978 MultiTemplateParamsArg TemplateParams); 6979 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, 6980 MultiTemplateParamsArg TemplateParams); 6981 6982 QualType CheckConstructorDeclarator(Declarator &D, QualType R, 6983 StorageClass& SC); 6984 void CheckConstructor(CXXConstructorDecl *Constructor); 6985 QualType CheckDestructorDeclarator(Declarator &D, QualType R, 6986 StorageClass& SC); 6987 bool CheckDestructor(CXXDestructorDecl *Destructor); 6988 void CheckConversionDeclarator(Declarator &D, QualType &R, 6989 StorageClass& SC); 6990 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); 6991 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 6992 StorageClass &SC); 6993 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD); 6994 6995 void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD); 6996 6997 bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 6998 CXXSpecialMember CSM); 6999 void CheckDelayedMemberExceptionSpecs(); 7000 7001 bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, 7002 DefaultedComparisonKind DCK); 7003 void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 7004 FunctionDecl *Spaceship); 7005 void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, 7006 DefaultedComparisonKind DCK); 7007 7008 //===--------------------------------------------------------------------===// 7009 // C++ Derived Classes 7010 // 7011 7012 /// ActOnBaseSpecifier - Parsed a base specifier 7013 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, 7014 SourceRange SpecifierRange, 7015 bool Virtual, AccessSpecifier Access, 7016 TypeSourceInfo *TInfo, 7017 SourceLocation EllipsisLoc); 7018 7019 BaseResult ActOnBaseSpecifier(Decl *classdecl, 7020 SourceRange SpecifierRange, 7021 ParsedAttributes &Attrs, 7022 bool Virtual, AccessSpecifier Access, 7023 ParsedType basetype, 7024 SourceLocation BaseLoc, 7025 SourceLocation EllipsisLoc); 7026 7027 bool AttachBaseSpecifiers(CXXRecordDecl *Class, 7028 MutableArrayRef<CXXBaseSpecifier *> Bases); 7029 void ActOnBaseSpecifiers(Decl *ClassDecl, 7030 MutableArrayRef<CXXBaseSpecifier *> Bases); 7031 7032 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base); 7033 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 7034 CXXBasePaths &Paths); 7035 7036 // FIXME: I don't like this name. 7037 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); 7038 7039 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 7040 SourceLocation Loc, SourceRange Range, 7041 CXXCastPath *BasePath = nullptr, 7042 bool IgnoreAccess = false); 7043 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 7044 unsigned InaccessibleBaseID, 7045 unsigned AmbiguousBaseConvID, 7046 SourceLocation Loc, SourceRange Range, 7047 DeclarationName Name, 7048 CXXCastPath *BasePath, 7049 bool IgnoreAccess = false); 7050 7051 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); 7052 7053 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 7054 const CXXMethodDecl *Old); 7055 7056 /// CheckOverridingFunctionReturnType - Checks whether the return types are 7057 /// covariant, according to C++ [class.virtual]p5. 7058 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 7059 const CXXMethodDecl *Old); 7060 7061 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception 7062 /// spec is a subset of base spec. 7063 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, 7064 const CXXMethodDecl *Old); 7065 7066 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); 7067 7068 /// CheckOverrideControl - Check C++11 override control semantics. 7069 void CheckOverrideControl(NamedDecl *D); 7070 7071 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was 7072 /// not used in the declaration of an overriding method. 7073 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent); 7074 7075 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function 7076 /// overrides a virtual member function marked 'final', according to 7077 /// C++11 [class.virtual]p4. 7078 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 7079 const CXXMethodDecl *Old); 7080 7081 7082 //===--------------------------------------------------------------------===// 7083 // C++ Access Control 7084 // 7085 7086 enum AccessResult { 7087 AR_accessible, 7088 AR_inaccessible, 7089 AR_dependent, 7090 AR_delayed 7091 }; 7092 7093 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, 7094 NamedDecl *PrevMemberDecl, 7095 AccessSpecifier LexicalAS); 7096 7097 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, 7098 DeclAccessPair FoundDecl); 7099 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, 7100 DeclAccessPair FoundDecl); 7101 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, 7102 SourceRange PlacementRange, 7103 CXXRecordDecl *NamingClass, 7104 DeclAccessPair FoundDecl, 7105 bool Diagnose = true); 7106 AccessResult CheckConstructorAccess(SourceLocation Loc, 7107 CXXConstructorDecl *D, 7108 DeclAccessPair FoundDecl, 7109 const InitializedEntity &Entity, 7110 bool IsCopyBindingRefToTemp = false); 7111 AccessResult CheckConstructorAccess(SourceLocation Loc, 7112 CXXConstructorDecl *D, 7113 DeclAccessPair FoundDecl, 7114 const InitializedEntity &Entity, 7115 const PartialDiagnostic &PDiag); 7116 AccessResult CheckDestructorAccess(SourceLocation Loc, 7117 CXXDestructorDecl *Dtor, 7118 const PartialDiagnostic &PDiag, 7119 QualType objectType = QualType()); 7120 AccessResult CheckFriendAccess(NamedDecl *D); 7121 AccessResult CheckMemberAccess(SourceLocation UseLoc, 7122 CXXRecordDecl *NamingClass, 7123 DeclAccessPair Found); 7124 AccessResult 7125 CheckStructuredBindingMemberAccess(SourceLocation UseLoc, 7126 CXXRecordDecl *DecomposedClass, 7127 DeclAccessPair Field); 7128 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, 7129 Expr *ObjectExpr, 7130 Expr *ArgExpr, 7131 DeclAccessPair FoundDecl); 7132 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, 7133 DeclAccessPair FoundDecl); 7134 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, 7135 QualType Base, QualType Derived, 7136 const CXXBasePath &Path, 7137 unsigned DiagID, 7138 bool ForceCheck = false, 7139 bool ForceUnprivileged = false); 7140 void CheckLookupAccess(const LookupResult &R); 7141 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass, 7142 QualType BaseType); 7143 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, 7144 DeclAccessPair Found, QualType ObjectType, 7145 SourceLocation Loc, 7146 const PartialDiagnostic &Diag); isMemberAccessibleForDeletion(CXXRecordDecl * NamingClass,DeclAccessPair Found,QualType ObjectType)7147 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, 7148 DeclAccessPair Found, 7149 QualType ObjectType) { 7150 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType, 7151 SourceLocation(), PDiag()); 7152 } 7153 7154 void HandleDependentAccessCheck(const DependentDiagnostic &DD, 7155 const MultiLevelTemplateArgumentList &TemplateArgs); 7156 void PerformDependentDiagnostics(const DeclContext *Pattern, 7157 const MultiLevelTemplateArgumentList &TemplateArgs); 7158 7159 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 7160 7161 /// When true, access checking violations are treated as SFINAE 7162 /// failures rather than hard errors. 7163 bool AccessCheckingSFINAE; 7164 7165 enum AbstractDiagSelID { 7166 AbstractNone = -1, 7167 AbstractReturnType, 7168 AbstractParamType, 7169 AbstractVariableType, 7170 AbstractFieldType, 7171 AbstractIvarType, 7172 AbstractSynthesizedIvarType, 7173 AbstractArrayType 7174 }; 7175 7176 bool isAbstractType(SourceLocation Loc, QualType T); 7177 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 7178 TypeDiagnoser &Diagnoser); 7179 template <typename... Ts> RequireNonAbstractType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)7180 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, 7181 const Ts &...Args) { 7182 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 7183 return RequireNonAbstractType(Loc, T, Diagnoser); 7184 } 7185 7186 void DiagnoseAbstractType(const CXXRecordDecl *RD); 7187 7188 //===--------------------------------------------------------------------===// 7189 // C++ Overloaded Operators [C++ 13.5] 7190 // 7191 7192 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); 7193 7194 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); 7195 7196 //===--------------------------------------------------------------------===// 7197 // C++ Templates [C++ 14] 7198 // 7199 void FilterAcceptableTemplateNames(LookupResult &R, 7200 bool AllowFunctionTemplates = true, 7201 bool AllowDependent = true); 7202 bool hasAnyAcceptableTemplateNames(LookupResult &R, 7203 bool AllowFunctionTemplates = true, 7204 bool AllowDependent = true, 7205 bool AllowNonTemplateFunctions = false); 7206 /// Try to interpret the lookup result D as a template-name. 7207 /// 7208 /// \param D A declaration found by name lookup. 7209 /// \param AllowFunctionTemplates Whether function templates should be 7210 /// considered valid results. 7211 /// \param AllowDependent Whether unresolved using declarations (that might 7212 /// name templates) should be considered valid results. 7213 static NamedDecl *getAsTemplateNameDecl(NamedDecl *D, 7214 bool AllowFunctionTemplates = true, 7215 bool AllowDependent = true); 7216 7217 enum TemplateNameIsRequiredTag { TemplateNameIsRequired }; 7218 /// Whether and why a template name is required in this lookup. 7219 class RequiredTemplateKind { 7220 public: 7221 /// Template name is required if TemplateKWLoc is valid. 7222 RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation()) TemplateKW(TemplateKWLoc)7223 : TemplateKW(TemplateKWLoc) {} 7224 /// Template name is unconditionally required. RequiredTemplateKind(TemplateNameIsRequiredTag)7225 RequiredTemplateKind(TemplateNameIsRequiredTag) : TemplateKW() {} 7226 getTemplateKeywordLoc()7227 SourceLocation getTemplateKeywordLoc() const { 7228 return TemplateKW.getValueOr(SourceLocation()); 7229 } hasTemplateKeyword()7230 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } isRequired()7231 bool isRequired() const { return TemplateKW != SourceLocation(); } 7232 explicit operator bool() const { return isRequired(); } 7233 7234 private: 7235 llvm::Optional<SourceLocation> TemplateKW; 7236 }; 7237 7238 enum class AssumedTemplateKind { 7239 /// This is not assumed to be a template name. 7240 None, 7241 /// This is assumed to be a template name because lookup found nothing. 7242 FoundNothing, 7243 /// This is assumed to be a template name because lookup found one or more 7244 /// functions (but no function templates). 7245 FoundFunctions, 7246 }; 7247 bool LookupTemplateName( 7248 LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, 7249 bool EnteringContext, bool &MemberOfUnknownSpecialization, 7250 RequiredTemplateKind RequiredTemplate = SourceLocation(), 7251 AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true); 7252 7253 TemplateNameKind isTemplateName(Scope *S, 7254 CXXScopeSpec &SS, 7255 bool hasTemplateKeyword, 7256 const UnqualifiedId &Name, 7257 ParsedType ObjectType, 7258 bool EnteringContext, 7259 TemplateTy &Template, 7260 bool &MemberOfUnknownSpecialization, 7261 bool Disambiguation = false); 7262 7263 /// Try to resolve an undeclared template name as a type template. 7264 /// 7265 /// Sets II to the identifier corresponding to the template name, and updates 7266 /// Name to a corresponding (typo-corrected) type template name and TNK to 7267 /// the corresponding kind, if possible. 7268 void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, 7269 TemplateNameKind &TNK, 7270 SourceLocation NameLoc, 7271 IdentifierInfo *&II); 7272 7273 bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, 7274 SourceLocation NameLoc, 7275 bool Diagnose = true); 7276 7277 /// Determine whether a particular identifier might be the name in a C++1z 7278 /// deduction-guide declaration. 7279 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, 7280 SourceLocation NameLoc, 7281 ParsedTemplateTy *Template = nullptr); 7282 7283 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, 7284 SourceLocation IILoc, 7285 Scope *S, 7286 const CXXScopeSpec *SS, 7287 TemplateTy &SuggestedTemplate, 7288 TemplateNameKind &SuggestedKind); 7289 7290 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, 7291 NamedDecl *Instantiation, 7292 bool InstantiatedFromMember, 7293 const NamedDecl *Pattern, 7294 const NamedDecl *PatternDef, 7295 TemplateSpecializationKind TSK, 7296 bool Complain = true); 7297 7298 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); 7299 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); 7300 7301 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename, 7302 SourceLocation EllipsisLoc, 7303 SourceLocation KeyLoc, 7304 IdentifierInfo *ParamName, 7305 SourceLocation ParamNameLoc, 7306 unsigned Depth, unsigned Position, 7307 SourceLocation EqualLoc, 7308 ParsedType DefaultArg, bool HasTypeConstraint); 7309 7310 bool ActOnTypeConstraint(const CXXScopeSpec &SS, 7311 TemplateIdAnnotation *TypeConstraint, 7312 TemplateTypeParmDecl *ConstrainedParameter, 7313 SourceLocation EllipsisLoc); 7314 7315 bool AttachTypeConstraint(NestedNameSpecifierLoc NS, 7316 DeclarationNameInfo NameInfo, 7317 ConceptDecl *NamedConcept, 7318 const TemplateArgumentListInfo *TemplateArgs, 7319 TemplateTypeParmDecl *ConstrainedParameter, 7320 SourceLocation EllipsisLoc); 7321 7322 bool AttachTypeConstraint(AutoTypeLoc TL, 7323 NonTypeTemplateParmDecl *ConstrainedParameter, 7324 SourceLocation EllipsisLoc); 7325 7326 bool RequireStructuralType(QualType T, SourceLocation Loc); 7327 7328 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, 7329 SourceLocation Loc); 7330 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); 7331 7332 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 7333 unsigned Depth, 7334 unsigned Position, 7335 SourceLocation EqualLoc, 7336 Expr *DefaultArg); 7337 NamedDecl *ActOnTemplateTemplateParameter(Scope *S, 7338 SourceLocation TmpLoc, 7339 TemplateParameterList *Params, 7340 SourceLocation EllipsisLoc, 7341 IdentifierInfo *ParamName, 7342 SourceLocation ParamNameLoc, 7343 unsigned Depth, 7344 unsigned Position, 7345 SourceLocation EqualLoc, 7346 ParsedTemplateArgument DefaultArg); 7347 7348 TemplateParameterList * 7349 ActOnTemplateParameterList(unsigned Depth, 7350 SourceLocation ExportLoc, 7351 SourceLocation TemplateLoc, 7352 SourceLocation LAngleLoc, 7353 ArrayRef<NamedDecl *> Params, 7354 SourceLocation RAngleLoc, 7355 Expr *RequiresClause); 7356 7357 /// The context in which we are checking a template parameter list. 7358 enum TemplateParamListContext { 7359 TPC_ClassTemplate, 7360 TPC_VarTemplate, 7361 TPC_FunctionTemplate, 7362 TPC_ClassTemplateMember, 7363 TPC_FriendClassTemplate, 7364 TPC_FriendFunctionTemplate, 7365 TPC_FriendFunctionTemplateDefinition, 7366 TPC_TypeAliasTemplate 7367 }; 7368 7369 bool CheckTemplateParameterList(TemplateParameterList *NewParams, 7370 TemplateParameterList *OldParams, 7371 TemplateParamListContext TPC, 7372 SkipBodyInfo *SkipBody = nullptr); 7373 TemplateParameterList *MatchTemplateParametersToScopeSpecifier( 7374 SourceLocation DeclStartLoc, SourceLocation DeclLoc, 7375 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, 7376 ArrayRef<TemplateParameterList *> ParamLists, 7377 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, 7378 bool SuppressDiagnostic = false); 7379 7380 DeclResult CheckClassTemplate( 7381 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, 7382 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, 7383 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, 7384 AccessSpecifier AS, SourceLocation ModulePrivateLoc, 7385 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, 7386 TemplateParameterList **OuterTemplateParamLists, 7387 SkipBodyInfo *SkipBody = nullptr); 7388 7389 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, 7390 QualType NTTPType, 7391 SourceLocation Loc); 7392 7393 /// Get a template argument mapping the given template parameter to itself, 7394 /// e.g. for X in \c template<int X>, this would return an expression template 7395 /// argument referencing X. 7396 TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param, 7397 SourceLocation Location); 7398 7399 void translateTemplateArguments(const ASTTemplateArgsPtr &In, 7400 TemplateArgumentListInfo &Out); 7401 7402 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType); 7403 7404 void NoteAllFoundTemplates(TemplateName Name); 7405 7406 QualType CheckTemplateIdType(TemplateName Template, 7407 SourceLocation TemplateLoc, 7408 TemplateArgumentListInfo &TemplateArgs); 7409 7410 TypeResult 7411 ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 7412 TemplateTy Template, IdentifierInfo *TemplateII, 7413 SourceLocation TemplateIILoc, SourceLocation LAngleLoc, 7414 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, 7415 bool IsCtorOrDtorName = false, bool IsClassName = false); 7416 7417 /// Parsed an elaborated-type-specifier that refers to a template-id, 7418 /// such as \c class T::template apply<U>. 7419 TypeResult ActOnTagTemplateIdType(TagUseKind TUK, 7420 TypeSpecifierType TagSpec, 7421 SourceLocation TagLoc, 7422 CXXScopeSpec &SS, 7423 SourceLocation TemplateKWLoc, 7424 TemplateTy TemplateD, 7425 SourceLocation TemplateLoc, 7426 SourceLocation LAngleLoc, 7427 ASTTemplateArgsPtr TemplateArgsIn, 7428 SourceLocation RAngleLoc); 7429 7430 DeclResult ActOnVarTemplateSpecialization( 7431 Scope *S, Declarator &D, TypeSourceInfo *DI, 7432 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, 7433 StorageClass SC, bool IsPartialSpecialization); 7434 7435 /// Get the specialization of the given variable template corresponding to 7436 /// the specified argument list, or a null-but-valid result if the arguments 7437 /// are dependent. 7438 DeclResult CheckVarTemplateId(VarTemplateDecl *Template, 7439 SourceLocation TemplateLoc, 7440 SourceLocation TemplateNameLoc, 7441 const TemplateArgumentListInfo &TemplateArgs); 7442 7443 /// Form a reference to the specialization of the given variable template 7444 /// corresponding to the specified argument list, or a null-but-valid result 7445 /// if the arguments are dependent. 7446 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, 7447 const DeclarationNameInfo &NameInfo, 7448 VarTemplateDecl *Template, 7449 SourceLocation TemplateLoc, 7450 const TemplateArgumentListInfo *TemplateArgs); 7451 7452 ExprResult 7453 CheckConceptTemplateId(const CXXScopeSpec &SS, 7454 SourceLocation TemplateKWLoc, 7455 const DeclarationNameInfo &ConceptNameInfo, 7456 NamedDecl *FoundDecl, ConceptDecl *NamedConcept, 7457 const TemplateArgumentListInfo *TemplateArgs); 7458 7459 void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc); 7460 7461 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, 7462 SourceLocation TemplateKWLoc, 7463 LookupResult &R, 7464 bool RequiresADL, 7465 const TemplateArgumentListInfo *TemplateArgs); 7466 7467 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, 7468 SourceLocation TemplateKWLoc, 7469 const DeclarationNameInfo &NameInfo, 7470 const TemplateArgumentListInfo *TemplateArgs); 7471 7472 TemplateNameKind ActOnTemplateName( 7473 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 7474 const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, 7475 TemplateTy &Template, bool AllowInjectedClassName = false); 7476 7477 DeclResult ActOnClassTemplateSpecialization( 7478 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, 7479 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, 7480 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, 7481 MultiTemplateParamsArg TemplateParameterLists, 7482 SkipBodyInfo *SkipBody = nullptr); 7483 7484 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, 7485 TemplateDecl *PrimaryTemplate, 7486 unsigned NumExplicitArgs, 7487 ArrayRef<TemplateArgument> Args); 7488 void CheckTemplatePartialSpecialization( 7489 ClassTemplatePartialSpecializationDecl *Partial); 7490 void CheckTemplatePartialSpecialization( 7491 VarTemplatePartialSpecializationDecl *Partial); 7492 7493 Decl *ActOnTemplateDeclarator(Scope *S, 7494 MultiTemplateParamsArg TemplateParameterLists, 7495 Declarator &D); 7496 7497 bool 7498 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, 7499 TemplateSpecializationKind NewTSK, 7500 NamedDecl *PrevDecl, 7501 TemplateSpecializationKind PrevTSK, 7502 SourceLocation PrevPtOfInstantiation, 7503 bool &SuppressNew); 7504 7505 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, 7506 const TemplateArgumentListInfo &ExplicitTemplateArgs, 7507 LookupResult &Previous); 7508 7509 bool CheckFunctionTemplateSpecialization( 7510 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, 7511 LookupResult &Previous, bool QualifiedFriend = false); 7512 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); 7513 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous); 7514 7515 DeclResult ActOnExplicitInstantiation( 7516 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, 7517 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, 7518 TemplateTy Template, SourceLocation TemplateNameLoc, 7519 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, 7520 SourceLocation RAngleLoc, const ParsedAttributesView &Attr); 7521 7522 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, 7523 SourceLocation TemplateLoc, 7524 unsigned TagSpec, SourceLocation KWLoc, 7525 CXXScopeSpec &SS, IdentifierInfo *Name, 7526 SourceLocation NameLoc, 7527 const ParsedAttributesView &Attr); 7528 7529 DeclResult ActOnExplicitInstantiation(Scope *S, 7530 SourceLocation ExternLoc, 7531 SourceLocation TemplateLoc, 7532 Declarator &D); 7533 7534 TemplateArgumentLoc 7535 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, 7536 SourceLocation TemplateLoc, 7537 SourceLocation RAngleLoc, 7538 Decl *Param, 7539 SmallVectorImpl<TemplateArgument> 7540 &Converted, 7541 bool &HasDefaultArg); 7542 7543 /// Specifies the context in which a particular template 7544 /// argument is being checked. 7545 enum CheckTemplateArgumentKind { 7546 /// The template argument was specified in the code or was 7547 /// instantiated with some deduced template arguments. 7548 CTAK_Specified, 7549 7550 /// The template argument was deduced via template argument 7551 /// deduction. 7552 CTAK_Deduced, 7553 7554 /// The template argument was deduced from an array bound 7555 /// via template argument deduction. 7556 CTAK_DeducedFromArrayBound 7557 }; 7558 7559 bool CheckTemplateArgument(NamedDecl *Param, 7560 TemplateArgumentLoc &Arg, 7561 NamedDecl *Template, 7562 SourceLocation TemplateLoc, 7563 SourceLocation RAngleLoc, 7564 unsigned ArgumentPackIndex, 7565 SmallVectorImpl<TemplateArgument> &Converted, 7566 CheckTemplateArgumentKind CTAK = CTAK_Specified); 7567 7568 /// Check that the given template arguments can be be provided to 7569 /// the given template, converting the arguments along the way. 7570 /// 7571 /// \param Template The template to which the template arguments are being 7572 /// provided. 7573 /// 7574 /// \param TemplateLoc The location of the template name in the source. 7575 /// 7576 /// \param TemplateArgs The list of template arguments. If the template is 7577 /// a template template parameter, this function may extend the set of 7578 /// template arguments to also include substituted, defaulted template 7579 /// arguments. 7580 /// 7581 /// \param PartialTemplateArgs True if the list of template arguments is 7582 /// intentionally partial, e.g., because we're checking just the initial 7583 /// set of template arguments. 7584 /// 7585 /// \param Converted Will receive the converted, canonicalized template 7586 /// arguments. 7587 /// 7588 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to 7589 /// contain the converted forms of the template arguments as written. 7590 /// Otherwise, \p TemplateArgs will not be modified. 7591 /// 7592 /// \param ConstraintsNotSatisfied If provided, and an error occured, will 7593 /// receive true if the cause for the error is the associated constraints of 7594 /// the template not being satisfied by the template arguments. 7595 /// 7596 /// \returns true if an error occurred, false otherwise. 7597 bool CheckTemplateArgumentList(TemplateDecl *Template, 7598 SourceLocation TemplateLoc, 7599 TemplateArgumentListInfo &TemplateArgs, 7600 bool PartialTemplateArgs, 7601 SmallVectorImpl<TemplateArgument> &Converted, 7602 bool UpdateArgsWithConversions = true, 7603 bool *ConstraintsNotSatisfied = nullptr); 7604 7605 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, 7606 TemplateArgumentLoc &Arg, 7607 SmallVectorImpl<TemplateArgument> &Converted); 7608 7609 bool CheckTemplateArgument(TemplateTypeParmDecl *Param, 7610 TypeSourceInfo *Arg); 7611 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 7612 QualType InstantiatedParamType, Expr *Arg, 7613 TemplateArgument &Converted, 7614 CheckTemplateArgumentKind CTAK = CTAK_Specified); 7615 bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, 7616 TemplateParameterList *Params, 7617 TemplateArgumentLoc &Arg); 7618 7619 ExprResult 7620 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, 7621 QualType ParamType, 7622 SourceLocation Loc); 7623 ExprResult 7624 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, 7625 SourceLocation Loc); 7626 7627 /// Enumeration describing how template parameter lists are compared 7628 /// for equality. 7629 enum TemplateParameterListEqualKind { 7630 /// We are matching the template parameter lists of two templates 7631 /// that might be redeclarations. 7632 /// 7633 /// \code 7634 /// template<typename T> struct X; 7635 /// template<typename T> struct X; 7636 /// \endcode 7637 TPL_TemplateMatch, 7638 7639 /// We are matching the template parameter lists of two template 7640 /// template parameters as part of matching the template parameter lists 7641 /// of two templates that might be redeclarations. 7642 /// 7643 /// \code 7644 /// template<template<int I> class TT> struct X; 7645 /// template<template<int Value> class Other> struct X; 7646 /// \endcode 7647 TPL_TemplateTemplateParmMatch, 7648 7649 /// We are matching the template parameter lists of a template 7650 /// template argument against the template parameter lists of a template 7651 /// template parameter. 7652 /// 7653 /// \code 7654 /// template<template<int Value> class Metafun> struct X; 7655 /// template<int Value> struct integer_c; 7656 /// X<integer_c> xic; 7657 /// \endcode 7658 TPL_TemplateTemplateArgumentMatch 7659 }; 7660 7661 bool TemplateParameterListsAreEqual(TemplateParameterList *New, 7662 TemplateParameterList *Old, 7663 bool Complain, 7664 TemplateParameterListEqualKind Kind, 7665 SourceLocation TemplateArgLoc 7666 = SourceLocation()); 7667 7668 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); 7669 7670 /// Called when the parser has parsed a C++ typename 7671 /// specifier, e.g., "typename T::type". 7672 /// 7673 /// \param S The scope in which this typename type occurs. 7674 /// \param TypenameLoc the location of the 'typename' keyword 7675 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 7676 /// \param II the identifier we're retrieving (e.g., 'type' in the example). 7677 /// \param IdLoc the location of the identifier. 7678 TypeResult 7679 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 7680 const CXXScopeSpec &SS, const IdentifierInfo &II, 7681 SourceLocation IdLoc); 7682 7683 /// Called when the parser has parsed a C++ typename 7684 /// specifier that ends in a template-id, e.g., 7685 /// "typename MetaFun::template apply<T1, T2>". 7686 /// 7687 /// \param S The scope in which this typename type occurs. 7688 /// \param TypenameLoc the location of the 'typename' keyword 7689 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 7690 /// \param TemplateLoc the location of the 'template' keyword, if any. 7691 /// \param TemplateName The template name. 7692 /// \param TemplateII The identifier used to name the template. 7693 /// \param TemplateIILoc The location of the template name. 7694 /// \param LAngleLoc The location of the opening angle bracket ('<'). 7695 /// \param TemplateArgs The template arguments. 7696 /// \param RAngleLoc The location of the closing angle bracket ('>'). 7697 TypeResult 7698 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 7699 const CXXScopeSpec &SS, 7700 SourceLocation TemplateLoc, 7701 TemplateTy TemplateName, 7702 IdentifierInfo *TemplateII, 7703 SourceLocation TemplateIILoc, 7704 SourceLocation LAngleLoc, 7705 ASTTemplateArgsPtr TemplateArgs, 7706 SourceLocation RAngleLoc); 7707 7708 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, 7709 SourceLocation KeywordLoc, 7710 NestedNameSpecifierLoc QualifierLoc, 7711 const IdentifierInfo &II, 7712 SourceLocation IILoc, 7713 TypeSourceInfo **TSI, 7714 bool DeducedTSTContext); 7715 7716 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, 7717 SourceLocation KeywordLoc, 7718 NestedNameSpecifierLoc QualifierLoc, 7719 const IdentifierInfo &II, 7720 SourceLocation IILoc, 7721 bool DeducedTSTContext = true); 7722 7723 7724 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, 7725 SourceLocation Loc, 7726 DeclarationName Name); 7727 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); 7728 7729 ExprResult RebuildExprInCurrentInstantiation(Expr *E); 7730 bool RebuildTemplateParamsInCurrentInstantiation( 7731 TemplateParameterList *Params); 7732 7733 std::string 7734 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 7735 const TemplateArgumentList &Args); 7736 7737 std::string 7738 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 7739 const TemplateArgument *Args, 7740 unsigned NumArgs); 7741 7742 //===--------------------------------------------------------------------===// 7743 // C++ Concepts 7744 //===--------------------------------------------------------------------===// 7745 Decl *ActOnConceptDefinition( 7746 Scope *S, MultiTemplateParamsArg TemplateParameterLists, 7747 IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr); 7748 7749 RequiresExprBodyDecl * 7750 ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, 7751 ArrayRef<ParmVarDecl *> LocalParameters, 7752 Scope *BodyScope); 7753 void ActOnFinishRequiresExpr(); 7754 concepts::Requirement *ActOnSimpleRequirement(Expr *E); 7755 concepts::Requirement *ActOnTypeRequirement( 7756 SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc, 7757 IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId); 7758 concepts::Requirement *ActOnCompoundRequirement(Expr *E, 7759 SourceLocation NoexceptLoc); 7760 concepts::Requirement * 7761 ActOnCompoundRequirement( 7762 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS, 7763 TemplateIdAnnotation *TypeConstraint, unsigned Depth); 7764 concepts::Requirement *ActOnNestedRequirement(Expr *Constraint); 7765 concepts::ExprRequirement * 7766 BuildExprRequirement( 7767 Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc, 7768 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); 7769 concepts::ExprRequirement * 7770 BuildExprRequirement( 7771 concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag, 7772 bool IsSatisfied, SourceLocation NoexceptLoc, 7773 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); 7774 concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type); 7775 concepts::TypeRequirement * 7776 BuildTypeRequirement( 7777 concepts::Requirement::SubstitutionDiagnostic *SubstDiag); 7778 concepts::NestedRequirement *BuildNestedRequirement(Expr *E); 7779 concepts::NestedRequirement * 7780 BuildNestedRequirement( 7781 concepts::Requirement::SubstitutionDiagnostic *SubstDiag); 7782 ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc, 7783 RequiresExprBodyDecl *Body, 7784 ArrayRef<ParmVarDecl *> LocalParameters, 7785 ArrayRef<concepts::Requirement *> Requirements, 7786 SourceLocation ClosingBraceLoc); 7787 7788 //===--------------------------------------------------------------------===// 7789 // C++ Variadic Templates (C++0x [temp.variadic]) 7790 //===--------------------------------------------------------------------===// 7791 7792 /// Determine whether an unexpanded parameter pack might be permitted in this 7793 /// location. Useful for error recovery. 7794 bool isUnexpandedParameterPackPermitted(); 7795 7796 /// The context in which an unexpanded parameter pack is 7797 /// being diagnosed. 7798 /// 7799 /// Note that the values of this enumeration line up with the first 7800 /// argument to the \c err_unexpanded_parameter_pack diagnostic. 7801 enum UnexpandedParameterPackContext { 7802 /// An arbitrary expression. 7803 UPPC_Expression = 0, 7804 7805 /// The base type of a class type. 7806 UPPC_BaseType, 7807 7808 /// The type of an arbitrary declaration. 7809 UPPC_DeclarationType, 7810 7811 /// The type of a data member. 7812 UPPC_DataMemberType, 7813 7814 /// The size of a bit-field. 7815 UPPC_BitFieldWidth, 7816 7817 /// The expression in a static assertion. 7818 UPPC_StaticAssertExpression, 7819 7820 /// The fixed underlying type of an enumeration. 7821 UPPC_FixedUnderlyingType, 7822 7823 /// The enumerator value. 7824 UPPC_EnumeratorValue, 7825 7826 /// A using declaration. 7827 UPPC_UsingDeclaration, 7828 7829 /// A friend declaration. 7830 UPPC_FriendDeclaration, 7831 7832 /// A declaration qualifier. 7833 UPPC_DeclarationQualifier, 7834 7835 /// An initializer. 7836 UPPC_Initializer, 7837 7838 /// A default argument. 7839 UPPC_DefaultArgument, 7840 7841 /// The type of a non-type template parameter. 7842 UPPC_NonTypeTemplateParameterType, 7843 7844 /// The type of an exception. 7845 UPPC_ExceptionType, 7846 7847 /// Partial specialization. 7848 UPPC_PartialSpecialization, 7849 7850 /// Microsoft __if_exists. 7851 UPPC_IfExists, 7852 7853 /// Microsoft __if_not_exists. 7854 UPPC_IfNotExists, 7855 7856 /// Lambda expression. 7857 UPPC_Lambda, 7858 7859 /// Block expression. 7860 UPPC_Block, 7861 7862 /// A type constraint. 7863 UPPC_TypeConstraint, 7864 7865 // A requirement in a requires-expression. 7866 UPPC_Requirement, 7867 7868 // A requires-clause. 7869 UPPC_RequiresClause, 7870 }; 7871 7872 /// Diagnose unexpanded parameter packs. 7873 /// 7874 /// \param Loc The location at which we should emit the diagnostic. 7875 /// 7876 /// \param UPPC The context in which we are diagnosing unexpanded 7877 /// parameter packs. 7878 /// 7879 /// \param Unexpanded the set of unexpanded parameter packs. 7880 /// 7881 /// \returns true if an error occurred, false otherwise. 7882 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, 7883 UnexpandedParameterPackContext UPPC, 7884 ArrayRef<UnexpandedParameterPack> Unexpanded); 7885 7886 /// If the given type contains an unexpanded parameter pack, 7887 /// diagnose the error. 7888 /// 7889 /// \param Loc The source location where a diagnostc should be emitted. 7890 /// 7891 /// \param T The type that is being checked for unexpanded parameter 7892 /// packs. 7893 /// 7894 /// \returns true if an error occurred, false otherwise. 7895 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, 7896 UnexpandedParameterPackContext UPPC); 7897 7898 /// If the given expression contains an unexpanded parameter 7899 /// pack, diagnose the error. 7900 /// 7901 /// \param E The expression that is being checked for unexpanded 7902 /// parameter packs. 7903 /// 7904 /// \returns true if an error occurred, false otherwise. 7905 bool DiagnoseUnexpandedParameterPack(Expr *E, 7906 UnexpandedParameterPackContext UPPC = UPPC_Expression); 7907 7908 /// If the given requirees-expression contains an unexpanded reference to one 7909 /// of its own parameter packs, diagnose the error. 7910 /// 7911 /// \param RE The requiress-expression that is being checked for unexpanded 7912 /// parameter packs. 7913 /// 7914 /// \returns true if an error occurred, false otherwise. 7915 bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE); 7916 7917 /// If the given nested-name-specifier contains an unexpanded 7918 /// parameter pack, diagnose the error. 7919 /// 7920 /// \param SS The nested-name-specifier that is being checked for 7921 /// unexpanded parameter packs. 7922 /// 7923 /// \returns true if an error occurred, false otherwise. 7924 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, 7925 UnexpandedParameterPackContext UPPC); 7926 7927 /// If the given name contains an unexpanded parameter pack, 7928 /// diagnose the error. 7929 /// 7930 /// \param NameInfo The name (with source location information) that 7931 /// is being checked for unexpanded parameter packs. 7932 /// 7933 /// \returns true if an error occurred, false otherwise. 7934 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, 7935 UnexpandedParameterPackContext UPPC); 7936 7937 /// If the given template name contains an unexpanded parameter pack, 7938 /// diagnose the error. 7939 /// 7940 /// \param Loc The location of the template name. 7941 /// 7942 /// \param Template The template name that is being checked for unexpanded 7943 /// parameter packs. 7944 /// 7945 /// \returns true if an error occurred, false otherwise. 7946 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, 7947 TemplateName Template, 7948 UnexpandedParameterPackContext UPPC); 7949 7950 /// If the given template argument contains an unexpanded parameter 7951 /// pack, diagnose the error. 7952 /// 7953 /// \param Arg The template argument that is being checked for unexpanded 7954 /// parameter packs. 7955 /// 7956 /// \returns true if an error occurred, false otherwise. 7957 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, 7958 UnexpandedParameterPackContext UPPC); 7959 7960 /// Collect the set of unexpanded parameter packs within the given 7961 /// template argument. 7962 /// 7963 /// \param Arg The template argument that will be traversed to find 7964 /// unexpanded parameter packs. 7965 void collectUnexpandedParameterPacks(TemplateArgument Arg, 7966 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 7967 7968 /// Collect the set of unexpanded parameter packs within the given 7969 /// template argument. 7970 /// 7971 /// \param Arg The template argument that will be traversed to find 7972 /// unexpanded parameter packs. 7973 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, 7974 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 7975 7976 /// Collect the set of unexpanded parameter packs within the given 7977 /// type. 7978 /// 7979 /// \param T The type that will be traversed to find 7980 /// unexpanded parameter packs. 7981 void collectUnexpandedParameterPacks(QualType T, 7982 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 7983 7984 /// Collect the set of unexpanded parameter packs within the given 7985 /// type. 7986 /// 7987 /// \param TL The type that will be traversed to find 7988 /// unexpanded parameter packs. 7989 void collectUnexpandedParameterPacks(TypeLoc TL, 7990 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 7991 7992 /// Collect the set of unexpanded parameter packs within the given 7993 /// nested-name-specifier. 7994 /// 7995 /// \param NNS The nested-name-specifier that will be traversed to find 7996 /// unexpanded parameter packs. 7997 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS, 7998 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 7999 8000 /// Collect the set of unexpanded parameter packs within the given 8001 /// name. 8002 /// 8003 /// \param NameInfo The name that will be traversed to find 8004 /// unexpanded parameter packs. 8005 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, 8006 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 8007 8008 /// Invoked when parsing a template argument followed by an 8009 /// ellipsis, which creates a pack expansion. 8010 /// 8011 /// \param Arg The template argument preceding the ellipsis, which 8012 /// may already be invalid. 8013 /// 8014 /// \param EllipsisLoc The location of the ellipsis. 8015 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, 8016 SourceLocation EllipsisLoc); 8017 8018 /// Invoked when parsing a type followed by an ellipsis, which 8019 /// creates a pack expansion. 8020 /// 8021 /// \param Type The type preceding the ellipsis, which will become 8022 /// the pattern of the pack expansion. 8023 /// 8024 /// \param EllipsisLoc The location of the ellipsis. 8025 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); 8026 8027 /// Construct a pack expansion type from the pattern of the pack 8028 /// expansion. 8029 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, 8030 SourceLocation EllipsisLoc, 8031 Optional<unsigned> NumExpansions); 8032 8033 /// Construct a pack expansion type from the pattern of the pack 8034 /// expansion. 8035 QualType CheckPackExpansion(QualType Pattern, 8036 SourceRange PatternRange, 8037 SourceLocation EllipsisLoc, 8038 Optional<unsigned> NumExpansions); 8039 8040 /// Invoked when parsing an expression followed by an ellipsis, which 8041 /// creates a pack expansion. 8042 /// 8043 /// \param Pattern The expression preceding the ellipsis, which will become 8044 /// the pattern of the pack expansion. 8045 /// 8046 /// \param EllipsisLoc The location of the ellipsis. 8047 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); 8048 8049 /// Invoked when parsing an expression followed by an ellipsis, which 8050 /// creates a pack expansion. 8051 /// 8052 /// \param Pattern The expression preceding the ellipsis, which will become 8053 /// the pattern of the pack expansion. 8054 /// 8055 /// \param EllipsisLoc The location of the ellipsis. 8056 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, 8057 Optional<unsigned> NumExpansions); 8058 8059 /// Determine whether we could expand a pack expansion with the 8060 /// given set of parameter packs into separate arguments by repeatedly 8061 /// transforming the pattern. 8062 /// 8063 /// \param EllipsisLoc The location of the ellipsis that identifies the 8064 /// pack expansion. 8065 /// 8066 /// \param PatternRange The source range that covers the entire pattern of 8067 /// the pack expansion. 8068 /// 8069 /// \param Unexpanded The set of unexpanded parameter packs within the 8070 /// pattern. 8071 /// 8072 /// \param ShouldExpand Will be set to \c true if the transformer should 8073 /// expand the corresponding pack expansions into separate arguments. When 8074 /// set, \c NumExpansions must also be set. 8075 /// 8076 /// \param RetainExpansion Whether the caller should add an unexpanded 8077 /// pack expansion after all of the expanded arguments. This is used 8078 /// when extending explicitly-specified template argument packs per 8079 /// C++0x [temp.arg.explicit]p9. 8080 /// 8081 /// \param NumExpansions The number of separate arguments that will be in 8082 /// the expanded form of the corresponding pack expansion. This is both an 8083 /// input and an output parameter, which can be set by the caller if the 8084 /// number of expansions is known a priori (e.g., due to a prior substitution) 8085 /// and will be set by the callee when the number of expansions is known. 8086 /// The callee must set this value when \c ShouldExpand is \c true; it may 8087 /// set this value in other cases. 8088 /// 8089 /// \returns true if an error occurred (e.g., because the parameter packs 8090 /// are to be instantiated with arguments of different lengths), false 8091 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) 8092 /// must be set. 8093 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, 8094 SourceRange PatternRange, 8095 ArrayRef<UnexpandedParameterPack> Unexpanded, 8096 const MultiLevelTemplateArgumentList &TemplateArgs, 8097 bool &ShouldExpand, 8098 bool &RetainExpansion, 8099 Optional<unsigned> &NumExpansions); 8100 8101 /// Determine the number of arguments in the given pack expansion 8102 /// type. 8103 /// 8104 /// This routine assumes that the number of arguments in the expansion is 8105 /// consistent across all of the unexpanded parameter packs in its pattern. 8106 /// 8107 /// Returns an empty Optional if the type can't be expanded. 8108 Optional<unsigned> getNumArgumentsInExpansion(QualType T, 8109 const MultiLevelTemplateArgumentList &TemplateArgs); 8110 8111 /// Determine whether the given declarator contains any unexpanded 8112 /// parameter packs. 8113 /// 8114 /// This routine is used by the parser to disambiguate function declarators 8115 /// with an ellipsis prior to the ')', e.g., 8116 /// 8117 /// \code 8118 /// void f(T...); 8119 /// \endcode 8120 /// 8121 /// To determine whether we have an (unnamed) function parameter pack or 8122 /// a variadic function. 8123 /// 8124 /// \returns true if the declarator contains any unexpanded parameter packs, 8125 /// false otherwise. 8126 bool containsUnexpandedParameterPacks(Declarator &D); 8127 8128 /// Returns the pattern of the pack expansion for a template argument. 8129 /// 8130 /// \param OrigLoc The template argument to expand. 8131 /// 8132 /// \param Ellipsis Will be set to the location of the ellipsis. 8133 /// 8134 /// \param NumExpansions Will be set to the number of expansions that will 8135 /// be generated from this pack expansion, if known a priori. 8136 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( 8137 TemplateArgumentLoc OrigLoc, 8138 SourceLocation &Ellipsis, 8139 Optional<unsigned> &NumExpansions) const; 8140 8141 /// Given a template argument that contains an unexpanded parameter pack, but 8142 /// which has already been substituted, attempt to determine the number of 8143 /// elements that will be produced once this argument is fully-expanded. 8144 /// 8145 /// This is intended for use when transforming 'sizeof...(Arg)' in order to 8146 /// avoid actually expanding the pack where possible. 8147 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg); 8148 8149 //===--------------------------------------------------------------------===// 8150 // C++ Template Argument Deduction (C++ [temp.deduct]) 8151 //===--------------------------------------------------------------------===// 8152 8153 /// Adjust the type \p ArgFunctionType to match the calling convention, 8154 /// noreturn, and optionally the exception specification of \p FunctionType. 8155 /// Deduction often wants to ignore these properties when matching function 8156 /// types. 8157 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, 8158 bool AdjustExceptionSpec = false); 8159 8160 /// Describes the result of template argument deduction. 8161 /// 8162 /// The TemplateDeductionResult enumeration describes the result of 8163 /// template argument deduction, as returned from 8164 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo 8165 /// structure provides additional information about the results of 8166 /// template argument deduction, e.g., the deduced template argument 8167 /// list (if successful) or the specific template parameters or 8168 /// deduced arguments that were involved in the failure. 8169 enum TemplateDeductionResult { 8170 /// Template argument deduction was successful. 8171 TDK_Success = 0, 8172 /// The declaration was invalid; do nothing. 8173 TDK_Invalid, 8174 /// Template argument deduction exceeded the maximum template 8175 /// instantiation depth (which has already been diagnosed). 8176 TDK_InstantiationDepth, 8177 /// Template argument deduction did not deduce a value 8178 /// for every template parameter. 8179 TDK_Incomplete, 8180 /// Template argument deduction did not deduce a value for every 8181 /// expansion of an expanded template parameter pack. 8182 TDK_IncompletePack, 8183 /// Template argument deduction produced inconsistent 8184 /// deduced values for the given template parameter. 8185 TDK_Inconsistent, 8186 /// Template argument deduction failed due to inconsistent 8187 /// cv-qualifiers on a template parameter type that would 8188 /// otherwise be deduced, e.g., we tried to deduce T in "const T" 8189 /// but were given a non-const "X". 8190 TDK_Underqualified, 8191 /// Substitution of the deduced template argument values 8192 /// resulted in an error. 8193 TDK_SubstitutionFailure, 8194 /// After substituting deduced template arguments, a dependent 8195 /// parameter type did not match the corresponding argument. 8196 TDK_DeducedMismatch, 8197 /// After substituting deduced template arguments, an element of 8198 /// a dependent parameter type did not match the corresponding element 8199 /// of the corresponding argument (when deducing from an initializer list). 8200 TDK_DeducedMismatchNested, 8201 /// A non-depnedent component of the parameter did not match the 8202 /// corresponding component of the argument. 8203 TDK_NonDeducedMismatch, 8204 /// When performing template argument deduction for a function 8205 /// template, there were too many call arguments. 8206 TDK_TooManyArguments, 8207 /// When performing template argument deduction for a function 8208 /// template, there were too few call arguments. 8209 TDK_TooFewArguments, 8210 /// The explicitly-specified template arguments were not valid 8211 /// template arguments for the given template. 8212 TDK_InvalidExplicitArguments, 8213 /// Checking non-dependent argument conversions failed. 8214 TDK_NonDependentConversionFailure, 8215 /// The deduced arguments did not satisfy the constraints associated 8216 /// with the template. 8217 TDK_ConstraintsNotSatisfied, 8218 /// Deduction failed; that's all we know. 8219 TDK_MiscellaneousDeductionFailure, 8220 /// CUDA Target attributes do not match. 8221 TDK_CUDATargetMismatch 8222 }; 8223 8224 TemplateDeductionResult 8225 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, 8226 const TemplateArgumentList &TemplateArgs, 8227 sema::TemplateDeductionInfo &Info); 8228 8229 TemplateDeductionResult 8230 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, 8231 const TemplateArgumentList &TemplateArgs, 8232 sema::TemplateDeductionInfo &Info); 8233 8234 TemplateDeductionResult SubstituteExplicitTemplateArguments( 8235 FunctionTemplateDecl *FunctionTemplate, 8236 TemplateArgumentListInfo &ExplicitTemplateArgs, 8237 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 8238 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, 8239 sema::TemplateDeductionInfo &Info); 8240 8241 /// brief A function argument from which we performed template argument 8242 // deduction for a call. 8243 struct OriginalCallArg { OriginalCallArgOriginalCallArg8244 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, 8245 unsigned ArgIdx, QualType OriginalArgType) 8246 : OriginalParamType(OriginalParamType), 8247 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx), 8248 OriginalArgType(OriginalArgType) {} 8249 8250 QualType OriginalParamType; 8251 bool DecomposedParam; 8252 unsigned ArgIdx; 8253 QualType OriginalArgType; 8254 }; 8255 8256 TemplateDeductionResult FinishTemplateArgumentDeduction( 8257 FunctionTemplateDecl *FunctionTemplate, 8258 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 8259 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, 8260 sema::TemplateDeductionInfo &Info, 8261 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr, 8262 bool PartialOverloading = false, 8263 llvm::function_ref<bool()> CheckNonDependent = []{ return false; }); 8264 8265 TemplateDeductionResult DeduceTemplateArguments( 8266 FunctionTemplateDecl *FunctionTemplate, 8267 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 8268 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, 8269 bool PartialOverloading, 8270 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent); 8271 8272 TemplateDeductionResult 8273 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 8274 TemplateArgumentListInfo *ExplicitTemplateArgs, 8275 QualType ArgFunctionType, 8276 FunctionDecl *&Specialization, 8277 sema::TemplateDeductionInfo &Info, 8278 bool IsAddressOfFunction = false); 8279 8280 TemplateDeductionResult 8281 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 8282 QualType ToType, 8283 CXXConversionDecl *&Specialization, 8284 sema::TemplateDeductionInfo &Info); 8285 8286 TemplateDeductionResult 8287 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 8288 TemplateArgumentListInfo *ExplicitTemplateArgs, 8289 FunctionDecl *&Specialization, 8290 sema::TemplateDeductionInfo &Info, 8291 bool IsAddressOfFunction = false); 8292 8293 /// Substitute Replacement for \p auto in \p TypeWithAuto 8294 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); 8295 /// Substitute Replacement for auto in TypeWithAuto 8296 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, 8297 QualType Replacement); 8298 /// Completely replace the \c auto in \p TypeWithAuto by 8299 /// \p Replacement. This does not retain any \c auto type sugar. 8300 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement); 8301 TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, 8302 QualType Replacement); 8303 8304 /// Result type of DeduceAutoType. 8305 enum DeduceAutoResult { 8306 DAR_Succeeded, 8307 DAR_Failed, 8308 DAR_FailedAlreadyDiagnosed 8309 }; 8310 8311 DeduceAutoResult 8312 DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result, 8313 Optional<unsigned> DependentDeductionDepth = None, 8314 bool IgnoreConstraints = false); 8315 DeduceAutoResult 8316 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result, 8317 Optional<unsigned> DependentDeductionDepth = None, 8318 bool IgnoreConstraints = false); 8319 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); 8320 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, 8321 bool Diagnose = true); 8322 8323 /// Declare implicit deduction guides for a class template if we've 8324 /// not already done so. 8325 void DeclareImplicitDeductionGuides(TemplateDecl *Template, 8326 SourceLocation Loc); 8327 8328 QualType DeduceTemplateSpecializationFromInitializer( 8329 TypeSourceInfo *TInfo, const InitializedEntity &Entity, 8330 const InitializationKind &Kind, MultiExprArg Init); 8331 8332 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, 8333 QualType Type, TypeSourceInfo *TSI, 8334 SourceRange Range, bool DirectInit, 8335 Expr *Init); 8336 8337 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const; 8338 8339 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, 8340 SourceLocation ReturnLoc, 8341 Expr *&RetExpr, AutoType *AT); 8342 8343 FunctionTemplateDecl *getMoreSpecializedTemplate( 8344 FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, 8345 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, 8346 unsigned NumCallArguments2, bool Reversed = false); 8347 UnresolvedSetIterator 8348 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, 8349 TemplateSpecCandidateSet &FailedCandidates, 8350 SourceLocation Loc, 8351 const PartialDiagnostic &NoneDiag, 8352 const PartialDiagnostic &AmbigDiag, 8353 const PartialDiagnostic &CandidateDiag, 8354 bool Complain = true, QualType TargetType = QualType()); 8355 8356 ClassTemplatePartialSpecializationDecl * 8357 getMoreSpecializedPartialSpecialization( 8358 ClassTemplatePartialSpecializationDecl *PS1, 8359 ClassTemplatePartialSpecializationDecl *PS2, 8360 SourceLocation Loc); 8361 8362 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, 8363 sema::TemplateDeductionInfo &Info); 8364 8365 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( 8366 VarTemplatePartialSpecializationDecl *PS1, 8367 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); 8368 8369 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T, 8370 sema::TemplateDeductionInfo &Info); 8371 8372 bool isTemplateTemplateParameterAtLeastAsSpecializedAs( 8373 TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc); 8374 8375 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, 8376 unsigned Depth, llvm::SmallBitVector &Used); 8377 8378 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, 8379 bool OnlyDeduced, 8380 unsigned Depth, 8381 llvm::SmallBitVector &Used); MarkDeducedTemplateParameters(const FunctionTemplateDecl * FunctionTemplate,llvm::SmallBitVector & Deduced)8382 void MarkDeducedTemplateParameters( 8383 const FunctionTemplateDecl *FunctionTemplate, 8384 llvm::SmallBitVector &Deduced) { 8385 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); 8386 } 8387 static void MarkDeducedTemplateParameters(ASTContext &Ctx, 8388 const FunctionTemplateDecl *FunctionTemplate, 8389 llvm::SmallBitVector &Deduced); 8390 8391 //===--------------------------------------------------------------------===// 8392 // C++ Template Instantiation 8393 // 8394 8395 MultiLevelTemplateArgumentList 8396 getTemplateInstantiationArgs(NamedDecl *D, 8397 const TemplateArgumentList *Innermost = nullptr, 8398 bool RelativeToPrimary = false, 8399 const FunctionDecl *Pattern = nullptr); 8400 8401 /// A context in which code is being synthesized (where a source location 8402 /// alone is not sufficient to identify the context). This covers template 8403 /// instantiation and various forms of implicitly-generated functions. 8404 struct CodeSynthesisContext { 8405 /// The kind of template instantiation we are performing 8406 enum SynthesisKind { 8407 /// We are instantiating a template declaration. The entity is 8408 /// the declaration we're instantiating (e.g., a CXXRecordDecl). 8409 TemplateInstantiation, 8410 8411 /// We are instantiating a default argument for a template 8412 /// parameter. The Entity is the template parameter whose argument is 8413 /// being instantiated, the Template is the template, and the 8414 /// TemplateArgs/NumTemplateArguments provide the template arguments as 8415 /// specified. 8416 DefaultTemplateArgumentInstantiation, 8417 8418 /// We are instantiating a default argument for a function. 8419 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs 8420 /// provides the template arguments as specified. 8421 DefaultFunctionArgumentInstantiation, 8422 8423 /// We are substituting explicit template arguments provided for 8424 /// a function template. The entity is a FunctionTemplateDecl. 8425 ExplicitTemplateArgumentSubstitution, 8426 8427 /// We are substituting template argument determined as part of 8428 /// template argument deduction for either a class template 8429 /// partial specialization or a function template. The 8430 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or 8431 /// a TemplateDecl. 8432 DeducedTemplateArgumentSubstitution, 8433 8434 /// We are substituting prior template arguments into a new 8435 /// template parameter. The template parameter itself is either a 8436 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. 8437 PriorTemplateArgumentSubstitution, 8438 8439 /// We are checking the validity of a default template argument that 8440 /// has been used when naming a template-id. 8441 DefaultTemplateArgumentChecking, 8442 8443 /// We are computing the exception specification for a defaulted special 8444 /// member function. 8445 ExceptionSpecEvaluation, 8446 8447 /// We are instantiating the exception specification for a function 8448 /// template which was deferred until it was needed. 8449 ExceptionSpecInstantiation, 8450 8451 /// We are instantiating a requirement of a requires expression. 8452 RequirementInstantiation, 8453 8454 /// We are checking the satisfaction of a nested requirement of a requires 8455 /// expression. 8456 NestedRequirementConstraintsCheck, 8457 8458 /// We are declaring an implicit special member function. 8459 DeclaringSpecialMember, 8460 8461 /// We are declaring an implicit 'operator==' for a defaulted 8462 /// 'operator<=>'. 8463 DeclaringImplicitEqualityComparison, 8464 8465 /// We are defining a synthesized function (such as a defaulted special 8466 /// member). 8467 DefiningSynthesizedFunction, 8468 8469 // We are checking the constraints associated with a constrained entity or 8470 // the constraint expression of a concept. This includes the checks that 8471 // atomic constraints have the type 'bool' and that they can be constant 8472 // evaluated. 8473 ConstraintsCheck, 8474 8475 // We are substituting template arguments into a constraint expression. 8476 ConstraintSubstitution, 8477 8478 // We are normalizing a constraint expression. 8479 ConstraintNormalization, 8480 8481 // We are substituting into the parameter mapping of an atomic constraint 8482 // during normalization. 8483 ParameterMappingSubstitution, 8484 8485 /// We are rewriting a comparison operator in terms of an operator<=>. 8486 RewritingOperatorAsSpaceship, 8487 8488 /// We are initializing a structured binding. 8489 InitializingStructuredBinding, 8490 8491 /// We are marking a class as __dllexport. 8492 MarkingClassDllexported, 8493 8494 /// Added for Template instantiation observation. 8495 /// Memoization means we are _not_ instantiating a template because 8496 /// it is already instantiated (but we entered a context where we 8497 /// would have had to if it was not already instantiated). 8498 Memoization 8499 } Kind; 8500 8501 /// Was the enclosing context a non-instantiation SFINAE context? 8502 bool SavedInNonInstantiationSFINAEContext; 8503 8504 /// The point of instantiation or synthesis within the source code. 8505 SourceLocation PointOfInstantiation; 8506 8507 /// The entity that is being synthesized. 8508 Decl *Entity; 8509 8510 /// The template (or partial specialization) in which we are 8511 /// performing the instantiation, for substitutions of prior template 8512 /// arguments. 8513 NamedDecl *Template; 8514 8515 /// The list of template arguments we are substituting, if they 8516 /// are not part of the entity. 8517 const TemplateArgument *TemplateArgs; 8518 8519 // FIXME: Wrap this union around more members, or perhaps store the 8520 // kind-specific members in the RAII object owning the context. 8521 union { 8522 /// The number of template arguments in TemplateArgs. 8523 unsigned NumTemplateArgs; 8524 8525 /// The special member being declared or defined. 8526 CXXSpecialMember SpecialMember; 8527 }; 8528 template_argumentsCodeSynthesisContext8529 ArrayRef<TemplateArgument> template_arguments() const { 8530 assert(Kind != DeclaringSpecialMember); 8531 return {TemplateArgs, NumTemplateArgs}; 8532 } 8533 8534 /// The template deduction info object associated with the 8535 /// substitution or checking of explicit or deduced template arguments. 8536 sema::TemplateDeductionInfo *DeductionInfo; 8537 8538 /// The source range that covers the construct that cause 8539 /// the instantiation, e.g., the template-id that causes a class 8540 /// template instantiation. 8541 SourceRange InstantiationRange; 8542 CodeSynthesisContextCodeSynthesisContext8543 CodeSynthesisContext() 8544 : Kind(TemplateInstantiation), 8545 SavedInNonInstantiationSFINAEContext(false), Entity(nullptr), 8546 Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0), 8547 DeductionInfo(nullptr) {} 8548 8549 /// Determines whether this template is an actual instantiation 8550 /// that should be counted toward the maximum instantiation depth. 8551 bool isInstantiationRecord() const; 8552 }; 8553 8554 /// List of active code synthesis contexts. 8555 /// 8556 /// This vector is treated as a stack. As synthesis of one entity requires 8557 /// synthesis of another, additional contexts are pushed onto the stack. 8558 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts; 8559 8560 /// Specializations whose definitions are currently being instantiated. 8561 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations; 8562 8563 /// Non-dependent types used in templates that have already been instantiated 8564 /// by some template instantiation. 8565 llvm::DenseSet<QualType> InstantiatedNonDependentTypes; 8566 8567 /// Extra modules inspected when performing a lookup during a template 8568 /// instantiation. Computed lazily. 8569 SmallVector<Module*, 16> CodeSynthesisContextLookupModules; 8570 8571 /// Cache of additional modules that should be used for name lookup 8572 /// within the current template instantiation. Computed lazily; use 8573 /// getLookupModules() to get a complete set. 8574 llvm::DenseSet<Module*> LookupModulesCache; 8575 8576 /// Get the set of additional modules that should be checked during 8577 /// name lookup. A module and its imports become visible when instanting a 8578 /// template defined within it. 8579 llvm::DenseSet<Module*> &getLookupModules(); 8580 8581 /// Map from the most recent declaration of a namespace to the most 8582 /// recent visible declaration of that namespace. 8583 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache; 8584 8585 /// Whether we are in a SFINAE context that is not associated with 8586 /// template instantiation. 8587 /// 8588 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside 8589 /// of a template instantiation or template argument deduction. 8590 bool InNonInstantiationSFINAEContext; 8591 8592 /// The number of \p CodeSynthesisContexts that are not template 8593 /// instantiations and, therefore, should not be counted as part of the 8594 /// instantiation depth. 8595 /// 8596 /// When the instantiation depth reaches the user-configurable limit 8597 /// \p LangOptions::InstantiationDepth we will abort instantiation. 8598 // FIXME: Should we have a similar limit for other forms of synthesis? 8599 unsigned NonInstantiationEntries; 8600 8601 /// The depth of the context stack at the point when the most recent 8602 /// error or warning was produced. 8603 /// 8604 /// This value is used to suppress printing of redundant context stacks 8605 /// when there are multiple errors or warnings in the same instantiation. 8606 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else. 8607 unsigned LastEmittedCodeSynthesisContextDepth = 0; 8608 8609 /// The template instantiation callbacks to trace or track 8610 /// instantiations (objects can be chained). 8611 /// 8612 /// This callbacks is used to print, trace or track template 8613 /// instantiations as they are being constructed. 8614 std::vector<std::unique_ptr<TemplateInstantiationCallback>> 8615 TemplateInstCallbacks; 8616 8617 /// The current index into pack expansion arguments that will be 8618 /// used for substitution of parameter packs. 8619 /// 8620 /// The pack expansion index will be -1 to indicate that parameter packs 8621 /// should be instantiated as themselves. Otherwise, the index specifies 8622 /// which argument within the parameter pack will be used for substitution. 8623 int ArgumentPackSubstitutionIndex; 8624 8625 /// RAII object used to change the argument pack substitution index 8626 /// within a \c Sema object. 8627 /// 8628 /// See \c ArgumentPackSubstitutionIndex for more information. 8629 class ArgumentPackSubstitutionIndexRAII { 8630 Sema &Self; 8631 int OldSubstitutionIndex; 8632 8633 public: ArgumentPackSubstitutionIndexRAII(Sema & Self,int NewSubstitutionIndex)8634 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) 8635 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { 8636 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; 8637 } 8638 ~ArgumentPackSubstitutionIndexRAII()8639 ~ArgumentPackSubstitutionIndexRAII() { 8640 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; 8641 } 8642 }; 8643 8644 friend class ArgumentPackSubstitutionRAII; 8645 8646 /// For each declaration that involved template argument deduction, the 8647 /// set of diagnostics that were suppressed during that template argument 8648 /// deduction. 8649 /// 8650 /// FIXME: Serialize this structure to the AST file. 8651 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > 8652 SuppressedDiagnosticsMap; 8653 SuppressedDiagnosticsMap SuppressedDiagnostics; 8654 8655 /// A stack object to be created when performing template 8656 /// instantiation. 8657 /// 8658 /// Construction of an object of type \c InstantiatingTemplate 8659 /// pushes the current instantiation onto the stack of active 8660 /// instantiations. If the size of this stack exceeds the maximum 8661 /// number of recursive template instantiations, construction 8662 /// produces an error and evaluates true. 8663 /// 8664 /// Destruction of this object will pop the named instantiation off 8665 /// the stack. 8666 struct InstantiatingTemplate { 8667 /// Note that we are instantiating a class template, 8668 /// function template, variable template, alias template, 8669 /// or a member thereof. 8670 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8671 Decl *Entity, 8672 SourceRange InstantiationRange = SourceRange()); 8673 8674 struct ExceptionSpecification {}; 8675 /// Note that we are instantiating an exception specification 8676 /// of a function template. 8677 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8678 FunctionDecl *Entity, ExceptionSpecification, 8679 SourceRange InstantiationRange = SourceRange()); 8680 8681 /// Note that we are instantiating a default argument in a 8682 /// template-id. 8683 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8684 TemplateParameter Param, TemplateDecl *Template, 8685 ArrayRef<TemplateArgument> TemplateArgs, 8686 SourceRange InstantiationRange = SourceRange()); 8687 8688 /// Note that we are substituting either explicitly-specified or 8689 /// deduced template arguments during function template argument deduction. 8690 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8691 FunctionTemplateDecl *FunctionTemplate, 8692 ArrayRef<TemplateArgument> TemplateArgs, 8693 CodeSynthesisContext::SynthesisKind Kind, 8694 sema::TemplateDeductionInfo &DeductionInfo, 8695 SourceRange InstantiationRange = SourceRange()); 8696 8697 /// Note that we are instantiating as part of template 8698 /// argument deduction for a class template declaration. 8699 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8700 TemplateDecl *Template, 8701 ArrayRef<TemplateArgument> TemplateArgs, 8702 sema::TemplateDeductionInfo &DeductionInfo, 8703 SourceRange InstantiationRange = SourceRange()); 8704 8705 /// Note that we are instantiating as part of template 8706 /// argument deduction for a class template partial 8707 /// specialization. 8708 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8709 ClassTemplatePartialSpecializationDecl *PartialSpec, 8710 ArrayRef<TemplateArgument> TemplateArgs, 8711 sema::TemplateDeductionInfo &DeductionInfo, 8712 SourceRange InstantiationRange = SourceRange()); 8713 8714 /// Note that we are instantiating as part of template 8715 /// argument deduction for a variable template partial 8716 /// specialization. 8717 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8718 VarTemplatePartialSpecializationDecl *PartialSpec, 8719 ArrayRef<TemplateArgument> TemplateArgs, 8720 sema::TemplateDeductionInfo &DeductionInfo, 8721 SourceRange InstantiationRange = SourceRange()); 8722 8723 /// Note that we are instantiating a default argument for a function 8724 /// parameter. 8725 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8726 ParmVarDecl *Param, 8727 ArrayRef<TemplateArgument> TemplateArgs, 8728 SourceRange InstantiationRange = SourceRange()); 8729 8730 /// Note that we are substituting prior template arguments into a 8731 /// non-type parameter. 8732 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8733 NamedDecl *Template, 8734 NonTypeTemplateParmDecl *Param, 8735 ArrayRef<TemplateArgument> TemplateArgs, 8736 SourceRange InstantiationRange); 8737 8738 /// Note that we are substituting prior template arguments into a 8739 /// template template parameter. 8740 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8741 NamedDecl *Template, 8742 TemplateTemplateParmDecl *Param, 8743 ArrayRef<TemplateArgument> TemplateArgs, 8744 SourceRange InstantiationRange); 8745 8746 /// Note that we are checking the default template argument 8747 /// against the template parameter for a given template-id. 8748 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8749 TemplateDecl *Template, 8750 NamedDecl *Param, 8751 ArrayRef<TemplateArgument> TemplateArgs, 8752 SourceRange InstantiationRange); 8753 8754 struct ConstraintsCheck {}; 8755 /// \brief Note that we are checking the constraints associated with some 8756 /// constrained entity (a concept declaration or a template with associated 8757 /// constraints). 8758 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8759 ConstraintsCheck, NamedDecl *Template, 8760 ArrayRef<TemplateArgument> TemplateArgs, 8761 SourceRange InstantiationRange); 8762 8763 struct ConstraintSubstitution {}; 8764 /// \brief Note that we are checking a constraint expression associated 8765 /// with a template declaration or as part of the satisfaction check of a 8766 /// concept. 8767 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8768 ConstraintSubstitution, NamedDecl *Template, 8769 sema::TemplateDeductionInfo &DeductionInfo, 8770 SourceRange InstantiationRange); 8771 8772 struct ConstraintNormalization {}; 8773 /// \brief Note that we are normalizing a constraint expression. 8774 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8775 ConstraintNormalization, NamedDecl *Template, 8776 SourceRange InstantiationRange); 8777 8778 struct ParameterMappingSubstitution {}; 8779 /// \brief Note that we are subtituting into the parameter mapping of an 8780 /// atomic constraint during constraint normalization. 8781 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8782 ParameterMappingSubstitution, NamedDecl *Template, 8783 SourceRange InstantiationRange); 8784 8785 /// \brief Note that we are substituting template arguments into a part of 8786 /// a requirement of a requires expression. 8787 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8788 concepts::Requirement *Req, 8789 sema::TemplateDeductionInfo &DeductionInfo, 8790 SourceRange InstantiationRange = SourceRange()); 8791 8792 /// \brief Note that we are checking the satisfaction of the constraint 8793 /// expression inside of a nested requirement. 8794 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8795 concepts::NestedRequirement *Req, ConstraintsCheck, 8796 SourceRange InstantiationRange = SourceRange()); 8797 8798 /// Note that we have finished instantiating this template. 8799 void Clear(); 8800 ~InstantiatingTemplateInstantiatingTemplate8801 ~InstantiatingTemplate() { Clear(); } 8802 8803 /// Determines whether we have exceeded the maximum 8804 /// recursive template instantiations. isInvalidInstantiatingTemplate8805 bool isInvalid() const { return Invalid; } 8806 8807 /// Determine whether we are already instantiating this 8808 /// specialization in some surrounding active instantiation. isAlreadyInstantiatingInstantiatingTemplate8809 bool isAlreadyInstantiating() const { return AlreadyInstantiating; } 8810 8811 private: 8812 Sema &SemaRef; 8813 bool Invalid; 8814 bool AlreadyInstantiating; 8815 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, 8816 SourceRange InstantiationRange); 8817 8818 InstantiatingTemplate( 8819 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, 8820 SourceLocation PointOfInstantiation, SourceRange InstantiationRange, 8821 Decl *Entity, NamedDecl *Template = nullptr, 8822 ArrayRef<TemplateArgument> TemplateArgs = None, 8823 sema::TemplateDeductionInfo *DeductionInfo = nullptr); 8824 8825 InstantiatingTemplate(const InstantiatingTemplate&) = delete; 8826 8827 InstantiatingTemplate& 8828 operator=(const InstantiatingTemplate&) = delete; 8829 }; 8830 8831 void pushCodeSynthesisContext(CodeSynthesisContext Ctx); 8832 void popCodeSynthesisContext(); 8833 8834 /// Determine whether we are currently performing template instantiation. inTemplateInstantiation()8835 bool inTemplateInstantiation() const { 8836 return CodeSynthesisContexts.size() > NonInstantiationEntries; 8837 } 8838 PrintContextStack()8839 void PrintContextStack() { 8840 if (!CodeSynthesisContexts.empty() && 8841 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) { 8842 PrintInstantiationStack(); 8843 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size(); 8844 } 8845 if (PragmaAttributeCurrentTargetDecl) 8846 PrintPragmaAttributeInstantiationPoint(); 8847 } 8848 void PrintInstantiationStack(); 8849 8850 void PrintPragmaAttributeInstantiationPoint(); 8851 8852 /// Determines whether we are currently in a context where 8853 /// template argument substitution failures are not considered 8854 /// errors. 8855 /// 8856 /// \returns An empty \c Optional if we're not in a SFINAE context. 8857 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest 8858 /// template-deduction context object, which can be used to capture 8859 /// diagnostics that will be suppressed. 8860 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; 8861 8862 /// Determines whether we are currently in a context that 8863 /// is not evaluated as per C++ [expr] p5. isUnevaluatedContext()8864 bool isUnevaluatedContext() const { 8865 assert(!ExprEvalContexts.empty() && 8866 "Must be in an expression evaluation context"); 8867 return ExprEvalContexts.back().isUnevaluated(); 8868 } 8869 8870 /// RAII class used to determine whether SFINAE has 8871 /// trapped any errors that occur during template argument 8872 /// deduction. 8873 class SFINAETrap { 8874 Sema &SemaRef; 8875 unsigned PrevSFINAEErrors; 8876 bool PrevInNonInstantiationSFINAEContext; 8877 bool PrevAccessCheckingSFINAE; 8878 bool PrevLastDiagnosticIgnored; 8879 8880 public: 8881 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) SemaRef(SemaRef)8882 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), 8883 PrevInNonInstantiationSFINAEContext( 8884 SemaRef.InNonInstantiationSFINAEContext), 8885 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE), 8886 PrevLastDiagnosticIgnored( 8887 SemaRef.getDiagnostics().isLastDiagnosticIgnored()) 8888 { 8889 if (!SemaRef.isSFINAEContext()) 8890 SemaRef.InNonInstantiationSFINAEContext = true; 8891 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; 8892 } 8893 ~SFINAETrap()8894 ~SFINAETrap() { 8895 SemaRef.NumSFINAEErrors = PrevSFINAEErrors; 8896 SemaRef.InNonInstantiationSFINAEContext 8897 = PrevInNonInstantiationSFINAEContext; 8898 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; 8899 SemaRef.getDiagnostics().setLastDiagnosticIgnored( 8900 PrevLastDiagnosticIgnored); 8901 } 8902 8903 /// Determine whether any SFINAE errors have been trapped. hasErrorOccurred()8904 bool hasErrorOccurred() const { 8905 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; 8906 } 8907 }; 8908 8909 /// RAII class used to indicate that we are performing provisional 8910 /// semantic analysis to determine the validity of a construct, so 8911 /// typo-correction and diagnostics in the immediate context (not within 8912 /// implicitly-instantiated templates) should be suppressed. 8913 class TentativeAnalysisScope { 8914 Sema &SemaRef; 8915 // FIXME: Using a SFINAETrap for this is a hack. 8916 SFINAETrap Trap; 8917 bool PrevDisableTypoCorrection; 8918 public: TentativeAnalysisScope(Sema & SemaRef)8919 explicit TentativeAnalysisScope(Sema &SemaRef) 8920 : SemaRef(SemaRef), Trap(SemaRef, true), 8921 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) { 8922 SemaRef.DisableTypoCorrection = true; 8923 } ~TentativeAnalysisScope()8924 ~TentativeAnalysisScope() { 8925 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection; 8926 } 8927 }; 8928 8929 /// The current instantiation scope used to store local 8930 /// variables. 8931 LocalInstantiationScope *CurrentInstantiationScope; 8932 8933 /// Tracks whether we are in a context where typo correction is 8934 /// disabled. 8935 bool DisableTypoCorrection; 8936 8937 /// The number of typos corrected by CorrectTypo. 8938 unsigned TyposCorrected; 8939 8940 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet; 8941 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations; 8942 8943 /// A cache containing identifiers for which typo correction failed and 8944 /// their locations, so that repeated attempts to correct an identifier in a 8945 /// given location are ignored if typo correction already failed for it. 8946 IdentifierSourceLocations TypoCorrectionFailures; 8947 8948 /// Worker object for performing CFG-based warnings. 8949 sema::AnalysisBasedWarnings AnalysisWarnings; 8950 threadSafety::BeforeSet *ThreadSafetyDeclCache; 8951 8952 /// An entity for which implicit template instantiation is required. 8953 /// 8954 /// The source location associated with the declaration is the first place in 8955 /// the source code where the declaration was "used". It is not necessarily 8956 /// the point of instantiation (which will be either before or after the 8957 /// namespace-scope declaration that triggered this implicit instantiation), 8958 /// However, it is the location that diagnostics should generally refer to, 8959 /// because users will need to know what code triggered the instantiation. 8960 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; 8961 8962 /// The queue of implicit template instantiations that are required 8963 /// but have not yet been performed. 8964 std::deque<PendingImplicitInstantiation> PendingInstantiations; 8965 8966 /// Queue of implicit template instantiations that cannot be performed 8967 /// eagerly. 8968 SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations; 8969 8970 class GlobalEagerInstantiationScope { 8971 public: GlobalEagerInstantiationScope(Sema & S,bool Enabled)8972 GlobalEagerInstantiationScope(Sema &S, bool Enabled) 8973 : S(S), Enabled(Enabled) { 8974 if (!Enabled) return; 8975 8976 SavedPendingInstantiations.swap(S.PendingInstantiations); 8977 SavedVTableUses.swap(S.VTableUses); 8978 } 8979 perform()8980 void perform() { 8981 if (Enabled) { 8982 S.DefineUsedVTables(); 8983 S.PerformPendingInstantiations(); 8984 } 8985 } 8986 ~GlobalEagerInstantiationScope()8987 ~GlobalEagerInstantiationScope() { 8988 if (!Enabled) return; 8989 8990 // Restore the set of pending vtables. 8991 assert(S.VTableUses.empty() && 8992 "VTableUses should be empty before it is discarded."); 8993 S.VTableUses.swap(SavedVTableUses); 8994 8995 // Restore the set of pending implicit instantiations. 8996 if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) { 8997 assert(S.PendingInstantiations.empty() && 8998 "PendingInstantiations should be empty before it is discarded."); 8999 S.PendingInstantiations.swap(SavedPendingInstantiations); 9000 } else { 9001 // Template instantiations in the PCH may be delayed until the TU. 9002 S.PendingInstantiations.swap(SavedPendingInstantiations); 9003 S.PendingInstantiations.insert(S.PendingInstantiations.end(), 9004 SavedPendingInstantiations.begin(), 9005 SavedPendingInstantiations.end()); 9006 } 9007 } 9008 9009 private: 9010 Sema &S; 9011 SmallVector<VTableUse, 16> SavedVTableUses; 9012 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; 9013 bool Enabled; 9014 }; 9015 9016 /// The queue of implicit template instantiations that are required 9017 /// and must be performed within the current local scope. 9018 /// 9019 /// This queue is only used for member functions of local classes in 9020 /// templates, which must be instantiated in the same scope as their 9021 /// enclosing function, so that they can reference function-local 9022 /// types, static variables, enumerators, etc. 9023 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; 9024 9025 class LocalEagerInstantiationScope { 9026 public: LocalEagerInstantiationScope(Sema & S)9027 LocalEagerInstantiationScope(Sema &S) : S(S) { 9028 SavedPendingLocalImplicitInstantiations.swap( 9029 S.PendingLocalImplicitInstantiations); 9030 } 9031 perform()9032 void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); } 9033 ~LocalEagerInstantiationScope()9034 ~LocalEagerInstantiationScope() { 9035 assert(S.PendingLocalImplicitInstantiations.empty() && 9036 "there shouldn't be any pending local implicit instantiations"); 9037 SavedPendingLocalImplicitInstantiations.swap( 9038 S.PendingLocalImplicitInstantiations); 9039 } 9040 9041 private: 9042 Sema &S; 9043 std::deque<PendingImplicitInstantiation> 9044 SavedPendingLocalImplicitInstantiations; 9045 }; 9046 9047 /// A helper class for building up ExtParameterInfos. 9048 class ExtParameterInfoBuilder { 9049 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos; 9050 bool HasInteresting = false; 9051 9052 public: 9053 /// Set the ExtParameterInfo for the parameter at the given index, 9054 /// set(unsigned index,FunctionProtoType::ExtParameterInfo info)9055 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) { 9056 assert(Infos.size() <= index); 9057 Infos.resize(index); 9058 Infos.push_back(info); 9059 9060 if (!HasInteresting) 9061 HasInteresting = (info != FunctionProtoType::ExtParameterInfo()); 9062 } 9063 9064 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the 9065 /// ExtParameterInfo array we've built up. 9066 const FunctionProtoType::ExtParameterInfo * getPointerOrNull(unsigned numParams)9067 getPointerOrNull(unsigned numParams) { 9068 if (!HasInteresting) return nullptr; 9069 Infos.resize(numParams); 9070 return Infos.data(); 9071 } 9072 }; 9073 9074 void PerformPendingInstantiations(bool LocalOnly = false); 9075 9076 TypeSourceInfo *SubstType(TypeSourceInfo *T, 9077 const MultiLevelTemplateArgumentList &TemplateArgs, 9078 SourceLocation Loc, DeclarationName Entity, 9079 bool AllowDeducedTST = false); 9080 9081 QualType SubstType(QualType T, 9082 const MultiLevelTemplateArgumentList &TemplateArgs, 9083 SourceLocation Loc, DeclarationName Entity); 9084 9085 TypeSourceInfo *SubstType(TypeLoc TL, 9086 const MultiLevelTemplateArgumentList &TemplateArgs, 9087 SourceLocation Loc, DeclarationName Entity); 9088 9089 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, 9090 const MultiLevelTemplateArgumentList &TemplateArgs, 9091 SourceLocation Loc, 9092 DeclarationName Entity, 9093 CXXRecordDecl *ThisContext, 9094 Qualifiers ThisTypeQuals); 9095 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, 9096 const MultiLevelTemplateArgumentList &Args); 9097 bool SubstExceptionSpec(SourceLocation Loc, 9098 FunctionProtoType::ExceptionSpecInfo &ESI, 9099 SmallVectorImpl<QualType> &ExceptionStorage, 9100 const MultiLevelTemplateArgumentList &Args); 9101 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, 9102 const MultiLevelTemplateArgumentList &TemplateArgs, 9103 int indexAdjustment, 9104 Optional<unsigned> NumExpansions, 9105 bool ExpectParameterPack); 9106 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, 9107 const FunctionProtoType::ExtParameterInfo *ExtParamInfos, 9108 const MultiLevelTemplateArgumentList &TemplateArgs, 9109 SmallVectorImpl<QualType> &ParamTypes, 9110 SmallVectorImpl<ParmVarDecl *> *OutParams, 9111 ExtParameterInfoBuilder &ParamInfos); 9112 ExprResult SubstExpr(Expr *E, 9113 const MultiLevelTemplateArgumentList &TemplateArgs); 9114 9115 /// Substitute the given template arguments into a list of 9116 /// expressions, expanding pack expansions if required. 9117 /// 9118 /// \param Exprs The list of expressions to substitute into. 9119 /// 9120 /// \param IsCall Whether this is some form of call, in which case 9121 /// default arguments will be dropped. 9122 /// 9123 /// \param TemplateArgs The set of template arguments to substitute. 9124 /// 9125 /// \param Outputs Will receive all of the substituted arguments. 9126 /// 9127 /// \returns true if an error occurred, false otherwise. 9128 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, 9129 const MultiLevelTemplateArgumentList &TemplateArgs, 9130 SmallVectorImpl<Expr *> &Outputs); 9131 9132 StmtResult SubstStmt(Stmt *S, 9133 const MultiLevelTemplateArgumentList &TemplateArgs); 9134 9135 TemplateParameterList * 9136 SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, 9137 const MultiLevelTemplateArgumentList &TemplateArgs); 9138 9139 bool 9140 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, 9141 const MultiLevelTemplateArgumentList &TemplateArgs, 9142 TemplateArgumentListInfo &Outputs); 9143 9144 9145 Decl *SubstDecl(Decl *D, DeclContext *Owner, 9146 const MultiLevelTemplateArgumentList &TemplateArgs); 9147 9148 /// Substitute the name and return type of a defaulted 'operator<=>' to form 9149 /// an implicit 'operator=='. 9150 FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, 9151 FunctionDecl *Spaceship); 9152 9153 ExprResult SubstInitializer(Expr *E, 9154 const MultiLevelTemplateArgumentList &TemplateArgs, 9155 bool CXXDirectInit); 9156 9157 bool 9158 SubstBaseSpecifiers(CXXRecordDecl *Instantiation, 9159 CXXRecordDecl *Pattern, 9160 const MultiLevelTemplateArgumentList &TemplateArgs); 9161 9162 bool 9163 InstantiateClass(SourceLocation PointOfInstantiation, 9164 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, 9165 const MultiLevelTemplateArgumentList &TemplateArgs, 9166 TemplateSpecializationKind TSK, 9167 bool Complain = true); 9168 9169 bool InstantiateEnum(SourceLocation PointOfInstantiation, 9170 EnumDecl *Instantiation, EnumDecl *Pattern, 9171 const MultiLevelTemplateArgumentList &TemplateArgs, 9172 TemplateSpecializationKind TSK); 9173 9174 bool InstantiateInClassInitializer( 9175 SourceLocation PointOfInstantiation, FieldDecl *Instantiation, 9176 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); 9177 9178 struct LateInstantiatedAttribute { 9179 const Attr *TmplAttr; 9180 LocalInstantiationScope *Scope; 9181 Decl *NewDecl; 9182 LateInstantiatedAttributeLateInstantiatedAttribute9183 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, 9184 Decl *D) 9185 : TmplAttr(A), Scope(S), NewDecl(D) 9186 { } 9187 }; 9188 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; 9189 9190 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, 9191 const Decl *Pattern, Decl *Inst, 9192 LateInstantiatedAttrVec *LateAttrs = nullptr, 9193 LocalInstantiationScope *OuterMostScope = nullptr); 9194 9195 void 9196 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, 9197 const Decl *Pattern, Decl *Inst, 9198 LateInstantiatedAttrVec *LateAttrs = nullptr, 9199 LocalInstantiationScope *OuterMostScope = nullptr); 9200 9201 void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor); 9202 9203 bool usesPartialOrExplicitSpecialization( 9204 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec); 9205 9206 bool 9207 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, 9208 ClassTemplateSpecializationDecl *ClassTemplateSpec, 9209 TemplateSpecializationKind TSK, 9210 bool Complain = true); 9211 9212 void InstantiateClassMembers(SourceLocation PointOfInstantiation, 9213 CXXRecordDecl *Instantiation, 9214 const MultiLevelTemplateArgumentList &TemplateArgs, 9215 TemplateSpecializationKind TSK); 9216 9217 void InstantiateClassTemplateSpecializationMembers( 9218 SourceLocation PointOfInstantiation, 9219 ClassTemplateSpecializationDecl *ClassTemplateSpec, 9220 TemplateSpecializationKind TSK); 9221 9222 NestedNameSpecifierLoc 9223 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 9224 const MultiLevelTemplateArgumentList &TemplateArgs); 9225 9226 DeclarationNameInfo 9227 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 9228 const MultiLevelTemplateArgumentList &TemplateArgs); 9229 TemplateName 9230 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, 9231 SourceLocation Loc, 9232 const MultiLevelTemplateArgumentList &TemplateArgs); 9233 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, 9234 TemplateArgumentListInfo &Result, 9235 const MultiLevelTemplateArgumentList &TemplateArgs); 9236 9237 bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, 9238 ParmVarDecl *Param); 9239 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, 9240 FunctionDecl *Function); 9241 bool CheckInstantiatedFunctionTemplateConstraints( 9242 SourceLocation PointOfInstantiation, FunctionDecl *Decl, 9243 ArrayRef<TemplateArgument> TemplateArgs, 9244 ConstraintSatisfaction &Satisfaction); 9245 FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, 9246 const TemplateArgumentList *Args, 9247 SourceLocation Loc); 9248 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 9249 FunctionDecl *Function, 9250 bool Recursive = false, 9251 bool DefinitionRequired = false, 9252 bool AtEndOfTU = false); 9253 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation( 9254 VarTemplateDecl *VarTemplate, VarDecl *FromVar, 9255 const TemplateArgumentList &TemplateArgList, 9256 const TemplateArgumentListInfo &TemplateArgsInfo, 9257 SmallVectorImpl<TemplateArgument> &Converted, 9258 SourceLocation PointOfInstantiation, 9259 LateInstantiatedAttrVec *LateAttrs = nullptr, 9260 LocalInstantiationScope *StartingScope = nullptr); 9261 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl( 9262 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, 9263 const MultiLevelTemplateArgumentList &TemplateArgs); 9264 void 9265 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, 9266 const MultiLevelTemplateArgumentList &TemplateArgs, 9267 LateInstantiatedAttrVec *LateAttrs, 9268 DeclContext *Owner, 9269 LocalInstantiationScope *StartingScope, 9270 bool InstantiatingVarTemplate = false, 9271 VarTemplateSpecializationDecl *PrevVTSD = nullptr); 9272 9273 void InstantiateVariableInitializer( 9274 VarDecl *Var, VarDecl *OldVar, 9275 const MultiLevelTemplateArgumentList &TemplateArgs); 9276 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, 9277 VarDecl *Var, bool Recursive = false, 9278 bool DefinitionRequired = false, 9279 bool AtEndOfTU = false); 9280 9281 void InstantiateMemInitializers(CXXConstructorDecl *New, 9282 const CXXConstructorDecl *Tmpl, 9283 const MultiLevelTemplateArgumentList &TemplateArgs); 9284 9285 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 9286 const MultiLevelTemplateArgumentList &TemplateArgs, 9287 bool FindingInstantiatedContext = false); 9288 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, 9289 const MultiLevelTemplateArgumentList &TemplateArgs); 9290 9291 // Objective-C declarations. 9292 enum ObjCContainerKind { 9293 OCK_None = -1, 9294 OCK_Interface = 0, 9295 OCK_Protocol, 9296 OCK_Category, 9297 OCK_ClassExtension, 9298 OCK_Implementation, 9299 OCK_CategoryImplementation 9300 }; 9301 ObjCContainerKind getObjCContainerKind() const; 9302 9303 DeclResult actOnObjCTypeParam(Scope *S, 9304 ObjCTypeParamVariance variance, 9305 SourceLocation varianceLoc, 9306 unsigned index, 9307 IdentifierInfo *paramName, 9308 SourceLocation paramLoc, 9309 SourceLocation colonLoc, 9310 ParsedType typeBound); 9311 9312 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc, 9313 ArrayRef<Decl *> typeParams, 9314 SourceLocation rAngleLoc); 9315 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList); 9316 9317 Decl *ActOnStartClassInterface( 9318 Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, 9319 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, 9320 IdentifierInfo *SuperName, SourceLocation SuperLoc, 9321 ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange, 9322 Decl *const *ProtoRefs, unsigned NumProtoRefs, 9323 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, 9324 const ParsedAttributesView &AttrList); 9325 9326 void ActOnSuperClassOfClassInterface(Scope *S, 9327 SourceLocation AtInterfaceLoc, 9328 ObjCInterfaceDecl *IDecl, 9329 IdentifierInfo *ClassName, 9330 SourceLocation ClassLoc, 9331 IdentifierInfo *SuperName, 9332 SourceLocation SuperLoc, 9333 ArrayRef<ParsedType> SuperTypeArgs, 9334 SourceRange SuperTypeArgsRange); 9335 9336 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, 9337 SmallVectorImpl<SourceLocation> &ProtocolLocs, 9338 IdentifierInfo *SuperName, 9339 SourceLocation SuperLoc); 9340 9341 Decl *ActOnCompatibilityAlias( 9342 SourceLocation AtCompatibilityAliasLoc, 9343 IdentifierInfo *AliasName, SourceLocation AliasLocation, 9344 IdentifierInfo *ClassName, SourceLocation ClassLocation); 9345 9346 bool CheckForwardProtocolDeclarationForCircularDependency( 9347 IdentifierInfo *PName, 9348 SourceLocation &PLoc, SourceLocation PrevLoc, 9349 const ObjCList<ObjCProtocolDecl> &PList); 9350 9351 Decl *ActOnStartProtocolInterface( 9352 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName, 9353 SourceLocation ProtocolLoc, Decl *const *ProtoRefNames, 9354 unsigned NumProtoRefs, const SourceLocation *ProtoLocs, 9355 SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); 9356 9357 Decl *ActOnStartCategoryInterface( 9358 SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, 9359 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, 9360 IdentifierInfo *CategoryName, SourceLocation CategoryLoc, 9361 Decl *const *ProtoRefs, unsigned NumProtoRefs, 9362 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, 9363 const ParsedAttributesView &AttrList); 9364 9365 Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc, 9366 IdentifierInfo *ClassName, 9367 SourceLocation ClassLoc, 9368 IdentifierInfo *SuperClassname, 9369 SourceLocation SuperClassLoc, 9370 const ParsedAttributesView &AttrList); 9371 9372 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, 9373 IdentifierInfo *ClassName, 9374 SourceLocation ClassLoc, 9375 IdentifierInfo *CatName, 9376 SourceLocation CatLoc, 9377 const ParsedAttributesView &AttrList); 9378 9379 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, 9380 ArrayRef<Decl *> Decls); 9381 9382 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, 9383 IdentifierInfo **IdentList, 9384 SourceLocation *IdentLocs, 9385 ArrayRef<ObjCTypeParamList *> TypeParamLists, 9386 unsigned NumElts); 9387 9388 DeclGroupPtrTy 9389 ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, 9390 ArrayRef<IdentifierLocPair> IdentList, 9391 const ParsedAttributesView &attrList); 9392 9393 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer, 9394 ArrayRef<IdentifierLocPair> ProtocolId, 9395 SmallVectorImpl<Decl *> &Protocols); 9396 9397 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId, 9398 SourceLocation ProtocolLoc, 9399 IdentifierInfo *TypeArgId, 9400 SourceLocation TypeArgLoc, 9401 bool SelectProtocolFirst = false); 9402 9403 /// Given a list of identifiers (and their locations), resolve the 9404 /// names to either Objective-C protocol qualifiers or type 9405 /// arguments, as appropriate. 9406 void actOnObjCTypeArgsOrProtocolQualifiers( 9407 Scope *S, 9408 ParsedType baseType, 9409 SourceLocation lAngleLoc, 9410 ArrayRef<IdentifierInfo *> identifiers, 9411 ArrayRef<SourceLocation> identifierLocs, 9412 SourceLocation rAngleLoc, 9413 SourceLocation &typeArgsLAngleLoc, 9414 SmallVectorImpl<ParsedType> &typeArgs, 9415 SourceLocation &typeArgsRAngleLoc, 9416 SourceLocation &protocolLAngleLoc, 9417 SmallVectorImpl<Decl *> &protocols, 9418 SourceLocation &protocolRAngleLoc, 9419 bool warnOnIncompleteProtocols); 9420 9421 /// Build a an Objective-C protocol-qualified 'id' type where no 9422 /// base type was specified. 9423 TypeResult actOnObjCProtocolQualifierType( 9424 SourceLocation lAngleLoc, 9425 ArrayRef<Decl *> protocols, 9426 ArrayRef<SourceLocation> protocolLocs, 9427 SourceLocation rAngleLoc); 9428 9429 /// Build a specialized and/or protocol-qualified Objective-C type. 9430 TypeResult actOnObjCTypeArgsAndProtocolQualifiers( 9431 Scope *S, 9432 SourceLocation Loc, 9433 ParsedType BaseType, 9434 SourceLocation TypeArgsLAngleLoc, 9435 ArrayRef<ParsedType> TypeArgs, 9436 SourceLocation TypeArgsRAngleLoc, 9437 SourceLocation ProtocolLAngleLoc, 9438 ArrayRef<Decl *> Protocols, 9439 ArrayRef<SourceLocation> ProtocolLocs, 9440 SourceLocation ProtocolRAngleLoc); 9441 9442 /// Build an Objective-C type parameter type. 9443 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, 9444 SourceLocation ProtocolLAngleLoc, 9445 ArrayRef<ObjCProtocolDecl *> Protocols, 9446 ArrayRef<SourceLocation> ProtocolLocs, 9447 SourceLocation ProtocolRAngleLoc, 9448 bool FailOnError = false); 9449 9450 /// Build an Objective-C object pointer type. 9451 QualType BuildObjCObjectType(QualType BaseType, 9452 SourceLocation Loc, 9453 SourceLocation TypeArgsLAngleLoc, 9454 ArrayRef<TypeSourceInfo *> TypeArgs, 9455 SourceLocation TypeArgsRAngleLoc, 9456 SourceLocation ProtocolLAngleLoc, 9457 ArrayRef<ObjCProtocolDecl *> Protocols, 9458 ArrayRef<SourceLocation> ProtocolLocs, 9459 SourceLocation ProtocolRAngleLoc, 9460 bool FailOnError = false); 9461 9462 /// Ensure attributes are consistent with type. 9463 /// \param [in, out] Attributes The attributes to check; they will 9464 /// be modified to be consistent with \p PropertyTy. 9465 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, 9466 SourceLocation Loc, 9467 unsigned &Attributes, 9468 bool propertyInPrimaryClass); 9469 9470 /// Process the specified property declaration and create decls for the 9471 /// setters and getters as needed. 9472 /// \param property The property declaration being processed 9473 void ProcessPropertyDecl(ObjCPropertyDecl *property); 9474 9475 9476 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, 9477 ObjCPropertyDecl *SuperProperty, 9478 const IdentifierInfo *Name, 9479 bool OverridingProtocolProperty); 9480 9481 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, 9482 ObjCInterfaceDecl *ID); 9483 9484 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, 9485 ArrayRef<Decl *> allMethods = None, 9486 ArrayRef<DeclGroupPtrTy> allTUVars = None); 9487 9488 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, 9489 SourceLocation LParenLoc, 9490 FieldDeclarator &FD, ObjCDeclSpec &ODS, 9491 Selector GetterSel, Selector SetterSel, 9492 tok::ObjCKeywordKind MethodImplKind, 9493 DeclContext *lexicalDC = nullptr); 9494 9495 Decl *ActOnPropertyImplDecl(Scope *S, 9496 SourceLocation AtLoc, 9497 SourceLocation PropertyLoc, 9498 bool ImplKind, 9499 IdentifierInfo *PropertyId, 9500 IdentifierInfo *PropertyIvar, 9501 SourceLocation PropertyIvarLoc, 9502 ObjCPropertyQueryKind QueryKind); 9503 9504 enum ObjCSpecialMethodKind { 9505 OSMK_None, 9506 OSMK_Alloc, 9507 OSMK_New, 9508 OSMK_Copy, 9509 OSMK_RetainingInit, 9510 OSMK_NonRetainingInit 9511 }; 9512 9513 struct ObjCArgInfo { 9514 IdentifierInfo *Name; 9515 SourceLocation NameLoc; 9516 // The Type is null if no type was specified, and the DeclSpec is invalid 9517 // in this case. 9518 ParsedType Type; 9519 ObjCDeclSpec DeclSpec; 9520 9521 /// ArgAttrs - Attribute list for this argument. 9522 ParsedAttributesView ArgAttrs; 9523 }; 9524 9525 Decl *ActOnMethodDeclaration( 9526 Scope *S, 9527 SourceLocation BeginLoc, // location of the + or -. 9528 SourceLocation EndLoc, // location of the ; or {. 9529 tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType, 9530 ArrayRef<SourceLocation> SelectorLocs, Selector Sel, 9531 // optional arguments. The number of types/arguments is obtained 9532 // from the Sel.getNumArgs(). 9533 ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo, 9534 unsigned CNumArgs, // c-style args 9535 const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind, 9536 bool isVariadic, bool MethodDefinition); 9537 9538 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, 9539 const ObjCObjectPointerType *OPT, 9540 bool IsInstance); 9541 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, 9542 bool IsInstance); 9543 9544 bool CheckARCMethodDecl(ObjCMethodDecl *method); 9545 bool inferObjCARCLifetime(ValueDecl *decl); 9546 9547 void deduceOpenCLAddressSpace(ValueDecl *decl); 9548 9549 ExprResult 9550 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, 9551 Expr *BaseExpr, 9552 SourceLocation OpLoc, 9553 DeclarationName MemberName, 9554 SourceLocation MemberLoc, 9555 SourceLocation SuperLoc, QualType SuperType, 9556 bool Super); 9557 9558 ExprResult 9559 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, 9560 IdentifierInfo &propertyName, 9561 SourceLocation receiverNameLoc, 9562 SourceLocation propertyNameLoc); 9563 9564 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); 9565 9566 /// Describes the kind of message expression indicated by a message 9567 /// send that starts with an identifier. 9568 enum ObjCMessageKind { 9569 /// The message is sent to 'super'. 9570 ObjCSuperMessage, 9571 /// The message is an instance message. 9572 ObjCInstanceMessage, 9573 /// The message is a class message, and the identifier is a type 9574 /// name. 9575 ObjCClassMessage 9576 }; 9577 9578 ObjCMessageKind getObjCMessageKind(Scope *S, 9579 IdentifierInfo *Name, 9580 SourceLocation NameLoc, 9581 bool IsSuper, 9582 bool HasTrailingDot, 9583 ParsedType &ReceiverType); 9584 9585 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, 9586 Selector Sel, 9587 SourceLocation LBracLoc, 9588 ArrayRef<SourceLocation> SelectorLocs, 9589 SourceLocation RBracLoc, 9590 MultiExprArg Args); 9591 9592 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, 9593 QualType ReceiverType, 9594 SourceLocation SuperLoc, 9595 Selector Sel, 9596 ObjCMethodDecl *Method, 9597 SourceLocation LBracLoc, 9598 ArrayRef<SourceLocation> SelectorLocs, 9599 SourceLocation RBracLoc, 9600 MultiExprArg Args, 9601 bool isImplicit = false); 9602 9603 ExprResult BuildClassMessageImplicit(QualType ReceiverType, 9604 bool isSuperReceiver, 9605 SourceLocation Loc, 9606 Selector Sel, 9607 ObjCMethodDecl *Method, 9608 MultiExprArg Args); 9609 9610 ExprResult ActOnClassMessage(Scope *S, 9611 ParsedType Receiver, 9612 Selector Sel, 9613 SourceLocation LBracLoc, 9614 ArrayRef<SourceLocation> SelectorLocs, 9615 SourceLocation RBracLoc, 9616 MultiExprArg Args); 9617 9618 ExprResult BuildInstanceMessage(Expr *Receiver, 9619 QualType ReceiverType, 9620 SourceLocation SuperLoc, 9621 Selector Sel, 9622 ObjCMethodDecl *Method, 9623 SourceLocation LBracLoc, 9624 ArrayRef<SourceLocation> SelectorLocs, 9625 SourceLocation RBracLoc, 9626 MultiExprArg Args, 9627 bool isImplicit = false); 9628 9629 ExprResult BuildInstanceMessageImplicit(Expr *Receiver, 9630 QualType ReceiverType, 9631 SourceLocation Loc, 9632 Selector Sel, 9633 ObjCMethodDecl *Method, 9634 MultiExprArg Args); 9635 9636 ExprResult ActOnInstanceMessage(Scope *S, 9637 Expr *Receiver, 9638 Selector Sel, 9639 SourceLocation LBracLoc, 9640 ArrayRef<SourceLocation> SelectorLocs, 9641 SourceLocation RBracLoc, 9642 MultiExprArg Args); 9643 9644 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, 9645 ObjCBridgeCastKind Kind, 9646 SourceLocation BridgeKeywordLoc, 9647 TypeSourceInfo *TSInfo, 9648 Expr *SubExpr); 9649 9650 ExprResult ActOnObjCBridgedCast(Scope *S, 9651 SourceLocation LParenLoc, 9652 ObjCBridgeCastKind Kind, 9653 SourceLocation BridgeKeywordLoc, 9654 ParsedType Type, 9655 SourceLocation RParenLoc, 9656 Expr *SubExpr); 9657 9658 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr); 9659 9660 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr); 9661 9662 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, 9663 CastKind &Kind); 9664 9665 bool checkObjCBridgeRelatedComponents(SourceLocation Loc, 9666 QualType DestType, QualType SrcType, 9667 ObjCInterfaceDecl *&RelatedClass, 9668 ObjCMethodDecl *&ClassMethod, 9669 ObjCMethodDecl *&InstanceMethod, 9670 TypedefNameDecl *&TDNDecl, 9671 bool CfToNs, bool Diagnose = true); 9672 9673 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, 9674 QualType DestType, QualType SrcType, 9675 Expr *&SrcExpr, bool Diagnose = true); 9676 9677 bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr, 9678 bool Diagnose = true); 9679 9680 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); 9681 9682 /// Check whether the given new method is a valid override of the 9683 /// given overridden method, and set any properties that should be inherited. 9684 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, 9685 const ObjCMethodDecl *Overridden); 9686 9687 /// Describes the compatibility of a result type with its method. 9688 enum ResultTypeCompatibilityKind { 9689 RTC_Compatible, 9690 RTC_Incompatible, 9691 RTC_Unknown 9692 }; 9693 9694 void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method, 9695 ObjCMethodDecl *overridden); 9696 9697 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, 9698 ObjCInterfaceDecl *CurrentClass, 9699 ResultTypeCompatibilityKind RTC); 9700 9701 enum PragmaOptionsAlignKind { 9702 POAK_Native, // #pragma options align=native 9703 POAK_Natural, // #pragma options align=natural 9704 POAK_Packed, // #pragma options align=packed 9705 POAK_Power, // #pragma options align=power 9706 POAK_Mac68k, // #pragma options align=mac68k 9707 POAK_Reset // #pragma options align=reset 9708 }; 9709 9710 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section 9711 void ActOnPragmaClangSection(SourceLocation PragmaLoc, 9712 PragmaClangSectionAction Action, 9713 PragmaClangSectionKind SecKind, StringRef SecName); 9714 9715 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. 9716 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, 9717 SourceLocation PragmaLoc); 9718 9719 /// ActOnPragmaPack - Called on well formed \#pragma pack(...). 9720 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, 9721 StringRef SlotLabel, Expr *Alignment); 9722 9723 enum class PragmaPackDiagnoseKind { 9724 NonDefaultStateAtInclude, 9725 ChangedStateAtExit 9726 }; 9727 9728 void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind, 9729 SourceLocation IncludeLoc); 9730 void DiagnoseUnterminatedPragmaPack(); 9731 9732 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. 9733 void ActOnPragmaMSStruct(PragmaMSStructKind Kind); 9734 9735 /// ActOnPragmaMSComment - Called on well formed 9736 /// \#pragma comment(kind, "arg"). 9737 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind, 9738 StringRef Arg); 9739 9740 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma 9741 /// pointers_to_members(representation method[, general purpose 9742 /// representation]). 9743 void ActOnPragmaMSPointersToMembers( 9744 LangOptions::PragmaMSPointersToMembersKind Kind, 9745 SourceLocation PragmaLoc); 9746 9747 /// Called on well formed \#pragma vtordisp(). 9748 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, 9749 SourceLocation PragmaLoc, 9750 MSVtorDispMode Value); 9751 9752 enum PragmaSectionKind { 9753 PSK_DataSeg, 9754 PSK_BSSSeg, 9755 PSK_ConstSeg, 9756 PSK_CodeSeg, 9757 }; 9758 9759 bool UnifySection(StringRef SectionName, 9760 int SectionFlags, 9761 DeclaratorDecl *TheDecl); 9762 bool UnifySection(StringRef SectionName, 9763 int SectionFlags, 9764 SourceLocation PragmaSectionLocation); 9765 9766 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg. 9767 void ActOnPragmaMSSeg(SourceLocation PragmaLocation, 9768 PragmaMsStackAction Action, 9769 llvm::StringRef StackSlotLabel, 9770 StringLiteral *SegmentName, 9771 llvm::StringRef PragmaName); 9772 9773 /// Called on well formed \#pragma section(). 9774 void ActOnPragmaMSSection(SourceLocation PragmaLocation, 9775 int SectionFlags, StringLiteral *SegmentName); 9776 9777 /// Called on well-formed \#pragma init_seg(). 9778 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, 9779 StringLiteral *SegmentName); 9780 9781 /// Called on #pragma clang __debug dump II 9782 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II); 9783 9784 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch 9785 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, 9786 StringRef Value); 9787 9788 /// Are precise floating point semantics currently enabled? isPreciseFPEnabled()9789 bool isPreciseFPEnabled() { 9790 return !CurFPFeatures.getAllowFPReassociate() && 9791 !CurFPFeatures.getNoSignedZero() && 9792 !CurFPFeatures.getAllowReciprocal() && 9793 !CurFPFeatures.getAllowApproxFunc(); 9794 } 9795 9796 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control 9797 void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action, 9798 PragmaFloatControlKind Value); 9799 9800 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. 9801 void ActOnPragmaUnused(const Token &Identifier, 9802 Scope *curScope, 9803 SourceLocation PragmaLoc); 9804 9805 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . 9806 void ActOnPragmaVisibility(const IdentifierInfo* VisType, 9807 SourceLocation PragmaLoc); 9808 9809 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, 9810 SourceLocation Loc); 9811 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); 9812 9813 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. 9814 void ActOnPragmaWeakID(IdentifierInfo* WeakName, 9815 SourceLocation PragmaLoc, 9816 SourceLocation WeakNameLoc); 9817 9818 /// ActOnPragmaRedefineExtname - Called on well formed 9819 /// \#pragma redefine_extname oldname newname. 9820 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, 9821 IdentifierInfo* AliasName, 9822 SourceLocation PragmaLoc, 9823 SourceLocation WeakNameLoc, 9824 SourceLocation AliasNameLoc); 9825 9826 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. 9827 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, 9828 IdentifierInfo* AliasName, 9829 SourceLocation PragmaLoc, 9830 SourceLocation WeakNameLoc, 9831 SourceLocation AliasNameLoc); 9832 9833 /// ActOnPragmaFPContract - Called on well formed 9834 /// \#pragma {STDC,OPENCL} FP_CONTRACT and 9835 /// \#pragma clang fp contract 9836 void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC); 9837 9838 /// Called on well formed 9839 /// \#pragma clang fp reassociate 9840 void ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled); 9841 9842 /// ActOnPragmaFenvAccess - Called on well formed 9843 /// \#pragma STDC FENV_ACCESS 9844 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled); 9845 9846 /// Called on well formed '\#pragma clang fp' that has option 'exceptions'. 9847 void ActOnPragmaFPExceptions(SourceLocation Loc, 9848 LangOptions::FPExceptionModeKind); 9849 9850 /// Called to set constant rounding mode for floating point operations. 9851 void setRoundingMode(SourceLocation Loc, llvm::RoundingMode); 9852 9853 /// Called to set exception behavior for floating point operations. 9854 void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind); 9855 9856 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to 9857 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. 9858 void AddAlignmentAttributesForRecord(RecordDecl *RD); 9859 9860 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. 9861 void AddMsStructLayoutForRecord(RecordDecl *RD); 9862 9863 /// PushNamespaceVisibilityAttr - Note that we've entered a 9864 /// namespace with a visibility attribute. 9865 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, 9866 SourceLocation Loc); 9867 9868 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, 9869 /// add an appropriate visibility attribute. 9870 void AddPushedVisibilityAttribute(Decl *RD); 9871 9872 /// PopPragmaVisibility - Pop the top element of the visibility stack; used 9873 /// for '\#pragma GCC visibility' and visibility attributes on namespaces. 9874 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); 9875 9876 /// FreeVisContext - Deallocate and null out VisContext. 9877 void FreeVisContext(); 9878 9879 /// AddCFAuditedAttribute - Check whether we're currently within 9880 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding 9881 /// the appropriate attribute. 9882 void AddCFAuditedAttribute(Decl *D); 9883 9884 void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, 9885 SourceLocation PragmaLoc, 9886 attr::ParsedSubjectMatchRuleSet Rules); 9887 void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc, 9888 const IdentifierInfo *Namespace); 9889 9890 /// Called on well-formed '\#pragma clang attribute pop'. 9891 void ActOnPragmaAttributePop(SourceLocation PragmaLoc, 9892 const IdentifierInfo *Namespace); 9893 9894 /// Adds the attributes that have been specified using the 9895 /// '\#pragma clang attribute push' directives to the given declaration. 9896 void AddPragmaAttributes(Scope *S, Decl *D); 9897 9898 void DiagnoseUnterminatedPragmaAttribute(); 9899 9900 /// Called on well formed \#pragma clang optimize. 9901 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); 9902 9903 /// Get the location for the currently active "\#pragma clang optimize 9904 /// off". If this location is invalid, then the state of the pragma is "on". getOptimizeOffPragmaLocation()9905 SourceLocation getOptimizeOffPragmaLocation() const { 9906 return OptimizeOffPragmaLocation; 9907 } 9908 9909 /// Only called on function definitions; if there is a pragma in scope 9910 /// with the effect of a range-based optnone, consider marking the function 9911 /// with attribute optnone. 9912 void AddRangeBasedOptnone(FunctionDecl *FD); 9913 9914 /// Adds the 'optnone' attribute to the function declaration if there 9915 /// are no conflicts; Loc represents the location causing the 'optnone' 9916 /// attribute to be added (usually because of a pragma). 9917 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc); 9918 9919 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. 9920 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, 9921 bool IsPackExpansion); 9922 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T, 9923 bool IsPackExpansion); 9924 9925 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular 9926 /// declaration. 9927 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, 9928 Expr *OE); 9929 9930 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular 9931 /// declaration. 9932 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, 9933 Expr *ParamExpr); 9934 9935 /// AddAlignValueAttr - Adds an align_value attribute to a particular 9936 /// declaration. 9937 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); 9938 9939 /// AddAnnotationAttr - Adds an annotation Annot with Args arguments to D. 9940 void AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI, 9941 StringRef Annot, MutableArrayRef<Expr *> Args); 9942 9943 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular 9944 /// declaration. 9945 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, 9946 Expr *MaxThreads, Expr *MinBlocks); 9947 9948 /// AddModeAttr - Adds a mode attribute to a particular declaration. 9949 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name, 9950 bool InInstantiation = false); 9951 9952 void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI, 9953 ParameterABI ABI); 9954 9955 enum class RetainOwnershipKind {NS, CF, OS}; 9956 void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI, 9957 RetainOwnershipKind K, bool IsTemplateInstantiation); 9958 9959 /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size 9960 /// attribute to a particular declaration. 9961 void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, 9962 Expr *Min, Expr *Max); 9963 9964 /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a 9965 /// particular declaration. 9966 void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, 9967 Expr *Min, Expr *Max); 9968 9969 bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type); 9970 9971 //===--------------------------------------------------------------------===// 9972 // C++ Coroutines TS 9973 // 9974 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, 9975 StringRef Keyword); 9976 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E); 9977 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E); 9978 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E); 9979 9980 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, 9981 bool IsImplicit = false); 9982 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, 9983 UnresolvedLookupExpr* Lookup); 9984 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E); 9985 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, 9986 bool IsImplicit = false); 9987 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs); 9988 bool buildCoroutineParameterMoves(SourceLocation Loc); 9989 VarDecl *buildCoroutinePromise(SourceLocation Loc); 9990 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body); 9991 ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc, 9992 SourceLocation FuncLoc); 9993 /// Check that the expression co_await promise.final_suspend() shall not be 9994 /// potentially-throwing. 9995 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend); 9996 9997 //===--------------------------------------------------------------------===// 9998 // OpenCL extensions. 9999 // 10000 private: 10001 std::string CurrOpenCLExtension; 10002 /// Extensions required by an OpenCL type. 10003 llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap; 10004 /// Extensions required by an OpenCL declaration. 10005 llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap; 10006 public: getCurrentOpenCLExtension()10007 llvm::StringRef getCurrentOpenCLExtension() const { 10008 return CurrOpenCLExtension; 10009 } 10010 10011 /// Check if a function declaration \p FD associates with any 10012 /// extensions present in OpenCLDeclExtMap and if so return the 10013 /// extension(s) name(s). 10014 std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD); 10015 10016 /// Check if a function type \p FT associates with any 10017 /// extensions present in OpenCLTypeExtMap and if so return the 10018 /// extension(s) name(s). 10019 std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT); 10020 10021 /// Find an extension in an appropriate extension map and return its name 10022 template<typename T, typename MapT> 10023 std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map); 10024 setCurrentOpenCLExtension(llvm::StringRef Ext)10025 void setCurrentOpenCLExtension(llvm::StringRef Ext) { 10026 CurrOpenCLExtension = std::string(Ext); 10027 } 10028 10029 /// Set OpenCL extensions for a type which can only be used when these 10030 /// OpenCL extensions are enabled. If \p Exts is empty, do nothing. 10031 /// \param Exts A space separated list of OpenCL extensions. 10032 void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts); 10033 10034 /// Set OpenCL extensions for a declaration which can only be 10035 /// used when these OpenCL extensions are enabled. If \p Exts is empty, do 10036 /// nothing. 10037 /// \param Exts A space separated list of OpenCL extensions. 10038 void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts); 10039 10040 /// Set current OpenCL extensions for a type which can only be used 10041 /// when these OpenCL extensions are enabled. If current OpenCL extension is 10042 /// empty, do nothing. 10043 void setCurrentOpenCLExtensionForType(QualType T); 10044 10045 /// Set current OpenCL extensions for a declaration which 10046 /// can only be used when these OpenCL extensions are enabled. If current 10047 /// OpenCL extension is empty, do nothing. 10048 void setCurrentOpenCLExtensionForDecl(Decl *FD); 10049 10050 bool isOpenCLDisabledDecl(Decl *FD); 10051 10052 /// Check if type \p T corresponding to declaration specifier \p DS 10053 /// is disabled due to required OpenCL extensions being disabled. If so, 10054 /// emit diagnostics. 10055 /// \return true if type is disabled. 10056 bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T); 10057 10058 /// Check if declaration \p D used by expression \p E 10059 /// is disabled due to required OpenCL extensions being disabled. If so, 10060 /// emit diagnostics. 10061 /// \return true if type is disabled. 10062 bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E); 10063 10064 //===--------------------------------------------------------------------===// 10065 // OpenMP directives and clauses. 10066 // 10067 private: 10068 void *VarDataSharingAttributesStack; 10069 /// Number of nested '#pragma omp declare target' directives. 10070 SmallVector<SourceLocation, 4> DeclareTargetNesting; 10071 /// Initialization of data-sharing attributes stack. 10072 void InitDataSharingAttributesStack(); 10073 void DestroyDataSharingAttributesStack(); 10074 ExprResult 10075 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind, 10076 bool StrictlyPositive = true); 10077 /// Returns OpenMP nesting level for current directive. 10078 unsigned getOpenMPNestingLevel() const; 10079 10080 /// Adjusts the function scopes index for the target-based regions. 10081 void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, 10082 unsigned Level) const; 10083 10084 /// Returns the number of scopes associated with the construct on the given 10085 /// OpenMP level. 10086 int getNumberOfConstructScopes(unsigned Level) const; 10087 10088 /// Push new OpenMP function region for non-capturing function. 10089 void pushOpenMPFunctionRegion(); 10090 10091 /// Pop OpenMP function region for non-capturing function. 10092 void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI); 10093 10094 /// Checks if a type or a declaration is disabled due to the owning extension 10095 /// being disabled, and emits diagnostic messages if it is disabled. 10096 /// \param D type or declaration to be checked. 10097 /// \param DiagLoc source location for the diagnostic message. 10098 /// \param DiagInfo information to be emitted for the diagnostic message. 10099 /// \param SrcRange source range of the declaration. 10100 /// \param Map maps type or declaration to the extensions. 10101 /// \param Selector selects diagnostic message: 0 for type and 1 for 10102 /// declaration. 10103 /// \return true if the type or declaration is disabled. 10104 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT> 10105 bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo, 10106 MapT &Map, unsigned Selector = 0, 10107 SourceRange SrcRange = SourceRange()); 10108 10109 /// Helper to keep information about the current `omp begin/end declare 10110 /// variant` nesting. 10111 struct OMPDeclareVariantScope { 10112 /// The associated OpenMP context selector. 10113 OMPTraitInfo *TI; 10114 10115 /// The associated OpenMP context selector mangling. 10116 std::string NameSuffix; 10117 10118 OMPDeclareVariantScope(OMPTraitInfo &TI); 10119 }; 10120 10121 /// Return the OMPTraitInfo for the surrounding scope, if any. getOMPTraitInfoForSurroundingScope()10122 OMPTraitInfo *getOMPTraitInfoForSurroundingScope() { 10123 return OMPDeclareVariantScopes.empty() ? nullptr 10124 : OMPDeclareVariantScopes.back().TI; 10125 } 10126 10127 /// The current `omp begin/end declare variant` scopes. 10128 SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes; 10129 10130 /// The declarator \p D defines a function in the scope \p S which is nested 10131 /// in an `omp begin/end declare variant` scope. In this method we create a 10132 /// declaration for \p D and rename \p D according to the OpenMP context 10133 /// selector of the surrounding scope. Return all base functions in \p Bases. 10134 void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 10135 Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, 10136 SmallVectorImpl<FunctionDecl *> &Bases); 10137 10138 /// Register \p D as specialization of all base functions in \p Bases in the 10139 /// current `omp begin/end declare variant` scope. 10140 void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( 10141 Decl *D, SmallVectorImpl<FunctionDecl *> &Bases); 10142 10143 public: 10144 10145 /// Can we exit a scope at the moment. isInOpenMPDeclareVariantScope()10146 bool isInOpenMPDeclareVariantScope() { 10147 return !OMPDeclareVariantScopes.empty(); 10148 } 10149 10150 /// Given the potential call expression \p Call, determine if there is a 10151 /// specialization via the OpenMP declare variant mechanism available. If 10152 /// there is, return the specialized call expression, otherwise return the 10153 /// original \p Call. 10154 ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope, 10155 SourceLocation LParenLoc, MultiExprArg ArgExprs, 10156 SourceLocation RParenLoc, Expr *ExecConfig); 10157 10158 /// Handle a `omp begin declare variant`. 10159 void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI); 10160 10161 /// Handle a `omp end declare variant`. 10162 void ActOnOpenMPEndDeclareVariant(); 10163 10164 /// Checks if the variant/multiversion functions are compatible. 10165 bool areMultiversionVariantFunctionsCompatible( 10166 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10167 const PartialDiagnostic &NoProtoDiagID, 10168 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10169 const PartialDiagnosticAt &NoSupportDiagIDAt, 10170 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10171 bool ConstexprSupported, bool CLinkageMayDiffer); 10172 10173 /// Function tries to capture lambda's captured variables in the OpenMP region 10174 /// before the original lambda is captured. 10175 void tryCaptureOpenMPLambdas(ValueDecl *V); 10176 10177 /// Return true if the provided declaration \a VD should be captured by 10178 /// reference. 10179 /// \param Level Relative level of nested OpenMP construct for that the check 10180 /// is performed. 10181 /// \param OpenMPCaptureLevel Capture level within an OpenMP construct. 10182 bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, 10183 unsigned OpenMPCaptureLevel) const; 10184 10185 /// Check if the specified variable is used in one of the private 10186 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP 10187 /// constructs. 10188 VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false, 10189 unsigned StopAt = 0); 10190 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 10191 ExprObjectKind OK, SourceLocation Loc); 10192 10193 /// If the current region is a loop-based region, mark the start of the loop 10194 /// construct. 10195 void startOpenMPLoop(); 10196 10197 /// If the current region is a range loop-based region, mark the start of the 10198 /// loop construct. 10199 void startOpenMPCXXRangeFor(); 10200 10201 /// Check if the specified variable is used in 'private' clause. 10202 /// \param Level Relative level of nested OpenMP construct for that the check 10203 /// is performed. 10204 OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, 10205 unsigned CapLevel) const; 10206 10207 /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.) 10208 /// for \p FD based on DSA for the provided corresponding captured declaration 10209 /// \p D. 10210 void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level); 10211 10212 /// Check if the specified variable is captured by 'target' directive. 10213 /// \param Level Relative level of nested OpenMP construct for that the check 10214 /// is performed. 10215 bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, 10216 unsigned CaptureLevel) const; 10217 10218 /// Check if the specified global variable must be captured by outer capture 10219 /// regions. 10220 /// \param Level Relative level of nested OpenMP construct for that 10221 /// the check is performed. 10222 bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, 10223 unsigned CaptureLevel) const; 10224 10225 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc, 10226 Expr *Op); 10227 /// Called on start of new data sharing attribute block. 10228 void StartOpenMPDSABlock(OpenMPDirectiveKind K, 10229 const DeclarationNameInfo &DirName, Scope *CurScope, 10230 SourceLocation Loc); 10231 /// Start analysis of clauses. 10232 void StartOpenMPClause(OpenMPClauseKind K); 10233 /// End analysis of clauses. 10234 void EndOpenMPClause(); 10235 /// Called on end of data sharing attribute block. 10236 void EndOpenMPDSABlock(Stmt *CurDirective); 10237 10238 /// Check if the current region is an OpenMP loop region and if it is, 10239 /// mark loop control variable, used in \p Init for loop initialization, as 10240 /// private by default. 10241 /// \param Init First part of the for loop. 10242 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init); 10243 10244 // OpenMP directives and clauses. 10245 /// Called on correct id-expression from the '#pragma omp 10246 /// threadprivate'. 10247 ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec, 10248 const DeclarationNameInfo &Id, 10249 OpenMPDirectiveKind Kind); 10250 /// Called on well-formed '#pragma omp threadprivate'. 10251 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective( 10252 SourceLocation Loc, 10253 ArrayRef<Expr *> VarList); 10254 /// Builds a new OpenMPThreadPrivateDecl and checks its correctness. 10255 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc, 10256 ArrayRef<Expr *> VarList); 10257 /// Called on well-formed '#pragma omp allocate'. 10258 DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc, 10259 ArrayRef<Expr *> VarList, 10260 ArrayRef<OMPClause *> Clauses, 10261 DeclContext *Owner = nullptr); 10262 /// Called on well-formed '#pragma omp requires'. 10263 DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc, 10264 ArrayRef<OMPClause *> ClauseList); 10265 /// Check restrictions on Requires directive 10266 OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc, 10267 ArrayRef<OMPClause *> Clauses); 10268 /// Check if the specified type is allowed to be used in 'omp declare 10269 /// reduction' construct. 10270 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 10271 TypeResult ParsedType); 10272 /// Called on start of '#pragma omp declare reduction'. 10273 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart( 10274 Scope *S, DeclContext *DC, DeclarationName Name, 10275 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 10276 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); 10277 /// Initialize declare reduction construct initializer. 10278 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D); 10279 /// Finish current declare reduction construct initializer. 10280 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner); 10281 /// Initialize declare reduction construct initializer. 10282 /// \return omp_priv variable. 10283 VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D); 10284 /// Finish current declare reduction construct initializer. 10285 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, 10286 VarDecl *OmpPrivParm); 10287 /// Called at the end of '#pragma omp declare reduction'. 10288 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd( 10289 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid); 10290 10291 /// Check variable declaration in 'omp declare mapper' construct. 10292 TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D); 10293 /// Check if the specified type is allowed to be used in 'omp declare 10294 /// mapper' construct. 10295 QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, 10296 TypeResult ParsedType); 10297 /// Called on start of '#pragma omp declare mapper'. 10298 DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective( 10299 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, 10300 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, 10301 Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, 10302 Decl *PrevDeclInScope = nullptr); 10303 /// Build the mapper variable of '#pragma omp declare mapper'. 10304 ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, 10305 QualType MapperType, 10306 SourceLocation StartLoc, 10307 DeclarationName VN); 10308 bool isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const; 10309 const ValueDecl *getOpenMPDeclareMapperVarName() const; 10310 10311 /// Called on the start of target region i.e. '#pragma omp declare target'. 10312 bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc); 10313 /// Called at the end of target region i.e. '#pragme omp end declare target'. 10314 void ActOnFinishOpenMPDeclareTargetDirective(); 10315 /// Searches for the provided declaration name for OpenMP declare target 10316 /// directive. 10317 NamedDecl * 10318 lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, 10319 const DeclarationNameInfo &Id, 10320 NamedDeclSetType &SameDirectiveDecls); 10321 /// Called on correct id-expression from the '#pragma omp declare target'. 10322 void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc, 10323 OMPDeclareTargetDeclAttr::MapTypeTy MT, 10324 OMPDeclareTargetDeclAttr::DevTypeTy DT); 10325 /// Check declaration inside target region. 10326 void 10327 checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, 10328 SourceLocation IdLoc = SourceLocation()); 10329 /// Finishes analysis of the deferred functions calls that may be declared as 10330 /// host/nohost during device/host compilation. 10331 void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller, 10332 const FunctionDecl *Callee, 10333 SourceLocation Loc); 10334 /// Return true inside OpenMP declare target region. isInOpenMPDeclareTargetContext()10335 bool isInOpenMPDeclareTargetContext() const { 10336 return !DeclareTargetNesting.empty(); 10337 } 10338 /// Return true inside OpenMP target region. 10339 bool isInOpenMPTargetExecutionDirective() const; 10340 10341 /// Return the number of captured regions created for an OpenMP directive. 10342 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind); 10343 10344 /// Initialization of captured region for OpenMP region. 10345 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope); 10346 /// End of OpenMP region. 10347 /// 10348 /// \param S Statement associated with the current OpenMP region. 10349 /// \param Clauses List of clauses for the current OpenMP region. 10350 /// 10351 /// \returns Statement for finished OpenMP region. 10352 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses); 10353 StmtResult ActOnOpenMPExecutableDirective( 10354 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 10355 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 10356 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); 10357 /// Called on well-formed '\#pragma omp parallel' after parsing 10358 /// of the associated statement. 10359 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 10360 Stmt *AStmt, 10361 SourceLocation StartLoc, 10362 SourceLocation EndLoc); 10363 using VarsWithInheritedDSAType = 10364 llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>; 10365 /// Called on well-formed '\#pragma omp simd' after parsing 10366 /// of the associated statement. 10367 StmtResult 10368 ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 10369 SourceLocation StartLoc, SourceLocation EndLoc, 10370 VarsWithInheritedDSAType &VarsWithImplicitDSA); 10371 /// Called on well-formed '\#pragma omp for' after parsing 10372 /// of the associated statement. 10373 StmtResult 10374 ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 10375 SourceLocation StartLoc, SourceLocation EndLoc, 10376 VarsWithInheritedDSAType &VarsWithImplicitDSA); 10377 /// Called on well-formed '\#pragma omp for simd' after parsing 10378 /// of the associated statement. 10379 StmtResult 10380 ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 10381 SourceLocation StartLoc, SourceLocation EndLoc, 10382 VarsWithInheritedDSAType &VarsWithImplicitDSA); 10383 /// Called on well-formed '\#pragma omp sections' after parsing 10384 /// of the associated statement. 10385 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 10386 Stmt *AStmt, SourceLocation StartLoc, 10387 SourceLocation EndLoc); 10388 /// Called on well-formed '\#pragma omp section' after parsing of the 10389 /// associated statement. 10390 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc, 10391 SourceLocation EndLoc); 10392 /// Called on well-formed '\#pragma omp single' after parsing of the 10393 /// associated statement. 10394 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 10395 Stmt *AStmt, SourceLocation StartLoc, 10396 SourceLocation EndLoc); 10397 /// Called on well-formed '\#pragma omp master' after parsing of the 10398 /// associated statement. 10399 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc, 10400 SourceLocation EndLoc); 10401 /// Called on well-formed '\#pragma omp critical' after parsing of the 10402 /// associated statement. 10403 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, 10404 ArrayRef<OMPClause *> Clauses, 10405 Stmt *AStmt, SourceLocation StartLoc, 10406 SourceLocation EndLoc); 10407 /// Called on well-formed '\#pragma omp parallel for' after parsing 10408 /// of the associated statement. 10409 StmtResult ActOnOpenMPParallelForDirective( 10410 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10411 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10412 /// Called on well-formed '\#pragma omp parallel for simd' after 10413 /// parsing of the associated statement. 10414 StmtResult ActOnOpenMPParallelForSimdDirective( 10415 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10416 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10417 /// Called on well-formed '\#pragma omp parallel master' after 10418 /// parsing of the associated statement. 10419 StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses, 10420 Stmt *AStmt, 10421 SourceLocation StartLoc, 10422 SourceLocation EndLoc); 10423 /// Called on well-formed '\#pragma omp parallel sections' after 10424 /// parsing of the associated statement. 10425 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 10426 Stmt *AStmt, 10427 SourceLocation StartLoc, 10428 SourceLocation EndLoc); 10429 /// Called on well-formed '\#pragma omp task' after parsing of the 10430 /// associated statement. 10431 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 10432 Stmt *AStmt, SourceLocation StartLoc, 10433 SourceLocation EndLoc); 10434 /// Called on well-formed '\#pragma omp taskyield'. 10435 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 10436 SourceLocation EndLoc); 10437 /// Called on well-formed '\#pragma omp barrier'. 10438 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 10439 SourceLocation EndLoc); 10440 /// Called on well-formed '\#pragma omp taskwait'. 10441 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 10442 SourceLocation EndLoc); 10443 /// Called on well-formed '\#pragma omp taskgroup'. 10444 StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, 10445 Stmt *AStmt, SourceLocation StartLoc, 10446 SourceLocation EndLoc); 10447 /// Called on well-formed '\#pragma omp flush'. 10448 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 10449 SourceLocation StartLoc, 10450 SourceLocation EndLoc); 10451 /// Called on well-formed '\#pragma omp depobj'. 10452 StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses, 10453 SourceLocation StartLoc, 10454 SourceLocation EndLoc); 10455 /// Called on well-formed '\#pragma omp scan'. 10456 StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses, 10457 SourceLocation StartLoc, 10458 SourceLocation EndLoc); 10459 /// Called on well-formed '\#pragma omp ordered' after parsing of the 10460 /// associated statement. 10461 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 10462 Stmt *AStmt, SourceLocation StartLoc, 10463 SourceLocation EndLoc); 10464 /// Called on well-formed '\#pragma omp atomic' after parsing of the 10465 /// associated statement. 10466 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 10467 Stmt *AStmt, SourceLocation StartLoc, 10468 SourceLocation EndLoc); 10469 /// Called on well-formed '\#pragma omp target' after parsing of the 10470 /// associated statement. 10471 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 10472 Stmt *AStmt, SourceLocation StartLoc, 10473 SourceLocation EndLoc); 10474 /// Called on well-formed '\#pragma omp target data' after parsing of 10475 /// the associated statement. 10476 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 10477 Stmt *AStmt, SourceLocation StartLoc, 10478 SourceLocation EndLoc); 10479 /// Called on well-formed '\#pragma omp target enter data' after 10480 /// parsing of the associated statement. 10481 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 10482 SourceLocation StartLoc, 10483 SourceLocation EndLoc, 10484 Stmt *AStmt); 10485 /// Called on well-formed '\#pragma omp target exit data' after 10486 /// parsing of the associated statement. 10487 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 10488 SourceLocation StartLoc, 10489 SourceLocation EndLoc, 10490 Stmt *AStmt); 10491 /// Called on well-formed '\#pragma omp target parallel' after 10492 /// parsing of the associated statement. 10493 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 10494 Stmt *AStmt, 10495 SourceLocation StartLoc, 10496 SourceLocation EndLoc); 10497 /// Called on well-formed '\#pragma omp target parallel for' after 10498 /// parsing of the associated statement. 10499 StmtResult ActOnOpenMPTargetParallelForDirective( 10500 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10501 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10502 /// Called on well-formed '\#pragma omp teams' after parsing of the 10503 /// associated statement. 10504 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 10505 Stmt *AStmt, SourceLocation StartLoc, 10506 SourceLocation EndLoc); 10507 /// Called on well-formed '\#pragma omp cancellation point'. 10508 StmtResult 10509 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 10510 SourceLocation EndLoc, 10511 OpenMPDirectiveKind CancelRegion); 10512 /// Called on well-formed '\#pragma omp cancel'. 10513 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 10514 SourceLocation StartLoc, 10515 SourceLocation EndLoc, 10516 OpenMPDirectiveKind CancelRegion); 10517 /// Called on well-formed '\#pragma omp taskloop' after parsing of the 10518 /// associated statement. 10519 StmtResult 10520 ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 10521 SourceLocation StartLoc, SourceLocation EndLoc, 10522 VarsWithInheritedDSAType &VarsWithImplicitDSA); 10523 /// Called on well-formed '\#pragma omp taskloop simd' after parsing of 10524 /// the associated statement. 10525 StmtResult ActOnOpenMPTaskLoopSimdDirective( 10526 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10527 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10528 /// Called on well-formed '\#pragma omp master taskloop' after parsing of the 10529 /// associated statement. 10530 StmtResult ActOnOpenMPMasterTaskLoopDirective( 10531 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10532 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10533 /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of 10534 /// the associated statement. 10535 StmtResult ActOnOpenMPMasterTaskLoopSimdDirective( 10536 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10537 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10538 /// Called on well-formed '\#pragma omp parallel master taskloop' after 10539 /// parsing of the associated statement. 10540 StmtResult ActOnOpenMPParallelMasterTaskLoopDirective( 10541 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10542 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10543 /// Called on well-formed '\#pragma omp parallel master taskloop simd' after 10544 /// parsing of the associated statement. 10545 StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective( 10546 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10547 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10548 /// Called on well-formed '\#pragma omp distribute' after parsing 10549 /// of the associated statement. 10550 StmtResult 10551 ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 10552 SourceLocation StartLoc, SourceLocation EndLoc, 10553 VarsWithInheritedDSAType &VarsWithImplicitDSA); 10554 /// Called on well-formed '\#pragma omp target update'. 10555 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 10556 SourceLocation StartLoc, 10557 SourceLocation EndLoc, 10558 Stmt *AStmt); 10559 /// Called on well-formed '\#pragma omp distribute parallel for' after 10560 /// parsing of the associated statement. 10561 StmtResult ActOnOpenMPDistributeParallelForDirective( 10562 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10563 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10564 /// Called on well-formed '\#pragma omp distribute parallel for simd' 10565 /// after parsing of the associated statement. 10566 StmtResult ActOnOpenMPDistributeParallelForSimdDirective( 10567 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10568 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10569 /// Called on well-formed '\#pragma omp distribute simd' after 10570 /// parsing of the associated statement. 10571 StmtResult ActOnOpenMPDistributeSimdDirective( 10572 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10573 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10574 /// Called on well-formed '\#pragma omp target parallel for simd' after 10575 /// parsing of the associated statement. 10576 StmtResult ActOnOpenMPTargetParallelForSimdDirective( 10577 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10578 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10579 /// Called on well-formed '\#pragma omp target simd' after parsing of 10580 /// the associated statement. 10581 StmtResult 10582 ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 10583 SourceLocation StartLoc, SourceLocation EndLoc, 10584 VarsWithInheritedDSAType &VarsWithImplicitDSA); 10585 /// Called on well-formed '\#pragma omp teams distribute' after parsing of 10586 /// the associated statement. 10587 StmtResult ActOnOpenMPTeamsDistributeDirective( 10588 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10589 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10590 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing 10591 /// of the associated statement. 10592 StmtResult ActOnOpenMPTeamsDistributeSimdDirective( 10593 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10594 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10595 /// Called on well-formed '\#pragma omp teams distribute parallel for simd' 10596 /// after parsing of the associated statement. 10597 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective( 10598 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10599 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10600 /// Called on well-formed '\#pragma omp teams distribute parallel for' 10601 /// after parsing of the associated statement. 10602 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective( 10603 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10604 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10605 /// Called on well-formed '\#pragma omp target teams' after parsing of the 10606 /// associated statement. 10607 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 10608 Stmt *AStmt, 10609 SourceLocation StartLoc, 10610 SourceLocation EndLoc); 10611 /// Called on well-formed '\#pragma omp target teams distribute' after parsing 10612 /// of the associated statement. 10613 StmtResult ActOnOpenMPTargetTeamsDistributeDirective( 10614 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10615 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10616 /// Called on well-formed '\#pragma omp target teams distribute parallel for' 10617 /// after parsing of the associated statement. 10618 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective( 10619 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10620 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10621 /// Called on well-formed '\#pragma omp target teams distribute parallel for 10622 /// simd' after parsing of the associated statement. 10623 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 10624 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10625 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10626 /// Called on well-formed '\#pragma omp target teams distribute simd' after 10627 /// parsing of the associated statement. 10628 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective( 10629 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10630 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10631 10632 /// Checks correctness of linear modifiers. 10633 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 10634 SourceLocation LinLoc); 10635 /// Checks that the specified declaration matches requirements for the linear 10636 /// decls. 10637 bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, 10638 OpenMPLinearClauseKind LinKind, QualType Type, 10639 bool IsDeclareSimd = false); 10640 10641 /// Called on well-formed '\#pragma omp declare simd' after parsing of 10642 /// the associated method/function. 10643 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective( 10644 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, 10645 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 10646 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 10647 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR); 10648 10649 /// Checks '\#pragma omp declare variant' variant function and original 10650 /// functions after parsing of the associated method/function. 10651 /// \param DG Function declaration to which declare variant directive is 10652 /// applied to. 10653 /// \param VariantRef Expression that references the variant function, which 10654 /// must be used instead of the original one, specified in \p DG. 10655 /// \param TI The trait info object representing the match clause. 10656 /// \returns None, if the function/variant function are not compatible with 10657 /// the pragma, pair of original function/variant ref expression otherwise. 10658 Optional<std::pair<FunctionDecl *, Expr *>> 10659 checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef, 10660 OMPTraitInfo &TI, SourceRange SR); 10661 10662 /// Called on well-formed '\#pragma omp declare variant' after parsing of 10663 /// the associated method/function. 10664 /// \param FD Function declaration to which declare variant directive is 10665 /// applied to. 10666 /// \param VariantRef Expression that references the variant function, which 10667 /// must be used instead of the original one, specified in \p DG. 10668 /// \param TI The context traits associated with the function variant. 10669 void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef, 10670 OMPTraitInfo &TI, SourceRange SR); 10671 10672 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, 10673 Expr *Expr, 10674 SourceLocation StartLoc, 10675 SourceLocation LParenLoc, 10676 SourceLocation EndLoc); 10677 /// Called on well-formed 'allocator' clause. 10678 OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator, 10679 SourceLocation StartLoc, 10680 SourceLocation LParenLoc, 10681 SourceLocation EndLoc); 10682 /// Called on well-formed 'if' clause. 10683 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 10684 Expr *Condition, SourceLocation StartLoc, 10685 SourceLocation LParenLoc, 10686 SourceLocation NameModifierLoc, 10687 SourceLocation ColonLoc, 10688 SourceLocation EndLoc); 10689 /// Called on well-formed 'final' clause. 10690 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc, 10691 SourceLocation LParenLoc, 10692 SourceLocation EndLoc); 10693 /// Called on well-formed 'num_threads' clause. 10694 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads, 10695 SourceLocation StartLoc, 10696 SourceLocation LParenLoc, 10697 SourceLocation EndLoc); 10698 /// Called on well-formed 'safelen' clause. 10699 OMPClause *ActOnOpenMPSafelenClause(Expr *Length, 10700 SourceLocation StartLoc, 10701 SourceLocation LParenLoc, 10702 SourceLocation EndLoc); 10703 /// Called on well-formed 'simdlen' clause. 10704 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc, 10705 SourceLocation LParenLoc, 10706 SourceLocation EndLoc); 10707 /// Called on well-formed 'collapse' clause. 10708 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops, 10709 SourceLocation StartLoc, 10710 SourceLocation LParenLoc, 10711 SourceLocation EndLoc); 10712 /// Called on well-formed 'ordered' clause. 10713 OMPClause * 10714 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc, 10715 SourceLocation LParenLoc = SourceLocation(), 10716 Expr *NumForLoops = nullptr); 10717 /// Called on well-formed 'grainsize' clause. 10718 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc, 10719 SourceLocation LParenLoc, 10720 SourceLocation EndLoc); 10721 /// Called on well-formed 'num_tasks' clause. 10722 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc, 10723 SourceLocation LParenLoc, 10724 SourceLocation EndLoc); 10725 /// Called on well-formed 'hint' clause. 10726 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 10727 SourceLocation LParenLoc, 10728 SourceLocation EndLoc); 10729 /// Called on well-formed 'detach' clause. 10730 OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc, 10731 SourceLocation LParenLoc, 10732 SourceLocation EndLoc); 10733 10734 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind, 10735 unsigned Argument, 10736 SourceLocation ArgumentLoc, 10737 SourceLocation StartLoc, 10738 SourceLocation LParenLoc, 10739 SourceLocation EndLoc); 10740 /// Called on well-formed 'default' clause. 10741 OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind, 10742 SourceLocation KindLoc, 10743 SourceLocation StartLoc, 10744 SourceLocation LParenLoc, 10745 SourceLocation EndLoc); 10746 /// Called on well-formed 'proc_bind' clause. 10747 OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind, 10748 SourceLocation KindLoc, 10749 SourceLocation StartLoc, 10750 SourceLocation LParenLoc, 10751 SourceLocation EndLoc); 10752 /// Called on well-formed 'order' clause. 10753 OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind, 10754 SourceLocation KindLoc, 10755 SourceLocation StartLoc, 10756 SourceLocation LParenLoc, 10757 SourceLocation EndLoc); 10758 /// Called on well-formed 'update' clause. 10759 OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind, 10760 SourceLocation KindLoc, 10761 SourceLocation StartLoc, 10762 SourceLocation LParenLoc, 10763 SourceLocation EndLoc); 10764 10765 OMPClause *ActOnOpenMPSingleExprWithArgClause( 10766 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr, 10767 SourceLocation StartLoc, SourceLocation LParenLoc, 10768 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc, 10769 SourceLocation EndLoc); 10770 /// Called on well-formed 'schedule' clause. 10771 OMPClause *ActOnOpenMPScheduleClause( 10772 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 10773 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 10774 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 10775 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); 10776 10777 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc, 10778 SourceLocation EndLoc); 10779 /// Called on well-formed 'nowait' clause. 10780 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc, 10781 SourceLocation EndLoc); 10782 /// Called on well-formed 'untied' clause. 10783 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc, 10784 SourceLocation EndLoc); 10785 /// Called on well-formed 'mergeable' clause. 10786 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc, 10787 SourceLocation EndLoc); 10788 /// Called on well-formed 'read' clause. 10789 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc, 10790 SourceLocation EndLoc); 10791 /// Called on well-formed 'write' clause. 10792 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc, 10793 SourceLocation EndLoc); 10794 /// Called on well-formed 'update' clause. 10795 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc, 10796 SourceLocation EndLoc); 10797 /// Called on well-formed 'capture' clause. 10798 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc, 10799 SourceLocation EndLoc); 10800 /// Called on well-formed 'seq_cst' clause. 10801 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 10802 SourceLocation EndLoc); 10803 /// Called on well-formed 'acq_rel' clause. 10804 OMPClause *ActOnOpenMPAcqRelClause(SourceLocation StartLoc, 10805 SourceLocation EndLoc); 10806 /// Called on well-formed 'acquire' clause. 10807 OMPClause *ActOnOpenMPAcquireClause(SourceLocation StartLoc, 10808 SourceLocation EndLoc); 10809 /// Called on well-formed 'release' clause. 10810 OMPClause *ActOnOpenMPReleaseClause(SourceLocation StartLoc, 10811 SourceLocation EndLoc); 10812 /// Called on well-formed 'relaxed' clause. 10813 OMPClause *ActOnOpenMPRelaxedClause(SourceLocation StartLoc, 10814 SourceLocation EndLoc); 10815 /// Called on well-formed 'destroy' clause. 10816 OMPClause *ActOnOpenMPDestroyClause(SourceLocation StartLoc, 10817 SourceLocation EndLoc); 10818 /// Called on well-formed 'threads' clause. 10819 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc, 10820 SourceLocation EndLoc); 10821 /// Called on well-formed 'simd' clause. 10822 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc, 10823 SourceLocation EndLoc); 10824 /// Called on well-formed 'nogroup' clause. 10825 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc, 10826 SourceLocation EndLoc); 10827 /// Called on well-formed 'unified_address' clause. 10828 OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, 10829 SourceLocation EndLoc); 10830 10831 /// Called on well-formed 'unified_address' clause. 10832 OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, 10833 SourceLocation EndLoc); 10834 10835 /// Called on well-formed 'reverse_offload' clause. 10836 OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, 10837 SourceLocation EndLoc); 10838 10839 /// Called on well-formed 'dynamic_allocators' clause. 10840 OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, 10841 SourceLocation EndLoc); 10842 10843 /// Called on well-formed 'atomic_default_mem_order' clause. 10844 OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause( 10845 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc, 10846 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); 10847 10848 OMPClause *ActOnOpenMPVarListClause( 10849 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *DepModOrTailExpr, 10850 const OMPVarListLocTy &Locs, SourceLocation ColonLoc, 10851 CXXScopeSpec &ReductionOrMapperIdScopeSpec, 10852 DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier, 10853 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 10854 ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit, 10855 SourceLocation ExtraModifierLoc, 10856 ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 10857 ArrayRef<SourceLocation> MotionModifiersLoc); 10858 /// Called on well-formed 'inclusive' clause. 10859 OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList, 10860 SourceLocation StartLoc, 10861 SourceLocation LParenLoc, 10862 SourceLocation EndLoc); 10863 /// Called on well-formed 'exclusive' clause. 10864 OMPClause *ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList, 10865 SourceLocation StartLoc, 10866 SourceLocation LParenLoc, 10867 SourceLocation EndLoc); 10868 /// Called on well-formed 'allocate' clause. 10869 OMPClause * 10870 ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList, 10871 SourceLocation StartLoc, SourceLocation ColonLoc, 10872 SourceLocation LParenLoc, SourceLocation EndLoc); 10873 /// Called on well-formed 'private' clause. 10874 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 10875 SourceLocation StartLoc, 10876 SourceLocation LParenLoc, 10877 SourceLocation EndLoc); 10878 /// Called on well-formed 'firstprivate' clause. 10879 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 10880 SourceLocation StartLoc, 10881 SourceLocation LParenLoc, 10882 SourceLocation EndLoc); 10883 /// Called on well-formed 'lastprivate' clause. 10884 OMPClause *ActOnOpenMPLastprivateClause( 10885 ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind, 10886 SourceLocation LPKindLoc, SourceLocation ColonLoc, 10887 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); 10888 /// Called on well-formed 'shared' clause. 10889 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 10890 SourceLocation StartLoc, 10891 SourceLocation LParenLoc, 10892 SourceLocation EndLoc); 10893 /// Called on well-formed 'reduction' clause. 10894 OMPClause *ActOnOpenMPReductionClause( 10895 ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier, 10896 SourceLocation StartLoc, SourceLocation LParenLoc, 10897 SourceLocation ModifierLoc, SourceLocation ColonLoc, 10898 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, 10899 const DeclarationNameInfo &ReductionId, 10900 ArrayRef<Expr *> UnresolvedReductions = llvm::None); 10901 /// Called on well-formed 'task_reduction' clause. 10902 OMPClause *ActOnOpenMPTaskReductionClause( 10903 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 10904 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, 10905 CXXScopeSpec &ReductionIdScopeSpec, 10906 const DeclarationNameInfo &ReductionId, 10907 ArrayRef<Expr *> UnresolvedReductions = llvm::None); 10908 /// Called on well-formed 'in_reduction' clause. 10909 OMPClause *ActOnOpenMPInReductionClause( 10910 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 10911 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, 10912 CXXScopeSpec &ReductionIdScopeSpec, 10913 const DeclarationNameInfo &ReductionId, 10914 ArrayRef<Expr *> UnresolvedReductions = llvm::None); 10915 /// Called on well-formed 'linear' clause. 10916 OMPClause * 10917 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step, 10918 SourceLocation StartLoc, SourceLocation LParenLoc, 10919 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc, 10920 SourceLocation ColonLoc, SourceLocation EndLoc); 10921 /// Called on well-formed 'aligned' clause. 10922 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList, 10923 Expr *Alignment, 10924 SourceLocation StartLoc, 10925 SourceLocation LParenLoc, 10926 SourceLocation ColonLoc, 10927 SourceLocation EndLoc); 10928 /// Called on well-formed 'copyin' clause. 10929 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 10930 SourceLocation StartLoc, 10931 SourceLocation LParenLoc, 10932 SourceLocation EndLoc); 10933 /// Called on well-formed 'copyprivate' clause. 10934 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 10935 SourceLocation StartLoc, 10936 SourceLocation LParenLoc, 10937 SourceLocation EndLoc); 10938 /// Called on well-formed 'flush' pseudo clause. 10939 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 10940 SourceLocation StartLoc, 10941 SourceLocation LParenLoc, 10942 SourceLocation EndLoc); 10943 /// Called on well-formed 'depobj' pseudo clause. 10944 OMPClause *ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc, 10945 SourceLocation LParenLoc, 10946 SourceLocation EndLoc); 10947 /// Called on well-formed 'depend' clause. 10948 OMPClause * 10949 ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind, 10950 SourceLocation DepLoc, SourceLocation ColonLoc, 10951 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 10952 SourceLocation LParenLoc, SourceLocation EndLoc); 10953 /// Called on well-formed 'device' clause. 10954 OMPClause *ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier, 10955 Expr *Device, SourceLocation StartLoc, 10956 SourceLocation LParenLoc, 10957 SourceLocation ModifierLoc, 10958 SourceLocation EndLoc); 10959 /// Called on well-formed 'map' clause. 10960 OMPClause * 10961 ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 10962 ArrayRef<SourceLocation> MapTypeModifiersLoc, 10963 CXXScopeSpec &MapperIdScopeSpec, 10964 DeclarationNameInfo &MapperId, 10965 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 10966 SourceLocation MapLoc, SourceLocation ColonLoc, 10967 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, 10968 ArrayRef<Expr *> UnresolvedMappers = llvm::None); 10969 /// Called on well-formed 'num_teams' clause. 10970 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc, 10971 SourceLocation LParenLoc, 10972 SourceLocation EndLoc); 10973 /// Called on well-formed 'thread_limit' clause. 10974 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 10975 SourceLocation StartLoc, 10976 SourceLocation LParenLoc, 10977 SourceLocation EndLoc); 10978 /// Called on well-formed 'priority' clause. 10979 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc, 10980 SourceLocation LParenLoc, 10981 SourceLocation EndLoc); 10982 /// Called on well-formed 'dist_schedule' clause. 10983 OMPClause *ActOnOpenMPDistScheduleClause( 10984 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, 10985 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc, 10986 SourceLocation CommaLoc, SourceLocation EndLoc); 10987 /// Called on well-formed 'defaultmap' clause. 10988 OMPClause *ActOnOpenMPDefaultmapClause( 10989 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 10990 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 10991 SourceLocation KindLoc, SourceLocation EndLoc); 10992 /// Called on well-formed 'to' clause. 10993 OMPClause * 10994 ActOnOpenMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 10995 ArrayRef<SourceLocation> MotionModifiersLoc, 10996 CXXScopeSpec &MapperIdScopeSpec, 10997 DeclarationNameInfo &MapperId, SourceLocation ColonLoc, 10998 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, 10999 ArrayRef<Expr *> UnresolvedMappers = llvm::None); 11000 /// Called on well-formed 'from' clause. 11001 OMPClause * 11002 ActOnOpenMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 11003 ArrayRef<SourceLocation> MotionModifiersLoc, 11004 CXXScopeSpec &MapperIdScopeSpec, 11005 DeclarationNameInfo &MapperId, SourceLocation ColonLoc, 11006 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, 11007 ArrayRef<Expr *> UnresolvedMappers = llvm::None); 11008 /// Called on well-formed 'use_device_ptr' clause. 11009 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 11010 const OMPVarListLocTy &Locs); 11011 /// Called on well-formed 'use_device_addr' clause. 11012 OMPClause *ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList, 11013 const OMPVarListLocTy &Locs); 11014 /// Called on well-formed 'is_device_ptr' clause. 11015 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 11016 const OMPVarListLocTy &Locs); 11017 /// Called on well-formed 'nontemporal' clause. 11018 OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList, 11019 SourceLocation StartLoc, 11020 SourceLocation LParenLoc, 11021 SourceLocation EndLoc); 11022 11023 /// Data for list of allocators. 11024 struct UsesAllocatorsData { 11025 /// Allocator. 11026 Expr *Allocator = nullptr; 11027 /// Allocator traits. 11028 Expr *AllocatorTraits = nullptr; 11029 /// Locations of '(' and ')' symbols. 11030 SourceLocation LParenLoc, RParenLoc; 11031 }; 11032 /// Called on well-formed 'uses_allocators' clause. 11033 OMPClause *ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc, 11034 SourceLocation LParenLoc, 11035 SourceLocation EndLoc, 11036 ArrayRef<UsesAllocatorsData> Data); 11037 /// Called on well-formed 'affinity' clause. 11038 OMPClause *ActOnOpenMPAffinityClause(SourceLocation StartLoc, 11039 SourceLocation LParenLoc, 11040 SourceLocation ColonLoc, 11041 SourceLocation EndLoc, Expr *Modifier, 11042 ArrayRef<Expr *> Locators); 11043 11044 /// The kind of conversion being performed. 11045 enum CheckedConversionKind { 11046 /// An implicit conversion. 11047 CCK_ImplicitConversion, 11048 /// A C-style cast. 11049 CCK_CStyleCast, 11050 /// A functional-style cast. 11051 CCK_FunctionalCast, 11052 /// A cast other than a C-style cast. 11053 CCK_OtherCast, 11054 /// A conversion for an operand of a builtin overloaded operator. 11055 CCK_ForBuiltinOverloadedOp 11056 }; 11057 isCast(CheckedConversionKind CCK)11058 static bool isCast(CheckedConversionKind CCK) { 11059 return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast || 11060 CCK == CCK_OtherCast; 11061 } 11062 11063 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit 11064 /// cast. If there is already an implicit cast, merge into the existing one. 11065 /// If isLvalue, the result of the cast is an lvalue. 11066 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, 11067 ExprValueKind VK = VK_RValue, 11068 const CXXCastPath *BasePath = nullptr, 11069 CheckedConversionKind CCK 11070 = CCK_ImplicitConversion); 11071 11072 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding 11073 /// to the conversion from scalar type ScalarTy to the Boolean type. 11074 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); 11075 11076 /// IgnoredValueConversions - Given that an expression's result is 11077 /// syntactically ignored, perform any conversions that are 11078 /// required. 11079 ExprResult IgnoredValueConversions(Expr *E); 11080 11081 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts 11082 // functions and arrays to their respective pointers (C99 6.3.2.1). 11083 ExprResult UsualUnaryConversions(Expr *E); 11084 11085 /// CallExprUnaryConversions - a special case of an unary conversion 11086 /// performed on a function designator of a call expression. 11087 ExprResult CallExprUnaryConversions(Expr *E); 11088 11089 // DefaultFunctionArrayConversion - converts functions and arrays 11090 // to their respective pointers (C99 6.3.2.1). 11091 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true); 11092 11093 // DefaultFunctionArrayLvalueConversion - converts functions and 11094 // arrays to their respective pointers and performs the 11095 // lvalue-to-rvalue conversion. 11096 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, 11097 bool Diagnose = true); 11098 11099 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on 11100 // the operand. This function is a no-op if the operand has a function type 11101 // or an array type. 11102 ExprResult DefaultLvalueConversion(Expr *E); 11103 11104 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 11105 // do not have a prototype. Integer promotions are performed on each 11106 // argument, and arguments that have type float are promoted to double. 11107 ExprResult DefaultArgumentPromotion(Expr *E); 11108 11109 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize 11110 /// it as an xvalue. In C++98, the result will still be a prvalue, because 11111 /// we don't have xvalues there. 11112 ExprResult TemporaryMaterializationConversion(Expr *E); 11113 11114 // Used for emitting the right warning by DefaultVariadicArgumentPromotion 11115 enum VariadicCallType { 11116 VariadicFunction, 11117 VariadicBlock, 11118 VariadicMethod, 11119 VariadicConstructor, 11120 VariadicDoesNotApply 11121 }; 11122 11123 VariadicCallType getVariadicCallType(FunctionDecl *FDecl, 11124 const FunctionProtoType *Proto, 11125 Expr *Fn); 11126 11127 // Used for determining in which context a type is allowed to be passed to a 11128 // vararg function. 11129 enum VarArgKind { 11130 VAK_Valid, 11131 VAK_ValidInCXX11, 11132 VAK_Undefined, 11133 VAK_MSVCUndefined, 11134 VAK_Invalid 11135 }; 11136 11137 // Determines which VarArgKind fits an expression. 11138 VarArgKind isValidVarArgType(const QualType &Ty); 11139 11140 /// Check to see if the given expression is a valid argument to a variadic 11141 /// function, issuing a diagnostic if not. 11142 void checkVariadicArgument(const Expr *E, VariadicCallType CT); 11143 11144 /// Check to see if a given expression could have '.c_str()' called on it. 11145 bool hasCStrMethod(const Expr *E); 11146 11147 /// GatherArgumentsForCall - Collector argument expressions for various 11148 /// form of call prototypes. 11149 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 11150 const FunctionProtoType *Proto, 11151 unsigned FirstParam, ArrayRef<Expr *> Args, 11152 SmallVectorImpl<Expr *> &AllArgs, 11153 VariadicCallType CallType = VariadicDoesNotApply, 11154 bool AllowExplicit = false, 11155 bool IsListInitialization = false); 11156 11157 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 11158 // will create a runtime trap if the resulting type is not a POD type. 11159 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 11160 FunctionDecl *FDecl); 11161 11162 /// Context in which we're performing a usual arithmetic conversion. 11163 enum ArithConvKind { 11164 /// An arithmetic operation. 11165 ACK_Arithmetic, 11166 /// A bitwise operation. 11167 ACK_BitwiseOp, 11168 /// A comparison. 11169 ACK_Comparison, 11170 /// A conditional (?:) operator. 11171 ACK_Conditional, 11172 /// A compound assignment expression. 11173 ACK_CompAssign, 11174 }; 11175 11176 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's 11177 // operands and then handles various conversions that are common to binary 11178 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this 11179 // routine returns the first non-arithmetic type found. The client is 11180 // responsible for emitting appropriate error diagnostics. 11181 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 11182 SourceLocation Loc, ArithConvKind ACK); 11183 11184 /// AssignConvertType - All of the 'assignment' semantic checks return this 11185 /// enum to indicate whether the assignment was allowed. These checks are 11186 /// done for simple assignments, as well as initialization, return from 11187 /// function, argument passing, etc. The query is phrased in terms of a 11188 /// source and destination type. 11189 enum AssignConvertType { 11190 /// Compatible - the types are compatible according to the standard. 11191 Compatible, 11192 11193 /// PointerToInt - The assignment converts a pointer to an int, which we 11194 /// accept as an extension. 11195 PointerToInt, 11196 11197 /// IntToPointer - The assignment converts an int to a pointer, which we 11198 /// accept as an extension. 11199 IntToPointer, 11200 11201 /// FunctionVoidPointer - The assignment is between a function pointer and 11202 /// void*, which the standard doesn't allow, but we accept as an extension. 11203 FunctionVoidPointer, 11204 11205 /// IncompatiblePointer - The assignment is between two pointers types that 11206 /// are not compatible, but we accept them as an extension. 11207 IncompatiblePointer, 11208 11209 /// IncompatibleFunctionPointer - The assignment is between two function 11210 /// pointers types that are not compatible, but we accept them as an 11211 /// extension. 11212 IncompatibleFunctionPointer, 11213 11214 /// IncompatiblePointerSign - The assignment is between two pointers types 11215 /// which point to integers which have a different sign, but are otherwise 11216 /// identical. This is a subset of the above, but broken out because it's by 11217 /// far the most common case of incompatible pointers. 11218 IncompatiblePointerSign, 11219 11220 /// CompatiblePointerDiscardsQualifiers - The assignment discards 11221 /// c/v/r qualifiers, which we accept as an extension. 11222 CompatiblePointerDiscardsQualifiers, 11223 11224 /// IncompatiblePointerDiscardsQualifiers - The assignment 11225 /// discards qualifiers that we don't permit to be discarded, 11226 /// like address spaces. 11227 IncompatiblePointerDiscardsQualifiers, 11228 11229 /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment 11230 /// changes address spaces in nested pointer types which is not allowed. 11231 /// For instance, converting __private int ** to __generic int ** is 11232 /// illegal even though __private could be converted to __generic. 11233 IncompatibleNestedPointerAddressSpaceMismatch, 11234 11235 /// IncompatibleNestedPointerQualifiers - The assignment is between two 11236 /// nested pointer types, and the qualifiers other than the first two 11237 /// levels differ e.g. char ** -> const char **, but we accept them as an 11238 /// extension. 11239 IncompatibleNestedPointerQualifiers, 11240 11241 /// IncompatibleVectors - The assignment is between two vector types that 11242 /// have the same size, which we accept as an extension. 11243 IncompatibleVectors, 11244 11245 /// IntToBlockPointer - The assignment converts an int to a block 11246 /// pointer. We disallow this. 11247 IntToBlockPointer, 11248 11249 /// IncompatibleBlockPointer - The assignment is between two block 11250 /// pointers types that are not compatible. 11251 IncompatibleBlockPointer, 11252 11253 /// IncompatibleObjCQualifiedId - The assignment is between a qualified 11254 /// id type and something else (that is incompatible with it). For example, 11255 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. 11256 IncompatibleObjCQualifiedId, 11257 11258 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an 11259 /// object with __weak qualifier. 11260 IncompatibleObjCWeakRef, 11261 11262 /// Incompatible - We reject this conversion outright, it is invalid to 11263 /// represent it in the AST. 11264 Incompatible 11265 }; 11266 11267 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the 11268 /// assignment conversion type specified by ConvTy. This returns true if the 11269 /// conversion was invalid or false if the conversion was accepted. 11270 bool DiagnoseAssignmentResult(AssignConvertType ConvTy, 11271 SourceLocation Loc, 11272 QualType DstType, QualType SrcType, 11273 Expr *SrcExpr, AssignmentAction Action, 11274 bool *Complained = nullptr); 11275 11276 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag 11277 /// enum. If AllowMask is true, then we also allow the complement of a valid 11278 /// value, to be used as a mask. 11279 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 11280 bool AllowMask) const; 11281 11282 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant 11283 /// integer not in the range of enum values. 11284 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, 11285 Expr *SrcExpr); 11286 11287 /// CheckAssignmentConstraints - Perform type checking for assignment, 11288 /// argument passing, variable initialization, and function return values. 11289 /// C99 6.5.16. 11290 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, 11291 QualType LHSType, 11292 QualType RHSType); 11293 11294 /// Check assignment constraints and optionally prepare for a conversion of 11295 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS 11296 /// is true. 11297 AssignConvertType CheckAssignmentConstraints(QualType LHSType, 11298 ExprResult &RHS, 11299 CastKind &Kind, 11300 bool ConvertRHS = true); 11301 11302 /// Check assignment constraints for an assignment of RHS to LHSType. 11303 /// 11304 /// \param LHSType The destination type for the assignment. 11305 /// \param RHS The source expression for the assignment. 11306 /// \param Diagnose If \c true, diagnostics may be produced when checking 11307 /// for assignability. If a diagnostic is produced, \p RHS will be 11308 /// set to ExprError(). Note that this function may still return 11309 /// without producing a diagnostic, even for an invalid assignment. 11310 /// \param DiagnoseCFAudited If \c true, the target is a function parameter 11311 /// in an audited Core Foundation API and does not need to be checked 11312 /// for ARC retain issues. 11313 /// \param ConvertRHS If \c true, \p RHS will be updated to model the 11314 /// conversions necessary to perform the assignment. If \c false, 11315 /// \p Diagnose must also be \c false. 11316 AssignConvertType CheckSingleAssignmentConstraints( 11317 QualType LHSType, ExprResult &RHS, bool Diagnose = true, 11318 bool DiagnoseCFAudited = false, bool ConvertRHS = true); 11319 11320 // If the lhs type is a transparent union, check whether we 11321 // can initialize the transparent union with the given expression. 11322 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, 11323 ExprResult &RHS); 11324 11325 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); 11326 11327 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); 11328 11329 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 11330 AssignmentAction Action, 11331 bool AllowExplicit = false); 11332 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 11333 const ImplicitConversionSequence& ICS, 11334 AssignmentAction Action, 11335 CheckedConversionKind CCK 11336 = CCK_ImplicitConversion); 11337 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 11338 const StandardConversionSequence& SCS, 11339 AssignmentAction Action, 11340 CheckedConversionKind CCK); 11341 11342 ExprResult PerformQualificationConversion( 11343 Expr *E, QualType Ty, ExprValueKind VK = VK_RValue, 11344 CheckedConversionKind CCK = CCK_ImplicitConversion); 11345 11346 /// the following "Check" methods will return a valid/converted QualType 11347 /// or a null QualType (indicating an error diagnostic was issued). 11348 11349 /// type checking binary operators (subroutines of CreateBuiltinBinOp). 11350 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, 11351 ExprResult &RHS); 11352 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 11353 ExprResult &RHS); 11354 QualType CheckPointerToMemberOperands( // C++ 5.5 11355 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, 11356 SourceLocation OpLoc, bool isIndirect); 11357 QualType CheckMultiplyDivideOperands( // C99 6.5.5 11358 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, 11359 bool IsDivide); 11360 QualType CheckRemainderOperands( // C99 6.5.5 11361 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11362 bool IsCompAssign = false); 11363 QualType CheckAdditionOperands( // C99 6.5.6 11364 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11365 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr); 11366 QualType CheckSubtractionOperands( // C99 6.5.6 11367 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11368 QualType* CompLHSTy = nullptr); 11369 QualType CheckShiftOperands( // C99 6.5.7 11370 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11371 BinaryOperatorKind Opc, bool IsCompAssign = false); 11372 void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE); 11373 QualType CheckCompareOperands( // C99 6.5.8/9 11374 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11375 BinaryOperatorKind Opc); 11376 QualType CheckBitwiseOperands( // C99 6.5.[10...12] 11377 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11378 BinaryOperatorKind Opc); 11379 QualType CheckLogicalOperands( // C99 6.5.[13,14] 11380 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11381 BinaryOperatorKind Opc); 11382 // CheckAssignmentOperands is used for both simple and compound assignment. 11383 // For simple assignment, pass both expressions and a null converted type. 11384 // For compound assignment, pass both expressions and the converted type. 11385 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] 11386 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); 11387 11388 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, 11389 UnaryOperatorKind Opcode, Expr *Op); 11390 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, 11391 BinaryOperatorKind Opcode, 11392 Expr *LHS, Expr *RHS); 11393 ExprResult checkPseudoObjectRValue(Expr *E); 11394 Expr *recreateSyntacticForm(PseudoObjectExpr *E); 11395 11396 QualType CheckConditionalOperands( // C99 6.5.15 11397 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, 11398 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); 11399 QualType CXXCheckConditionalOperands( // C++ 5.16 11400 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, 11401 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); 11402 QualType CheckGNUVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, 11403 ExprResult &RHS, 11404 SourceLocation QuestionLoc); 11405 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, 11406 bool ConvertArgs = true); 11407 QualType FindCompositePointerType(SourceLocation Loc, 11408 ExprResult &E1, ExprResult &E2, 11409 bool ConvertArgs = true) { 11410 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get(); 11411 QualType Composite = 11412 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs); 11413 E1 = E1Tmp; 11414 E2 = E2Tmp; 11415 return Composite; 11416 } 11417 11418 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 11419 SourceLocation QuestionLoc); 11420 11421 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 11422 SourceLocation QuestionLoc); 11423 11424 void DiagnoseAlwaysNonNullPointer(Expr *E, 11425 Expr::NullPointerConstantKind NullType, 11426 bool IsEqual, SourceRange Range); 11427 11428 /// type checking for vector binary operators. 11429 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 11430 SourceLocation Loc, bool IsCompAssign, 11431 bool AllowBothBool, bool AllowBoolConversion); 11432 QualType GetSignedVectorType(QualType V); 11433 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11434 SourceLocation Loc, 11435 BinaryOperatorKind Opc); 11436 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11437 SourceLocation Loc); 11438 11439 /// Type checking for matrix binary operators. 11440 QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 11441 SourceLocation Loc, 11442 bool IsCompAssign); 11443 QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 11444 SourceLocation Loc, bool IsCompAssign); 11445 11446 bool isValidSveBitcast(QualType srcType, QualType destType); 11447 11448 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType); 11449 bool isLaxVectorConversion(QualType srcType, QualType destType); 11450 11451 /// type checking declaration initializers (C99 6.7.8) 11452 bool CheckForConstantInitializer(Expr *e, QualType t); 11453 11454 // type checking C++ declaration initializers (C++ [dcl.init]). 11455 11456 /// ReferenceCompareResult - Expresses the result of comparing two 11457 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the 11458 /// purposes of initialization by reference (C++ [dcl.init.ref]p4). 11459 enum ReferenceCompareResult { 11460 /// Ref_Incompatible - The two types are incompatible, so direct 11461 /// reference binding is not possible. 11462 Ref_Incompatible = 0, 11463 /// Ref_Related - The two types are reference-related, which means 11464 /// that their unqualified forms (T1 and T2) are either the same 11465 /// or T1 is a base class of T2. 11466 Ref_Related, 11467 /// Ref_Compatible - The two types are reference-compatible. 11468 Ref_Compatible 11469 }; 11470 11471 // Fake up a scoped enumeration that still contextually converts to bool. 11472 struct ReferenceConversionsScope { 11473 /// The conversions that would be performed on an lvalue of type T2 when 11474 /// binding a reference of type T1 to it, as determined when evaluating 11475 /// whether T1 is reference-compatible with T2. 11476 enum ReferenceConversions { 11477 Qualification = 0x1, 11478 NestedQualification = 0x2, 11479 Function = 0x4, 11480 DerivedToBase = 0x8, 11481 ObjC = 0x10, 11482 ObjCLifetime = 0x20, 11483 11484 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime) 11485 }; 11486 }; 11487 using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions; 11488 11489 ReferenceCompareResult 11490 CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, 11491 ReferenceConversions *Conv = nullptr); 11492 11493 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 11494 Expr *CastExpr, CastKind &CastKind, 11495 ExprValueKind &VK, CXXCastPath &Path); 11496 11497 /// Force an expression with unknown-type to an expression of the 11498 /// given type. 11499 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); 11500 11501 /// Type-check an expression that's being passed to an 11502 /// __unknown_anytype parameter. 11503 ExprResult checkUnknownAnyArg(SourceLocation callLoc, 11504 Expr *result, QualType ¶mType); 11505 11506 // CheckVectorCast - check type constraints for vectors. 11507 // Since vectors are an extension, there are no C standard reference for this. 11508 // We allow casting between vectors and integer datatypes of the same size. 11509 // returns true if the cast is invalid 11510 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 11511 CastKind &Kind); 11512 11513 /// Prepare `SplattedExpr` for a vector splat operation, adding 11514 /// implicit casts if necessary. 11515 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr); 11516 11517 // CheckExtVectorCast - check type constraints for extended vectors. 11518 // Since vectors are an extension, there are no C standard reference for this. 11519 // We allow casting between vectors and integer datatypes of the same size, 11520 // or vectors and the element type of that vector. 11521 // returns the cast expr 11522 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, 11523 CastKind &Kind); 11524 11525 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, 11526 SourceLocation LParenLoc, 11527 Expr *CastExpr, 11528 SourceLocation RParenLoc); 11529 11530 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error }; 11531 11532 /// Checks for invalid conversions and casts between 11533 /// retainable pointers and other pointer kinds for ARC and Weak. 11534 ARCConversionResult CheckObjCConversion(SourceRange castRange, 11535 QualType castType, Expr *&op, 11536 CheckedConversionKind CCK, 11537 bool Diagnose = true, 11538 bool DiagnoseCFAudited = false, 11539 BinaryOperatorKind Opc = BO_PtrMemD 11540 ); 11541 11542 Expr *stripARCUnbridgedCast(Expr *e); 11543 void diagnoseARCUnbridgedCast(Expr *e); 11544 11545 bool CheckObjCARCUnavailableWeakConversion(QualType castType, 11546 QualType ExprType); 11547 11548 /// checkRetainCycles - Check whether an Objective-C message send 11549 /// might create an obvious retain cycle. 11550 void checkRetainCycles(ObjCMessageExpr *msg); 11551 void checkRetainCycles(Expr *receiver, Expr *argument); 11552 void checkRetainCycles(VarDecl *Var, Expr *Init); 11553 11554 /// checkUnsafeAssigns - Check whether +1 expr is being assigned 11555 /// to weak/__unsafe_unretained type. 11556 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); 11557 11558 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned 11559 /// to weak/__unsafe_unretained expression. 11560 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); 11561 11562 /// CheckMessageArgumentTypes - Check types in an Obj-C message send. 11563 /// \param Method - May be null. 11564 /// \param [out] ReturnType - The return type of the send. 11565 /// \return true iff there were any incompatible types. 11566 bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType, 11567 MultiExprArg Args, Selector Sel, 11568 ArrayRef<SourceLocation> SelectorLocs, 11569 ObjCMethodDecl *Method, bool isClassMessage, 11570 bool isSuperMessage, SourceLocation lbrac, 11571 SourceLocation rbrac, SourceRange RecRange, 11572 QualType &ReturnType, ExprValueKind &VK); 11573 11574 /// Determine the result of a message send expression based on 11575 /// the type of the receiver, the method expected to receive the message, 11576 /// and the form of the message send. 11577 QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType, 11578 ObjCMethodDecl *Method, bool isClassMessage, 11579 bool isSuperMessage); 11580 11581 /// If the given expression involves a message send to a method 11582 /// with a related result type, emit a note describing what happened. 11583 void EmitRelatedResultTypeNote(const Expr *E); 11584 11585 /// Given that we had incompatible pointer types in a return 11586 /// statement, check whether we're in a method with a related result 11587 /// type, and if so, emit a note describing what happened. 11588 void EmitRelatedResultTypeNoteForReturn(QualType destType); 11589 11590 class ConditionResult { 11591 Decl *ConditionVar; 11592 FullExprArg Condition; 11593 bool Invalid; 11594 bool HasKnownValue; 11595 bool KnownValue; 11596 11597 friend class Sema; ConditionResult(Sema & S,Decl * ConditionVar,FullExprArg Condition,bool IsConstexpr)11598 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition, 11599 bool IsConstexpr) 11600 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false), 11601 HasKnownValue(IsConstexpr && Condition.get() && 11602 !Condition.get()->isValueDependent()), 11603 KnownValue(HasKnownValue && 11604 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {} ConditionResult(bool Invalid)11605 explicit ConditionResult(bool Invalid) 11606 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid), 11607 HasKnownValue(false), KnownValue(false) {} 11608 11609 public: ConditionResult()11610 ConditionResult() : ConditionResult(false) {} isInvalid()11611 bool isInvalid() const { return Invalid; } get()11612 std::pair<VarDecl *, Expr *> get() const { 11613 return std::make_pair(cast_or_null<VarDecl>(ConditionVar), 11614 Condition.get()); 11615 } getKnownValue()11616 llvm::Optional<bool> getKnownValue() const { 11617 if (!HasKnownValue) 11618 return None; 11619 return KnownValue; 11620 } 11621 }; ConditionError()11622 static ConditionResult ConditionError() { return ConditionResult(true); } 11623 11624 enum class ConditionKind { 11625 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'. 11626 ConstexprIf, ///< A constant boolean condition from 'if constexpr'. 11627 Switch ///< An integral condition for a 'switch' statement. 11628 }; 11629 11630 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, 11631 Expr *SubExpr, ConditionKind CK); 11632 11633 ConditionResult ActOnConditionVariable(Decl *ConditionVar, 11634 SourceLocation StmtLoc, 11635 ConditionKind CK); 11636 11637 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); 11638 11639 ExprResult CheckConditionVariable(VarDecl *ConditionVar, 11640 SourceLocation StmtLoc, 11641 ConditionKind CK); 11642 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond); 11643 11644 /// CheckBooleanCondition - Diagnose problems involving the use of 11645 /// the given expression as a boolean condition (e.g. in an if 11646 /// statement). Also performs the standard function and array 11647 /// decays, possibly changing the input variable. 11648 /// 11649 /// \param Loc - A location associated with the condition, e.g. the 11650 /// 'if' keyword. 11651 /// \return true iff there were any errors 11652 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, 11653 bool IsConstexpr = false); 11654 11655 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression 11656 /// found in an explicit(bool) specifier. 11657 ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E); 11658 11659 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier. 11660 /// Returns true if the explicit specifier is now resolved. 11661 bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec); 11662 11663 /// DiagnoseAssignmentAsCondition - Given that an expression is 11664 /// being used as a boolean condition, warn if it's an assignment. 11665 void DiagnoseAssignmentAsCondition(Expr *E); 11666 11667 /// Redundant parentheses over an equality comparison can indicate 11668 /// that the user intended an assignment used as condition. 11669 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); 11670 11671 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. 11672 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false); 11673 11674 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 11675 /// the specified width and sign. If an overflow occurs, detect it and emit 11676 /// the specified diagnostic. 11677 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, 11678 unsigned NewWidth, bool NewSign, 11679 SourceLocation Loc, unsigned DiagID); 11680 11681 /// Checks that the Objective-C declaration is declared in the global scope. 11682 /// Emits an error and marks the declaration as invalid if it's not declared 11683 /// in the global scope. 11684 bool CheckObjCDeclScope(Decl *D); 11685 11686 /// Abstract base class used for diagnosing integer constant 11687 /// expression violations. 11688 class VerifyICEDiagnoser { 11689 public: 11690 bool Suppress; 11691 Suppress(Suppress)11692 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } 11693 11694 virtual SemaDiagnosticBuilder 11695 diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T); 11696 virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 11697 SourceLocation Loc) = 0; 11698 virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc); ~VerifyICEDiagnoser()11699 virtual ~VerifyICEDiagnoser() {} 11700 }; 11701 11702 enum AllowFoldKind { 11703 NoFold, 11704 AllowFold, 11705 }; 11706 11707 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, 11708 /// and reports the appropriate diagnostics. Returns false on success. 11709 /// Can optionally return the value of the expression. 11710 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 11711 VerifyICEDiagnoser &Diagnoser, 11712 AllowFoldKind CanFold = NoFold); 11713 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 11714 unsigned DiagID, 11715 AllowFoldKind CanFold = NoFold); 11716 ExprResult VerifyIntegerConstantExpression(Expr *E, 11717 llvm::APSInt *Result = nullptr, 11718 AllowFoldKind CanFold = NoFold); 11719 ExprResult VerifyIntegerConstantExpression(Expr *E, 11720 AllowFoldKind CanFold = NoFold) { 11721 return VerifyIntegerConstantExpression(E, nullptr, CanFold); 11722 } 11723 11724 /// VerifyBitField - verifies that a bit field expression is an ICE and has 11725 /// the correct width, and that the field type is valid. 11726 /// Returns false on success. 11727 /// Can optionally return whether the bit-field is of width 0 11728 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 11729 QualType FieldTy, bool IsMsStruct, 11730 Expr *BitWidth, bool *ZeroWidth = nullptr); 11731 11732 private: 11733 unsigned ForceCUDAHostDeviceDepth = 0; 11734 11735 public: 11736 /// Increments our count of the number of times we've seen a pragma forcing 11737 /// functions to be __host__ __device__. So long as this count is greater 11738 /// than zero, all functions encountered will be __host__ __device__. 11739 void PushForceCUDAHostDevice(); 11740 11741 /// Decrements our count of the number of times we've seen a pragma forcing 11742 /// functions to be __host__ __device__. Returns false if the count is 0 11743 /// before incrementing, so you can emit an error. 11744 bool PopForceCUDAHostDevice(); 11745 11746 /// Diagnostics that are emitted only if we discover that the given function 11747 /// must be codegen'ed. Because handling these correctly adds overhead to 11748 /// compilation, this is currently only enabled for CUDA compilations. 11749 llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>, 11750 std::vector<PartialDiagnosticAt>> 11751 DeviceDeferredDiags; 11752 11753 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the 11754 /// key in a hashtable, both the FD and location are hashed. 11755 struct FunctionDeclAndLoc { 11756 CanonicalDeclPtr<FunctionDecl> FD; 11757 SourceLocation Loc; 11758 }; 11759 11760 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a 11761 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the 11762 /// same deferred diag twice. 11763 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags; 11764 11765 /// An inverse call graph, mapping known-emitted functions to one of their 11766 /// known-emitted callers (plus the location of the call). 11767 /// 11768 /// Functions that we can tell a priori must be emitted aren't added to this 11769 /// map. 11770 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>, 11771 /* Caller = */ FunctionDeclAndLoc> 11772 DeviceKnownEmittedFns; 11773 11774 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current 11775 /// context is "used as device code". 11776 /// 11777 /// - If CurContext is a __host__ function, does not emit any diagnostics 11778 /// unless \p EmitOnBothSides is true. 11779 /// - If CurContext is a __device__ or __global__ function, emits the 11780 /// diagnostics immediately. 11781 /// - If CurContext is a __host__ __device__ function and we are compiling for 11782 /// the device, creates a diagnostic which is emitted if and when we realize 11783 /// that the function will be codegen'ed. 11784 /// 11785 /// Example usage: 11786 /// 11787 /// // Variable-length arrays are not allowed in CUDA device code. 11788 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget()) 11789 /// return ExprError(); 11790 /// // Otherwise, continue parsing as normal. 11791 SemaDiagnosticBuilder CUDADiagIfDeviceCode(SourceLocation Loc, 11792 unsigned DiagID); 11793 11794 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current 11795 /// context is "used as host code". 11796 /// 11797 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched. 11798 SemaDiagnosticBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID); 11799 11800 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current 11801 /// context is "used as device code". 11802 /// 11803 /// - If CurContext is a `declare target` function or it is known that the 11804 /// function is emitted for the device, emits the diagnostics immediately. 11805 /// - If CurContext is a non-`declare target` function and we are compiling 11806 /// for the device, creates a diagnostic which is emitted if and when we 11807 /// realize that the function will be codegen'ed. 11808 /// 11809 /// Example usage: 11810 /// 11811 /// // Variable-length arrays are not allowed in NVPTX device code. 11812 /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported)) 11813 /// return ExprError(); 11814 /// // Otherwise, continue parsing as normal. 11815 SemaDiagnosticBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, 11816 unsigned DiagID); 11817 11818 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current 11819 /// context is "used as host code". 11820 /// 11821 /// - If CurContext is a `declare target` function or it is known that the 11822 /// function is emitted for the host, emits the diagnostics immediately. 11823 /// - If CurContext is a non-host function, just ignore it. 11824 /// 11825 /// Example usage: 11826 /// 11827 /// // Variable-length arrays are not allowed in NVPTX device code. 11828 /// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported)) 11829 /// return ExprError(); 11830 /// // Otherwise, continue parsing as normal. 11831 SemaDiagnosticBuilder diagIfOpenMPHostCode(SourceLocation Loc, 11832 unsigned DiagID); 11833 11834 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID); targetDiag(SourceLocation Loc,const PartialDiagnostic & PD)11835 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, 11836 const PartialDiagnostic &PD) { 11837 return targetDiag(Loc, PD.getDiagID()) << PD; 11838 } 11839 11840 /// Check if the expression is allowed to be used in expressions for the 11841 /// offloading devices. 11842 void checkDeviceDecl(const ValueDecl *D, SourceLocation Loc); 11843 11844 enum CUDAFunctionTarget { 11845 CFT_Device, 11846 CFT_Global, 11847 CFT_Host, 11848 CFT_HostDevice, 11849 CFT_InvalidTarget 11850 }; 11851 11852 /// Determines whether the given function is a CUDA device/host/kernel/etc. 11853 /// function. 11854 /// 11855 /// Use this rather than examining the function's attributes yourself -- you 11856 /// will get it wrong. Returns CFT_Host if D is null. 11857 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D, 11858 bool IgnoreImplicitHDAttr = false); 11859 CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs); 11860 11861 /// Gets the CUDA target for the current context. CurrentCUDATarget()11862 CUDAFunctionTarget CurrentCUDATarget() { 11863 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext)); 11864 } 11865 11866 static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D); 11867 11868 // CUDA function call preference. Must be ordered numerically from 11869 // worst to best. 11870 enum CUDAFunctionPreference { 11871 CFP_Never, // Invalid caller/callee combination. 11872 CFP_WrongSide, // Calls from host-device to host or device 11873 // function that do not match current compilation 11874 // mode. 11875 CFP_HostDevice, // Any calls to host/device functions. 11876 CFP_SameSide, // Calls from host-device to host or device 11877 // function matching current compilation mode. 11878 CFP_Native, // host-to-host or device-to-device calls. 11879 }; 11880 11881 /// Identifies relative preference of a given Caller/Callee 11882 /// combination, based on their host/device attributes. 11883 /// \param Caller function which needs address of \p Callee. 11884 /// nullptr in case of global context. 11885 /// \param Callee target function 11886 /// 11887 /// \returns preference value for particular Caller/Callee combination. 11888 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller, 11889 const FunctionDecl *Callee); 11890 11891 /// Determines whether Caller may invoke Callee, based on their CUDA 11892 /// host/device attributes. Returns false if the call is not allowed. 11893 /// 11894 /// Note: Will return true for CFP_WrongSide calls. These may appear in 11895 /// semantically correct CUDA programs, but only if they're never codegen'ed. IsAllowedCUDACall(const FunctionDecl * Caller,const FunctionDecl * Callee)11896 bool IsAllowedCUDACall(const FunctionDecl *Caller, 11897 const FunctionDecl *Callee) { 11898 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never; 11899 } 11900 11901 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, 11902 /// depending on FD and the current compilation settings. 11903 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD, 11904 const LookupResult &Previous); 11905 11906 /// May add implicit CUDAConstantAttr attribute to VD, depending on VD 11907 /// and current compilation settings. 11908 void MaybeAddCUDAConstantAttr(VarDecl *VD); 11909 11910 public: 11911 /// Check whether we're allowed to call Callee from the current context. 11912 /// 11913 /// - If the call is never allowed in a semantically-correct program 11914 /// (CFP_Never), emits an error and returns false. 11915 /// 11916 /// - If the call is allowed in semantically-correct programs, but only if 11917 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to 11918 /// be emitted if and when the caller is codegen'ed, and returns true. 11919 /// 11920 /// Will only create deferred diagnostics for a given SourceLocation once, 11921 /// so you can safely call this multiple times without generating duplicate 11922 /// deferred errors. 11923 /// 11924 /// - Otherwise, returns true without emitting any diagnostics. 11925 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee); 11926 11927 void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture); 11928 11929 /// Set __device__ or __host__ __device__ attributes on the given lambda 11930 /// operator() method. 11931 /// 11932 /// CUDA lambdas by default is host device function unless it has explicit 11933 /// host or device attribute. 11934 void CUDASetLambdaAttrs(CXXMethodDecl *Method); 11935 11936 /// Finds a function in \p Matches with highest calling priority 11937 /// from \p Caller context and erases all functions with lower 11938 /// calling priority. 11939 void EraseUnwantedCUDAMatches( 11940 const FunctionDecl *Caller, 11941 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches); 11942 11943 /// Given a implicit special member, infer its CUDA target from the 11944 /// calls it needs to make to underlying base/field special members. 11945 /// \param ClassDecl the class for which the member is being created. 11946 /// \param CSM the kind of special member. 11947 /// \param MemberDecl the special member itself. 11948 /// \param ConstRHS true if this is a copy operation with a const object on 11949 /// its RHS. 11950 /// \param Diagnose true if this call should emit diagnostics. 11951 /// \return true if there was an error inferring. 11952 /// The result of this call is implicit CUDA target attribute(s) attached to 11953 /// the member declaration. 11954 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, 11955 CXXSpecialMember CSM, 11956 CXXMethodDecl *MemberDecl, 11957 bool ConstRHS, 11958 bool Diagnose); 11959 11960 /// \return true if \p CD can be considered empty according to CUDA 11961 /// (E.2.3.1 in CUDA 7.5 Programming guide). 11962 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD); 11963 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD); 11964 11965 // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In 11966 // case of error emits appropriate diagnostic and invalidates \p Var. 11967 // 11968 // \details CUDA allows only empty constructors as initializers for global 11969 // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all 11970 // __shared__ variables whether they are local or not (they all are implicitly 11971 // static in CUDA). One exception is that CUDA allows constant initializers 11972 // for __constant__ and __device__ variables. 11973 void checkAllowedCUDAInitializer(VarDecl *VD); 11974 11975 /// Check whether NewFD is a valid overload for CUDA. Emits 11976 /// diagnostics and invalidates NewFD if not. 11977 void checkCUDATargetOverload(FunctionDecl *NewFD, 11978 const LookupResult &Previous); 11979 /// Copies target attributes from the template TD to the function FD. 11980 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD); 11981 11982 /// Returns the name of the launch configuration function. This is the name 11983 /// of the function that will be called to configure kernel call, with the 11984 /// parameters specified via <<<>>>. 11985 std::string getCudaConfigureFuncName() const; 11986 11987 /// \name Code completion 11988 //@{ 11989 /// Describes the context in which code completion occurs. 11990 enum ParserCompletionContext { 11991 /// Code completion occurs at top-level or namespace context. 11992 PCC_Namespace, 11993 /// Code completion occurs within a class, struct, or union. 11994 PCC_Class, 11995 /// Code completion occurs within an Objective-C interface, protocol, 11996 /// or category. 11997 PCC_ObjCInterface, 11998 /// Code completion occurs within an Objective-C implementation or 11999 /// category implementation 12000 PCC_ObjCImplementation, 12001 /// Code completion occurs within the list of instance variables 12002 /// in an Objective-C interface, protocol, category, or implementation. 12003 PCC_ObjCInstanceVariableList, 12004 /// Code completion occurs following one or more template 12005 /// headers. 12006 PCC_Template, 12007 /// Code completion occurs following one or more template 12008 /// headers within a class. 12009 PCC_MemberTemplate, 12010 /// Code completion occurs within an expression. 12011 PCC_Expression, 12012 /// Code completion occurs within a statement, which may 12013 /// also be an expression or a declaration. 12014 PCC_Statement, 12015 /// Code completion occurs at the beginning of the 12016 /// initialization statement (or expression) in a for loop. 12017 PCC_ForInit, 12018 /// Code completion occurs within the condition of an if, 12019 /// while, switch, or for statement. 12020 PCC_Condition, 12021 /// Code completion occurs within the body of a function on a 12022 /// recovery path, where we do not have a specific handle on our position 12023 /// in the grammar. 12024 PCC_RecoveryInFunction, 12025 /// Code completion occurs where only a type is permitted. 12026 PCC_Type, 12027 /// Code completion occurs in a parenthesized expression, which 12028 /// might also be a type cast. 12029 PCC_ParenthesizedExpression, 12030 /// Code completion occurs within a sequence of declaration 12031 /// specifiers within a function, method, or block. 12032 PCC_LocalDeclarationSpecifiers 12033 }; 12034 12035 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); 12036 void CodeCompleteOrdinaryName(Scope *S, 12037 ParserCompletionContext CompletionContext); 12038 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, 12039 bool AllowNonIdentifiers, 12040 bool AllowNestedNameSpecifiers); 12041 12042 struct CodeCompleteExpressionData; 12043 void CodeCompleteExpression(Scope *S, 12044 const CodeCompleteExpressionData &Data); 12045 void CodeCompleteExpression(Scope *S, QualType PreferredType, 12046 bool IsParenthesized = false); 12047 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase, 12048 SourceLocation OpLoc, bool IsArrow, 12049 bool IsBaseExprStatement, 12050 QualType PreferredType); 12051 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS, 12052 QualType PreferredType); 12053 void CodeCompleteTag(Scope *S, unsigned TagSpec); 12054 void CodeCompleteTypeQualifiers(DeclSpec &DS); 12055 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, 12056 const VirtSpecifiers *VS = nullptr); 12057 void CodeCompleteBracketDeclarator(Scope *S); 12058 void CodeCompleteCase(Scope *S); 12059 /// Reports signatures for a call to CodeCompleteConsumer and returns the 12060 /// preferred type for the current argument. Returned type can be null. 12061 QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args, 12062 SourceLocation OpenParLoc); 12063 QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type, 12064 SourceLocation Loc, 12065 ArrayRef<Expr *> Args, 12066 SourceLocation OpenParLoc); 12067 QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl, 12068 CXXScopeSpec SS, 12069 ParsedType TemplateTypeTy, 12070 ArrayRef<Expr *> ArgExprs, 12071 IdentifierInfo *II, 12072 SourceLocation OpenParLoc); 12073 void CodeCompleteInitializer(Scope *S, Decl *D); 12074 /// Trigger code completion for a record of \p BaseType. \p InitExprs are 12075 /// expressions in the initializer list seen so far and \p D is the current 12076 /// Designation being parsed. 12077 void CodeCompleteDesignator(const QualType BaseType, 12078 llvm::ArrayRef<Expr *> InitExprs, 12079 const Designation &D); 12080 void CodeCompleteAfterIf(Scope *S, bool IsBracedThen); 12081 12082 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext, 12083 bool IsUsingDeclaration, QualType BaseType, 12084 QualType PreferredType); 12085 void CodeCompleteUsing(Scope *S); 12086 void CodeCompleteUsingDirective(Scope *S); 12087 void CodeCompleteNamespaceDecl(Scope *S); 12088 void CodeCompleteNamespaceAliasDecl(Scope *S); 12089 void CodeCompleteOperatorName(Scope *S); 12090 void CodeCompleteConstructorInitializer( 12091 Decl *Constructor, 12092 ArrayRef<CXXCtorInitializer *> Initializers); 12093 12094 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, 12095 bool AfterAmpersand); 12096 void CodeCompleteAfterFunctionEquals(Declarator &D); 12097 12098 void CodeCompleteObjCAtDirective(Scope *S); 12099 void CodeCompleteObjCAtVisibility(Scope *S); 12100 void CodeCompleteObjCAtStatement(Scope *S); 12101 void CodeCompleteObjCAtExpression(Scope *S); 12102 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); 12103 void CodeCompleteObjCPropertyGetter(Scope *S); 12104 void CodeCompleteObjCPropertySetter(Scope *S); 12105 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, 12106 bool IsParameter); 12107 void CodeCompleteObjCMessageReceiver(Scope *S); 12108 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, 12109 ArrayRef<IdentifierInfo *> SelIdents, 12110 bool AtArgumentExpression); 12111 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, 12112 ArrayRef<IdentifierInfo *> SelIdents, 12113 bool AtArgumentExpression, 12114 bool IsSuper = false); 12115 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, 12116 ArrayRef<IdentifierInfo *> SelIdents, 12117 bool AtArgumentExpression, 12118 ObjCInterfaceDecl *Super = nullptr); 12119 void CodeCompleteObjCForCollection(Scope *S, 12120 DeclGroupPtrTy IterationVar); 12121 void CodeCompleteObjCSelector(Scope *S, 12122 ArrayRef<IdentifierInfo *> SelIdents); 12123 void CodeCompleteObjCProtocolReferences( 12124 ArrayRef<IdentifierLocPair> Protocols); 12125 void CodeCompleteObjCProtocolDecl(Scope *S); 12126 void CodeCompleteObjCInterfaceDecl(Scope *S); 12127 void CodeCompleteObjCSuperclass(Scope *S, 12128 IdentifierInfo *ClassName, 12129 SourceLocation ClassNameLoc); 12130 void CodeCompleteObjCImplementationDecl(Scope *S); 12131 void CodeCompleteObjCInterfaceCategory(Scope *S, 12132 IdentifierInfo *ClassName, 12133 SourceLocation ClassNameLoc); 12134 void CodeCompleteObjCImplementationCategory(Scope *S, 12135 IdentifierInfo *ClassName, 12136 SourceLocation ClassNameLoc); 12137 void CodeCompleteObjCPropertyDefinition(Scope *S); 12138 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, 12139 IdentifierInfo *PropertyName); 12140 void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, 12141 ParsedType ReturnType); 12142 void CodeCompleteObjCMethodDeclSelector(Scope *S, 12143 bool IsInstanceMethod, 12144 bool AtParameterName, 12145 ParsedType ReturnType, 12146 ArrayRef<IdentifierInfo *> SelIdents); 12147 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName, 12148 SourceLocation ClassNameLoc, 12149 bool IsBaseExprStatement); 12150 void CodeCompletePreprocessorDirective(bool InConditional); 12151 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); 12152 void CodeCompletePreprocessorMacroName(bool IsDefinition); 12153 void CodeCompletePreprocessorExpression(); 12154 void CodeCompletePreprocessorMacroArgument(Scope *S, 12155 IdentifierInfo *Macro, 12156 MacroInfo *MacroInfo, 12157 unsigned Argument); 12158 void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled); 12159 void CodeCompleteNaturalLanguage(); 12160 void CodeCompleteAvailabilityPlatformName(); 12161 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, 12162 CodeCompletionTUInfo &CCTUInfo, 12163 SmallVectorImpl<CodeCompletionResult> &Results); 12164 //@} 12165 12166 //===--------------------------------------------------------------------===// 12167 // Extra semantic analysis beyond the C type system 12168 12169 public: 12170 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, 12171 unsigned ByteNo) const; 12172 12173 private: 12174 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 12175 const ArraySubscriptExpr *ASE=nullptr, 12176 bool AllowOnePastEnd=true, bool IndexNegated=false); 12177 void CheckArrayAccess(const Expr *E); 12178 // Used to grab the relevant information from a FormatAttr and a 12179 // FunctionDeclaration. 12180 struct FormatStringInfo { 12181 unsigned FormatIdx; 12182 unsigned FirstDataArg; 12183 bool HasVAListArg; 12184 }; 12185 12186 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 12187 FormatStringInfo *FSI); 12188 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 12189 const FunctionProtoType *Proto); 12190 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, 12191 ArrayRef<const Expr *> Args); 12192 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 12193 const FunctionProtoType *Proto); 12194 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto); 12195 void CheckConstructorCall(FunctionDecl *FDecl, 12196 ArrayRef<const Expr *> Args, 12197 const FunctionProtoType *Proto, 12198 SourceLocation Loc); 12199 12200 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 12201 const Expr *ThisArg, ArrayRef<const Expr *> Args, 12202 bool IsMemberFunction, SourceLocation Loc, SourceRange Range, 12203 VariadicCallType CallType); 12204 12205 bool CheckObjCString(Expr *Arg); 12206 ExprResult CheckOSLogFormatStringArg(Expr *Arg); 12207 12208 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, 12209 unsigned BuiltinID, CallExpr *TheCall); 12210 12211 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12212 CallExpr *TheCall); 12213 12214 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall); 12215 12216 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 12217 unsigned MaxWidth); 12218 bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12219 CallExpr *TheCall); 12220 bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 12221 bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 12222 bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12223 CallExpr *TheCall); 12224 bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg, 12225 bool WantCDE); 12226 bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12227 CallExpr *TheCall); 12228 12229 bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12230 CallExpr *TheCall); 12231 bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 12232 bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 12233 bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); 12234 bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12235 CallExpr *TheCall); 12236 bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 12237 CallExpr *TheCall); 12238 bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); 12239 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 12240 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall); 12241 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall); 12242 bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall); 12243 bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 12244 ArrayRef<int> ArgNums); 12245 bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums); 12246 bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 12247 ArrayRef<int> ArgNums); 12248 bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12249 CallExpr *TheCall); 12250 bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12251 CallExpr *TheCall); 12252 bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 12253 12254 bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall); 12255 bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call); 12256 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); 12257 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); 12258 bool SemaBuiltinComplex(CallExpr *TheCall); 12259 bool SemaBuiltinVSX(CallExpr *TheCall); 12260 bool SemaBuiltinOSLogFormat(CallExpr *TheCall); 12261 12262 public: 12263 // Used by C++ template instantiation. 12264 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); 12265 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 12266 SourceLocation BuiltinLoc, 12267 SourceLocation RParenLoc); 12268 12269 private: 12270 bool SemaBuiltinPrefetch(CallExpr *TheCall); 12271 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall); 12272 bool SemaBuiltinAssume(CallExpr *TheCall); 12273 bool SemaBuiltinAssumeAligned(CallExpr *TheCall); 12274 bool SemaBuiltinLongjmp(CallExpr *TheCall); 12275 bool SemaBuiltinSetjmp(CallExpr *TheCall); 12276 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); 12277 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult); 12278 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, 12279 AtomicExpr::AtomicOp Op); 12280 ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, 12281 bool IsDelete); 12282 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 12283 llvm::APSInt &Result); 12284 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, 12285 int High, bool RangeIsError = true); 12286 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 12287 unsigned Multiple); 12288 bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum); 12289 bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 12290 unsigned ArgBits); 12291 bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum, 12292 unsigned ArgBits); 12293 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 12294 int ArgNum, unsigned ExpectedFieldNum, 12295 bool AllowName); 12296 bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall); 12297 bool SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeDesc); 12298 12299 bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc); 12300 12301 // Matrix builtin handling. 12302 ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall, 12303 ExprResult CallResult); 12304 ExprResult SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 12305 ExprResult CallResult); 12306 ExprResult SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 12307 ExprResult CallResult); 12308 12309 public: 12310 enum FormatStringType { 12311 FST_Scanf, 12312 FST_Printf, 12313 FST_NSString, 12314 FST_Strftime, 12315 FST_Strfmon, 12316 FST_Kprintf, 12317 FST_FreeBSDKPrintf, 12318 FST_OSTrace, 12319 FST_OSLog, 12320 FST_Unknown 12321 }; 12322 static FormatStringType GetFormatStringType(const FormatAttr *Format); 12323 12324 bool FormatStringHasSArg(const StringLiteral *FExpr); 12325 12326 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx); 12327 12328 private: 12329 bool CheckFormatArguments(const FormatAttr *Format, 12330 ArrayRef<const Expr *> Args, 12331 bool IsCXXMember, 12332 VariadicCallType CallType, 12333 SourceLocation Loc, SourceRange Range, 12334 llvm::SmallBitVector &CheckedVarArgs); 12335 bool CheckFormatArguments(ArrayRef<const Expr *> Args, 12336 bool HasVAListArg, unsigned format_idx, 12337 unsigned firstDataArg, FormatStringType Type, 12338 VariadicCallType CallType, 12339 SourceLocation Loc, SourceRange range, 12340 llvm::SmallBitVector &CheckedVarArgs); 12341 12342 void CheckAbsoluteValueFunction(const CallExpr *Call, 12343 const FunctionDecl *FDecl); 12344 12345 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl); 12346 12347 void CheckMemaccessArguments(const CallExpr *Call, 12348 unsigned BId, 12349 IdentifierInfo *FnName); 12350 12351 void CheckStrlcpycatArguments(const CallExpr *Call, 12352 IdentifierInfo *FnName); 12353 12354 void CheckStrncatArguments(const CallExpr *Call, 12355 IdentifierInfo *FnName); 12356 12357 void CheckFreeArguments(const CallExpr *E); 12358 12359 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 12360 SourceLocation ReturnLoc, 12361 bool isObjCMethod = false, 12362 const AttrVec *Attrs = nullptr, 12363 const FunctionDecl *FD = nullptr); 12364 12365 public: 12366 void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS); 12367 12368 private: 12369 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); 12370 void CheckBoolLikeConversion(Expr *E, SourceLocation CC); 12371 void CheckForIntOverflow(Expr *E); 12372 void CheckUnsequencedOperations(const Expr *E); 12373 12374 /// Perform semantic checks on a completed expression. This will either 12375 /// be a full-expression or a default argument expression. 12376 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(), 12377 bool IsConstexpr = false); 12378 12379 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, 12380 Expr *Init); 12381 12382 /// Check if there is a field shadowing. 12383 void CheckShadowInheritedFields(const SourceLocation &Loc, 12384 DeclarationName FieldName, 12385 const CXXRecordDecl *RD, 12386 bool DeclIsField = true); 12387 12388 /// Check if the given expression contains 'break' or 'continue' 12389 /// statement that produces control flow different from GCC. 12390 void CheckBreakContinueBinding(Expr *E); 12391 12392 /// Check whether receiver is mutable ObjC container which 12393 /// attempts to add itself into the container 12394 void CheckObjCCircularContainer(ObjCMessageExpr *Message); 12395 12396 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE); 12397 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, 12398 bool DeleteWasArrayForm); 12399 public: 12400 /// Register a magic integral constant to be used as a type tag. 12401 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 12402 uint64_t MagicValue, QualType Type, 12403 bool LayoutCompatible, bool MustBeNull); 12404 12405 struct TypeTagData { TypeTagDataTypeTagData12406 TypeTagData() {} 12407 TypeTagDataTypeTagData12408 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) : 12409 Type(Type), LayoutCompatible(LayoutCompatible), 12410 MustBeNull(MustBeNull) 12411 {} 12412 12413 QualType Type; 12414 12415 /// If true, \c Type should be compared with other expression's types for 12416 /// layout-compatibility. 12417 unsigned LayoutCompatible : 1; 12418 unsigned MustBeNull : 1; 12419 }; 12420 12421 /// A pair of ArgumentKind identifier and magic value. This uniquely 12422 /// identifies the magic value. 12423 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; 12424 12425 private: 12426 /// A map from magic value to type information. 12427 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>> 12428 TypeTagForDatatypeMagicValues; 12429 12430 /// Peform checks on a call of a function with argument_with_type_tag 12431 /// or pointer_with_type_tag attributes. 12432 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 12433 const ArrayRef<const Expr *> ExprArgs, 12434 SourceLocation CallSiteLoc); 12435 12436 /// Check if we are taking the address of a packed field 12437 /// as this may be a problem if the pointer value is dereferenced. 12438 void CheckAddressOfPackedMember(Expr *rhs); 12439 12440 /// The parser's current scope. 12441 /// 12442 /// The parser maintains this state here. 12443 Scope *CurScope; 12444 12445 mutable IdentifierInfo *Ident_super; 12446 mutable IdentifierInfo *Ident___float128; 12447 12448 /// Nullability type specifiers. 12449 IdentifierInfo *Ident__Nonnull = nullptr; 12450 IdentifierInfo *Ident__Nullable = nullptr; 12451 IdentifierInfo *Ident__Nullable_result = nullptr; 12452 IdentifierInfo *Ident__Null_unspecified = nullptr; 12453 12454 IdentifierInfo *Ident_NSError = nullptr; 12455 12456 /// The handler for the FileChanged preprocessor events. 12457 /// 12458 /// Used for diagnostics that implement custom semantic analysis for #include 12459 /// directives, like -Wpragma-pack. 12460 sema::SemaPPCallbacks *SemaPPCallbackHandler; 12461 12462 protected: 12463 friend class Parser; 12464 friend class InitializationSequence; 12465 friend class ASTReader; 12466 friend class ASTDeclReader; 12467 friend class ASTWriter; 12468 12469 public: 12470 /// Retrieve the keyword associated 12471 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability); 12472 12473 /// The struct behind the CFErrorRef pointer. 12474 RecordDecl *CFError = nullptr; 12475 bool isCFError(RecordDecl *D); 12476 12477 /// Retrieve the identifier "NSError". 12478 IdentifierInfo *getNSErrorIdent(); 12479 12480 /// Retrieve the parser's current scope. 12481 /// 12482 /// This routine must only be used when it is certain that semantic analysis 12483 /// and the parser are in precisely the same context, which is not the case 12484 /// when, e.g., we are performing any kind of template instantiation. 12485 /// Therefore, the only safe places to use this scope are in the parser 12486 /// itself and in routines directly invoked from the parser and *never* from 12487 /// template substitution or instantiation. getCurScope()12488 Scope *getCurScope() const { return CurScope; } 12489 incrementMSManglingNumber()12490 void incrementMSManglingNumber() const { 12491 return CurScope->incrementMSManglingNumber(); 12492 } 12493 12494 IdentifierInfo *getSuperIdentifier() const; 12495 IdentifierInfo *getFloat128Identifier() const; 12496 12497 Decl *getObjCDeclContext() const; 12498 getCurLexicalContext()12499 DeclContext *getCurLexicalContext() const { 12500 return OriginalLexicalContext ? OriginalLexicalContext : CurContext; 12501 } 12502 getCurObjCLexicalContext()12503 const DeclContext *getCurObjCLexicalContext() const { 12504 const DeclContext *DC = getCurLexicalContext(); 12505 // A category implicitly has the attribute of the interface. 12506 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC)) 12507 DC = CatD->getClassInterface(); 12508 return DC; 12509 } 12510 12511 /// Determine the number of levels of enclosing template parameters. This is 12512 /// only usable while parsing. Note that this does not include dependent 12513 /// contexts in which no template parameters have yet been declared, such as 12514 /// in a terse function template or generic lambda before the first 'auto' is 12515 /// encountered. 12516 unsigned getTemplateDepth(Scope *S) const; 12517 12518 /// To be used for checking whether the arguments being passed to 12519 /// function exceeds the number of parameters expected for it. 12520 static bool TooManyArguments(size_t NumParams, size_t NumArgs, 12521 bool PartialOverloading = false) { 12522 // We check whether we're just after a comma in code-completion. 12523 if (NumArgs > 0 && PartialOverloading) 12524 return NumArgs + 1 > NumParams; // If so, we view as an extra argument. 12525 return NumArgs > NumParams; 12526 } 12527 12528 // Emitting members of dllexported classes is delayed until the class 12529 // (including field initializers) is fully parsed. 12530 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses; 12531 SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions; 12532 12533 private: 12534 int ParsingClassDepth = 0; 12535 12536 class SavePendingParsedClassStateRAII { 12537 public: SavePendingParsedClassStateRAII(Sema & S)12538 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); } 12539 ~SavePendingParsedClassStateRAII()12540 ~SavePendingParsedClassStateRAII() { 12541 assert(S.DelayedOverridingExceptionSpecChecks.empty() && 12542 "there shouldn't be any pending delayed exception spec checks"); 12543 assert(S.DelayedEquivalentExceptionSpecChecks.empty() && 12544 "there shouldn't be any pending delayed exception spec checks"); 12545 swapSavedState(); 12546 } 12547 12548 private: 12549 Sema &S; 12550 decltype(DelayedOverridingExceptionSpecChecks) 12551 SavedOverridingExceptionSpecChecks; 12552 decltype(DelayedEquivalentExceptionSpecChecks) 12553 SavedEquivalentExceptionSpecChecks; 12554 swapSavedState()12555 void swapSavedState() { 12556 SavedOverridingExceptionSpecChecks.swap( 12557 S.DelayedOverridingExceptionSpecChecks); 12558 SavedEquivalentExceptionSpecChecks.swap( 12559 S.DelayedEquivalentExceptionSpecChecks); 12560 } 12561 }; 12562 12563 /// Helper class that collects misaligned member designations and 12564 /// their location info for delayed diagnostics. 12565 struct MisalignedMember { 12566 Expr *E; 12567 RecordDecl *RD; 12568 ValueDecl *MD; 12569 CharUnits Alignment; 12570 MisalignedMemberMisalignedMember12571 MisalignedMember() : E(), RD(), MD(), Alignment() {} MisalignedMemberMisalignedMember12572 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD, 12573 CharUnits Alignment) 12574 : E(E), RD(RD), MD(MD), Alignment(Alignment) {} MisalignedMemberMisalignedMember12575 explicit MisalignedMember(Expr *E) 12576 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {} 12577 12578 bool operator==(const MisalignedMember &m) { return this->E == m.E; } 12579 }; 12580 /// Small set of gathered accesses to potentially misaligned members 12581 /// due to the packed attribute. 12582 SmallVector<MisalignedMember, 4> MisalignedMembers; 12583 12584 /// Adds an expression to the set of gathered misaligned members. 12585 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 12586 CharUnits Alignment); 12587 12588 public: 12589 /// Diagnoses the current set of gathered accesses. This typically 12590 /// happens at full expression level. The set is cleared after emitting the 12591 /// diagnostics. 12592 void DiagnoseMisalignedMembers(); 12593 12594 /// This function checks if the expression is in the sef of potentially 12595 /// misaligned members and it is converted to some pointer type T with lower 12596 /// or equal alignment requirements. If so it removes it. This is used when 12597 /// we do not want to diagnose such misaligned access (e.g. in conversions to 12598 /// void*). 12599 void DiscardMisalignedMemberAddress(const Type *T, Expr *E); 12600 12601 /// This function calls Action when it determines that E designates a 12602 /// misaligned member due to the packed attribute. This is used to emit 12603 /// local diagnostics like in reference binding. 12604 void RefersToMemberWithReducedAlignment( 12605 Expr *E, 12606 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 12607 Action); 12608 12609 /// Describes the reason a calling convention specification was ignored, used 12610 /// for diagnostics. 12611 enum class CallingConventionIgnoredReason { 12612 ForThisTarget = 0, 12613 VariadicFunction, 12614 ConstructorDestructor, 12615 BuiltinFunction 12616 }; 12617 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current 12618 /// context is "used as device code". 12619 /// 12620 /// - If CurLexicalContext is a kernel function or it is known that the 12621 /// function will be emitted for the device, emits the diagnostics 12622 /// immediately. 12623 /// - If CurLexicalContext is a function and we are compiling 12624 /// for the device, but we don't know that this function will be codegen'ed 12625 /// for devive yet, creates a diagnostic which is emitted if and when we 12626 /// realize that the function will be codegen'ed. 12627 /// 12628 /// Example usage: 12629 /// 12630 /// Diagnose __float128 type usage only from SYCL device code if the current 12631 /// target doesn't support it 12632 /// if (!S.Context.getTargetInfo().hasFloat128Type() && 12633 /// S.getLangOpts().SYCLIsDevice) 12634 /// SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128"; 12635 SemaDiagnosticBuilder SYCLDiagIfDeviceCode(SourceLocation Loc, 12636 unsigned DiagID); 12637 12638 /// Check whether we're allowed to call Callee from the current context. 12639 /// 12640 /// - If the call is never allowed in a semantically-correct program 12641 /// emits an error and returns false. 12642 /// 12643 /// - If the call is allowed in semantically-correct programs, but only if 12644 /// it's never codegen'ed, creates a deferred diagnostic to be emitted if 12645 /// and when the caller is codegen'ed, and returns true. 12646 /// 12647 /// - Otherwise, returns true without emitting any diagnostics. 12648 /// 12649 /// Adds Callee to DeviceCallGraph if we don't know if its caller will be 12650 /// codegen'ed yet. 12651 bool checkSYCLDeviceFunction(SourceLocation Loc, FunctionDecl *Callee); 12652 }; 12653 12654 /// RAII object that enters a new expression evaluation context. 12655 class EnterExpressionEvaluationContext { 12656 Sema &Actions; 12657 bool Entered = true; 12658 12659 public: 12660 EnterExpressionEvaluationContext( 12661 Sema &Actions, Sema::ExpressionEvaluationContext NewContext, 12662 Decl *LambdaContextDecl = nullptr, 12663 Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = 12664 Sema::ExpressionEvaluationContextRecord::EK_Other, 12665 bool ShouldEnter = true) Actions(Actions)12666 : Actions(Actions), Entered(ShouldEnter) { 12667 if (Entered) 12668 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, 12669 ExprContext); 12670 } 12671 EnterExpressionEvaluationContext( 12672 Sema &Actions, Sema::ExpressionEvaluationContext NewContext, 12673 Sema::ReuseLambdaContextDecl_t, 12674 Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = 12675 Sema::ExpressionEvaluationContextRecord::EK_Other) Actions(Actions)12676 : Actions(Actions) { 12677 Actions.PushExpressionEvaluationContext( 12678 NewContext, Sema::ReuseLambdaContextDecl, ExprContext); 12679 } 12680 12681 enum InitListTag { InitList }; 12682 EnterExpressionEvaluationContext(Sema &Actions, InitListTag, 12683 bool ShouldEnter = true) Actions(Actions)12684 : Actions(Actions), Entered(false) { 12685 // In C++11 onwards, narrowing checks are performed on the contents of 12686 // braced-init-lists, even when they occur within unevaluated operands. 12687 // Therefore we still need to instantiate constexpr functions used in such 12688 // a context. 12689 if (ShouldEnter && Actions.isUnevaluatedContext() && 12690 Actions.getLangOpts().CPlusPlus11) { 12691 Actions.PushExpressionEvaluationContext( 12692 Sema::ExpressionEvaluationContext::UnevaluatedList); 12693 Entered = true; 12694 } 12695 } 12696 ~EnterExpressionEvaluationContext()12697 ~EnterExpressionEvaluationContext() { 12698 if (Entered) 12699 Actions.PopExpressionEvaluationContext(); 12700 } 12701 }; 12702 12703 DeductionFailureInfo 12704 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, 12705 sema::TemplateDeductionInfo &Info); 12706 12707 /// Contains a late templated function. 12708 /// Will be parsed at the end of the translation unit, used by Sema & Parser. 12709 struct LateParsedTemplate { 12710 CachedTokens Toks; 12711 /// The template function declaration to be late parsed. 12712 Decl *D; 12713 }; 12714 } // end namespace clang 12715 12716 namespace llvm { 12717 // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its 12718 // SourceLocation. 12719 template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> { 12720 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc; 12721 using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>; 12722 12723 static FunctionDeclAndLoc getEmptyKey() { 12724 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()}; 12725 } 12726 12727 static FunctionDeclAndLoc getTombstoneKey() { 12728 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()}; 12729 } 12730 12731 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) { 12732 return hash_combine(FDBaseInfo::getHashValue(FDL.FD), 12733 FDL.Loc.getHashValue()); 12734 } 12735 12736 static bool isEqual(const FunctionDeclAndLoc &LHS, 12737 const FunctionDeclAndLoc &RHS) { 12738 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc; 12739 } 12740 }; 12741 } // namespace llvm 12742 12743 #endif 12744