1 //===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the Sema class, which performs semantic analysis and 11 // builds ASTs. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #ifndef LLVM_CLANG_SEMA_SEMA_H 16 #define LLVM_CLANG_SEMA_SEMA_H 17 18 #include "clang/AST/Attr.h" 19 #include "clang/AST/DeclarationName.h" 20 #include "clang/AST/Expr.h" 21 #include "clang/AST/ExprObjC.h" 22 #include "clang/AST/ExternalASTSource.h" 23 #include "clang/AST/MangleNumberingContext.h" 24 #include "clang/AST/NSAPI.h" 25 #include "clang/AST/PrettyPrinter.h" 26 #include "clang/AST/TypeLoc.h" 27 #include "clang/Basic/ExpressionTraits.h" 28 #include "clang/Basic/LangOptions.h" 29 #include "clang/Basic/Module.h" 30 #include "clang/Basic/OpenMPKinds.h" 31 #include "clang/Basic/Specifiers.h" 32 #include "clang/Basic/TemplateKinds.h" 33 #include "clang/Basic/TypeTraits.h" 34 #include "clang/Sema/AnalysisBasedWarnings.h" 35 #include "clang/Sema/DeclSpec.h" 36 #include "clang/Sema/ExternalSemaSource.h" 37 #include "clang/Sema/IdentifierResolver.h" 38 #include "clang/Sema/LocInfoType.h" 39 #include "clang/Sema/ObjCMethodList.h" 40 #include "clang/Sema/Ownership.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/TypoCorrection.h" 44 #include "clang/Sema/Weak.h" 45 #include "llvm/ADT/ArrayRef.h" 46 #include "llvm/ADT/Optional.h" 47 #include "llvm/ADT/SetVector.h" 48 #include "llvm/ADT/SmallPtrSet.h" 49 #include "llvm/ADT/SmallVector.h" 50 #include "llvm/ADT/TinyPtrVector.h" 51 #include <deque> 52 #include <memory> 53 #include <string> 54 #include <vector> 55 56 namespace llvm { 57 class APSInt; 58 template <typename ValueT> struct DenseMapInfo; 59 template <typename ValueT, typename ValueInfoT> class DenseSet; 60 class SmallBitVector; 61 class InlineAsmIdentifierInfo; 62 } 63 64 namespace clang { 65 class ADLResult; 66 class ASTConsumer; 67 class ASTContext; 68 class ASTMutationListener; 69 class ASTReader; 70 class ASTWriter; 71 class ArrayType; 72 class AttributeList; 73 class BlockDecl; 74 class CapturedDecl; 75 class CXXBasePath; 76 class CXXBasePaths; 77 class CXXBindTemporaryExpr; 78 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; 79 class CXXConstructorDecl; 80 class CXXConversionDecl; 81 class CXXDestructorDecl; 82 class CXXFieldCollector; 83 class CXXMemberCallExpr; 84 class CXXMethodDecl; 85 class CXXScopeSpec; 86 class CXXTemporary; 87 class CXXTryStmt; 88 class CallExpr; 89 class ClassTemplateDecl; 90 class ClassTemplatePartialSpecializationDecl; 91 class ClassTemplateSpecializationDecl; 92 class VarTemplatePartialSpecializationDecl; 93 class CodeCompleteConsumer; 94 class CodeCompletionAllocator; 95 class CodeCompletionTUInfo; 96 class CodeCompletionResult; 97 class Decl; 98 class DeclAccessPair; 99 class DeclContext; 100 class DeclRefExpr; 101 class DeclaratorDecl; 102 class DeducedTemplateArgument; 103 class DependentDiagnostic; 104 class DesignatedInitExpr; 105 class Designation; 106 class EnableIfAttr; 107 class EnumConstantDecl; 108 class Expr; 109 class ExtVectorType; 110 class ExternalSemaSource; 111 class FormatAttr; 112 class FriendDecl; 113 class FunctionDecl; 114 class FunctionProtoType; 115 class FunctionTemplateDecl; 116 class ImplicitConversionSequence; 117 class InitListExpr; 118 class InitializationKind; 119 class InitializationSequence; 120 class InitializedEntity; 121 class IntegerLiteral; 122 class LabelStmt; 123 class LambdaExpr; 124 class LangOptions; 125 class LocalInstantiationScope; 126 class LookupResult; 127 class MacroInfo; 128 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath; 129 class ModuleLoader; 130 class MultiLevelTemplateArgumentList; 131 class NamedDecl; 132 class ObjCCategoryDecl; 133 class ObjCCategoryImplDecl; 134 class ObjCCompatibleAliasDecl; 135 class ObjCContainerDecl; 136 class ObjCImplDecl; 137 class ObjCImplementationDecl; 138 class ObjCInterfaceDecl; 139 class ObjCIvarDecl; 140 template <class T> class ObjCList; 141 class ObjCMessageExpr; 142 class ObjCMethodDecl; 143 class ObjCPropertyDecl; 144 class ObjCProtocolDecl; 145 class OMPThreadPrivateDecl; 146 class OMPClause; 147 class OverloadCandidateSet; 148 class OverloadExpr; 149 class ParenListExpr; 150 class ParmVarDecl; 151 class Preprocessor; 152 class PseudoDestructorTypeStorage; 153 class PseudoObjectExpr; 154 class QualType; 155 class StandardConversionSequence; 156 class Stmt; 157 class StringLiteral; 158 class SwitchStmt; 159 class TemplateArgument; 160 class TemplateArgumentList; 161 class TemplateArgumentLoc; 162 class TemplateDecl; 163 class TemplateParameterList; 164 class TemplatePartialOrderingContext; 165 class TemplateTemplateParmDecl; 166 class Token; 167 class TypeAliasDecl; 168 class TypedefDecl; 169 class TypedefNameDecl; 170 class TypeLoc; 171 class TypoCorrectionConsumer; 172 class UnqualifiedId; 173 class UnresolvedLookupExpr; 174 class UnresolvedMemberExpr; 175 class UnresolvedSetImpl; 176 class UnresolvedSetIterator; 177 class UsingDecl; 178 class UsingShadowDecl; 179 class ValueDecl; 180 class VarDecl; 181 class VarTemplateSpecializationDecl; 182 class VisibilityAttr; 183 class VisibleDeclConsumer; 184 class IndirectFieldDecl; 185 struct DeductionFailureInfo; 186 class TemplateSpecCandidateSet; 187 188 namespace sema { 189 class AccessedEntity; 190 class BlockScopeInfo; 191 class CapturedRegionScopeInfo; 192 class CapturingScopeInfo; 193 class CompoundScopeInfo; 194 class DelayedDiagnostic; 195 class DelayedDiagnosticPool; 196 class FunctionScopeInfo; 197 class LambdaScopeInfo; 198 class PossiblyUnreachableDiag; 199 class TemplateDeductionInfo; 200 } 201 202 namespace threadSafety { 203 class BeforeSet; 204 void threadSafetyCleanup(BeforeSet* Cache); 205 } 206 207 // FIXME: No way to easily map from TemplateTypeParmTypes to 208 // TemplateTypeParmDecls, so we have this horrible PointerUnion. 209 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, 210 SourceLocation> UnexpandedParameterPack; 211 212 /// Sema - This implements semantic analysis and AST building for C. 213 class Sema { 214 Sema(const Sema &) = delete; 215 void operator=(const Sema &) = delete; 216 217 ///\brief Source of additional semantic information. 218 ExternalSemaSource *ExternalSource; 219 220 ///\brief Whether Sema has generated a multiplexer and has to delete it. 221 bool isMultiplexExternalSource; 222 223 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); 224 225 static bool shouldLinkPossiblyHiddenDecl(const NamedDecl * Old,const NamedDecl * New)226 shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, const NamedDecl *New) { 227 // We are about to link these. It is now safe to compute the linkage of 228 // the new decl. If the new decl has external linkage, we will 229 // link it with the hidden decl (which also has external linkage) and 230 // it will keep having external linkage. If it has internal linkage, we 231 // will not link it. Since it has no previous decls, it will remain 232 // with internal linkage. 233 return !Old->isHidden() || New->isExternallyVisible(); 234 } 235 236 public: 237 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; 238 typedef OpaquePtr<TemplateName> TemplateTy; 239 typedef OpaquePtr<QualType> TypeTy; 240 241 OpenCLOptions OpenCLFeatures; 242 FPOptions FPFeatures; 243 244 const LangOptions &LangOpts; 245 Preprocessor &PP; 246 ASTContext &Context; 247 ASTConsumer &Consumer; 248 DiagnosticsEngine &Diags; 249 SourceManager &SourceMgr; 250 251 /// \brief Flag indicating whether or not to collect detailed statistics. 252 bool CollectStats; 253 254 /// \brief Code-completion consumer. 255 CodeCompleteConsumer *CodeCompleter; 256 257 /// CurContext - This is the current declaration context of parsing. 258 DeclContext *CurContext; 259 260 /// \brief Generally null except when we temporarily switch decl contexts, 261 /// like in \see ActOnObjCTemporaryExitContainerContext. 262 DeclContext *OriginalLexicalContext; 263 264 /// VAListTagName - The declaration name corresponding to __va_list_tag. 265 /// This is used as part of a hack to omit that class from ADL results. 266 DeclarationName VAListTagName; 267 268 /// PackContext - Manages the stack for \#pragma pack. An alignment 269 /// of 0 indicates default alignment. 270 void *PackContext; // Really a "PragmaPackStack*" 271 272 bool MSStructPragmaOn; // True when \#pragma ms_struct on 273 274 /// \brief Controls member pointer representation format under the MS ABI. 275 LangOptions::PragmaMSPointersToMembersKind 276 MSPointerToMemberRepresentationMethod; 277 278 enum PragmaVtorDispKind { 279 PVDK_Push, ///< #pragma vtordisp(push, mode) 280 PVDK_Set, ///< #pragma vtordisp(mode) 281 PVDK_Pop, ///< #pragma vtordisp(pop) 282 PVDK_Reset ///< #pragma vtordisp() 283 }; 284 285 enum PragmaMsStackAction { 286 PSK_Reset, // #pragma () 287 PSK_Set, // #pragma ("name") 288 PSK_Push, // #pragma (push[, id]) 289 PSK_Push_Set, // #pragma (push[, id], "name") 290 PSK_Pop, // #pragma (pop[, id]) 291 PSK_Pop_Set, // #pragma (pop[, id], "name") 292 }; 293 294 /// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft 295 /// C++ ABI. Possible values are 0, 1, and 2, which mean: 296 /// 297 /// 0: Suppress all vtordisps 298 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial 299 /// structors 300 /// 2: Always insert vtordisps to support RTTI on partially constructed 301 /// objects 302 /// 303 /// The stack always has at least one element in it. 304 SmallVector<MSVtorDispAttr::Mode, 2> VtorDispModeStack; 305 306 /// Stack of active SEH __finally scopes. Can be empty. 307 SmallVector<Scope*, 2> CurrentSEHFinally; 308 309 /// \brief Source location for newly created implicit MSInheritanceAttrs 310 SourceLocation ImplicitMSInheritanceAttrLoc; 311 312 template<typename ValueType> 313 struct PragmaStack { 314 struct Slot { 315 llvm::StringRef StackSlotLabel; 316 ValueType Value; 317 SourceLocation PragmaLocation; SlotPragmaStack::Slot318 Slot(llvm::StringRef StackSlotLabel, 319 ValueType Value, 320 SourceLocation PragmaLocation) 321 : StackSlotLabel(StackSlotLabel), Value(Value), 322 PragmaLocation(PragmaLocation) {} 323 }; 324 void Act(SourceLocation PragmaLocation, 325 PragmaMsStackAction Action, 326 llvm::StringRef StackSlotLabel, 327 ValueType Value); PragmaStackPragmaStack328 explicit PragmaStack(const ValueType &Value) 329 : CurrentValue(Value) {} 330 SmallVector<Slot, 2> Stack; 331 ValueType CurrentValue; 332 SourceLocation CurrentPragmaLocation; 333 }; 334 // FIXME: We should serialize / deserialize these if they occur in a PCH (but 335 // we shouldn't do so if they're in a module). 336 PragmaStack<StringLiteral *> DataSegStack; 337 PragmaStack<StringLiteral *> BSSSegStack; 338 PragmaStack<StringLiteral *> ConstSegStack; 339 PragmaStack<StringLiteral *> CodeSegStack; 340 341 /// Last section used with #pragma init_seg. 342 StringLiteral *CurInitSeg; 343 SourceLocation CurInitSegLoc; 344 345 /// VisContext - Manages the stack for \#pragma GCC visibility. 346 void *VisContext; // Really a "PragmaVisStack*" 347 348 /// \brief This represents the last location of a "#pragma clang optimize off" 349 /// directive if such a directive has not been closed by an "on" yet. If 350 /// optimizations are currently "on", this is set to an invalid location. 351 SourceLocation OptimizeOffPragmaLocation; 352 353 /// \brief Flag indicating if Sema is building a recovery call expression. 354 /// 355 /// This flag is used to avoid building recovery call expressions 356 /// if Sema is already doing so, which would cause infinite recursions. 357 bool IsBuildingRecoveryCallExpr; 358 359 /// ExprNeedsCleanups - True if the current evaluation context 360 /// requires cleanups to be run at its conclusion. 361 bool ExprNeedsCleanups; 362 363 /// ExprCleanupObjects - This is the stack of objects requiring 364 /// cleanup that are created by the current full expression. The 365 /// element type here is ExprWithCleanups::Object. 366 SmallVector<BlockDecl*, 8> ExprCleanupObjects; 367 368 /// \brief Store a list of either DeclRefExprs or MemberExprs 369 /// that contain a reference to a variable (constant) that may or may not 370 /// be odr-used in this Expr, and we won't know until all lvalue-to-rvalue 371 /// and discarded value conversions have been applied to all subexpressions 372 /// of the enclosing full expression. This is cleared at the end of each 373 /// full expression. 374 llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs; 375 376 /// \brief Stack containing information about each of the nested 377 /// function, block, and method scopes that are currently active. 378 /// 379 /// This array is never empty. Clients should ignore the first 380 /// element, which is used to cache a single FunctionScopeInfo 381 /// that's used to parse every top-level function. 382 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; 383 384 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, 385 &ExternalSemaSource::ReadExtVectorDecls, 2, 2> 386 ExtVectorDeclsType; 387 388 /// ExtVectorDecls - This is a list all the extended vector types. This allows 389 /// us to associate a raw vector type with one of the ext_vector type names. 390 /// This is only necessary for issuing pretty diagnostics. 391 ExtVectorDeclsType ExtVectorDecls; 392 393 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. 394 std::unique_ptr<CXXFieldCollector> FieldCollector; 395 396 typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType; 397 398 /// \brief Set containing all declared private fields that are not used. 399 NamedDeclSetType UnusedPrivateFields; 400 401 /// \brief Set containing all typedefs that are likely unused. 402 llvm::SmallSetVector<const TypedefNameDecl *, 4> 403 UnusedLocalTypedefNameCandidates; 404 405 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; 406 407 /// PureVirtualClassDiagSet - a set of class declarations which we have 408 /// emitted a list of pure virtual functions. Used to prevent emitting the 409 /// same list more than once. 410 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet; 411 412 /// ParsingInitForAutoVars - a set of declarations with auto types for which 413 /// we are currently parsing the initializer. 414 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; 415 416 /// \brief Look for a locally scoped extern "C" declaration by the given name. 417 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name); 418 419 typedef LazyVector<VarDecl *, ExternalSemaSource, 420 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> 421 TentativeDefinitionsType; 422 423 /// \brief All the tentative definitions encountered in the TU. 424 TentativeDefinitionsType TentativeDefinitions; 425 426 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, 427 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> 428 UnusedFileScopedDeclsType; 429 430 /// \brief The set of file scoped decls seen so far that have not been used 431 /// and must warn if not used. Only contains the first declaration. 432 UnusedFileScopedDeclsType UnusedFileScopedDecls; 433 434 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, 435 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> 436 DelegatingCtorDeclsType; 437 438 /// \brief All the delegating constructors seen so far in the file, used for 439 /// cycle detection at the end of the TU. 440 DelegatingCtorDeclsType DelegatingCtorDecls; 441 442 /// \brief All the overriding functions seen during a class definition 443 /// that had their exception spec checks delayed, plus the overridden 444 /// function. 445 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2> 446 DelayedExceptionSpecChecks; 447 448 /// \brief All the members seen during a class definition which were both 449 /// explicitly defaulted and had explicitly-specified exception 450 /// specifications, along with the function type containing their 451 /// user-specified exception specification. Those exception specifications 452 /// were overridden with the default specifications, but we still need to 453 /// check whether they are compatible with the default specification, and 454 /// we can't do that until the nesting set of class definitions is complete. 455 SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2> 456 DelayedDefaultedMemberExceptionSpecs; 457 458 typedef llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> 459 LateParsedTemplateMapT; 460 LateParsedTemplateMapT LateParsedTemplateMap; 461 462 /// \brief Callback to the parser to parse templated functions when needed. 463 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT); 464 typedef void LateTemplateParserCleanupCB(void *P); 465 LateTemplateParserCB *LateTemplateParser; 466 LateTemplateParserCleanupCB *LateTemplateParserCleanup; 467 void *OpaqueParser; 468 SetLateTemplateParser(LateTemplateParserCB * LTP,LateTemplateParserCleanupCB * LTPCleanup,void * P)469 void SetLateTemplateParser(LateTemplateParserCB *LTP, 470 LateTemplateParserCleanupCB *LTPCleanup, 471 void *P) { 472 LateTemplateParser = LTP; 473 LateTemplateParserCleanup = LTPCleanup; 474 OpaqueParser = P; 475 } 476 477 class DelayedDiagnostics; 478 479 class DelayedDiagnosticsState { 480 sema::DelayedDiagnosticPool *SavedPool; 481 friend class Sema::DelayedDiagnostics; 482 }; 483 typedef DelayedDiagnosticsState ParsingDeclState; 484 typedef DelayedDiagnosticsState ProcessingContextState; 485 486 /// A class which encapsulates the logic for delaying diagnostics 487 /// during parsing and other processing. 488 class DelayedDiagnostics { 489 /// \brief The current pool of diagnostics into which delayed 490 /// diagnostics should go. 491 sema::DelayedDiagnosticPool *CurPool; 492 493 public: DelayedDiagnostics()494 DelayedDiagnostics() : CurPool(nullptr) {} 495 496 /// Adds a delayed diagnostic. 497 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h 498 499 /// Determines whether diagnostics should be delayed. shouldDelayDiagnostics()500 bool shouldDelayDiagnostics() { return CurPool != nullptr; } 501 502 /// Returns the current delayed-diagnostics pool. getCurrentPool()503 sema::DelayedDiagnosticPool *getCurrentPool() const { 504 return CurPool; 505 } 506 507 /// Enter a new scope. Access and deprecation diagnostics will be 508 /// collected in this pool. push(sema::DelayedDiagnosticPool & pool)509 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { 510 DelayedDiagnosticsState state; 511 state.SavedPool = CurPool; 512 CurPool = &pool; 513 return state; 514 } 515 516 /// Leave a delayed-diagnostic state that was previously pushed. 517 /// Do not emit any of the diagnostics. This is performed as part 518 /// of the bookkeeping of popping a pool "properly". popWithoutEmitting(DelayedDiagnosticsState state)519 void popWithoutEmitting(DelayedDiagnosticsState state) { 520 CurPool = state.SavedPool; 521 } 522 523 /// Enter a new scope where access and deprecation diagnostics are 524 /// not delayed. pushUndelayed()525 DelayedDiagnosticsState pushUndelayed() { 526 DelayedDiagnosticsState state; 527 state.SavedPool = CurPool; 528 CurPool = nullptr; 529 return state; 530 } 531 532 /// Undo a previous pushUndelayed(). popUndelayed(DelayedDiagnosticsState state)533 void popUndelayed(DelayedDiagnosticsState state) { 534 assert(CurPool == nullptr); 535 CurPool = state.SavedPool; 536 } 537 } DelayedDiagnostics; 538 539 /// A RAII object to temporarily push a declaration context. 540 class ContextRAII { 541 private: 542 Sema &S; 543 DeclContext *SavedContext; 544 ProcessingContextState SavedContextState; 545 QualType SavedCXXThisTypeOverride; 546 547 public: 548 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) S(S)549 : S(S), SavedContext(S.CurContext), 550 SavedContextState(S.DelayedDiagnostics.pushUndelayed()), 551 SavedCXXThisTypeOverride(S.CXXThisTypeOverride) 552 { 553 assert(ContextToPush && "pushing null context"); 554 S.CurContext = ContextToPush; 555 if (NewThisContext) 556 S.CXXThisTypeOverride = QualType(); 557 } 558 pop()559 void pop() { 560 if (!SavedContext) return; 561 S.CurContext = SavedContext; 562 S.DelayedDiagnostics.popUndelayed(SavedContextState); 563 S.CXXThisTypeOverride = SavedCXXThisTypeOverride; 564 SavedContext = nullptr; 565 } 566 ~ContextRAII()567 ~ContextRAII() { 568 pop(); 569 } 570 }; 571 572 /// \brief RAII object to handle the state changes required to synthesize 573 /// a function body. 574 class SynthesizedFunctionScope { 575 Sema &S; 576 Sema::ContextRAII SavedContext; 577 578 public: SynthesizedFunctionScope(Sema & S,DeclContext * DC)579 SynthesizedFunctionScope(Sema &S, DeclContext *DC) 580 : S(S), SavedContext(S, DC) 581 { 582 S.PushFunctionScope(); 583 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 584 } 585 ~SynthesizedFunctionScope()586 ~SynthesizedFunctionScope() { 587 S.PopExpressionEvaluationContext(); 588 S.PopFunctionScopeInfo(); 589 } 590 }; 591 592 /// WeakUndeclaredIdentifiers - Identifiers contained in 593 /// \#pragma weak before declared. rare. may alias another 594 /// identifier, declared or undeclared 595 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers; 596 597 /// ExtnameUndeclaredIdentifiers - Identifiers contained in 598 /// \#pragma redefine_extname before declared. Used in Solaris system headers 599 /// to define functions that occur in multiple standards to call the version 600 /// in the currently selected standard. 601 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers; 602 603 604 /// \brief Load weak undeclared identifiers from the external source. 605 void LoadExternalWeakUndeclaredIdentifiers(); 606 607 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by 608 /// \#pragma weak during processing of other Decls. 609 /// I couldn't figure out a clean way to generate these in-line, so 610 /// we store them here and handle separately -- which is a hack. 611 /// It would be best to refactor this. 612 SmallVector<Decl*,2> WeakTopLevelDecl; 613 614 IdentifierResolver IdResolver; 615 616 /// Translation Unit Scope - useful to Objective-C actions that need 617 /// to lookup file scope declarations in the "ordinary" C decl namespace. 618 /// For example, user-defined classes, built-in "id" type, etc. 619 Scope *TUScope; 620 621 /// \brief The C++ "std" namespace, where the standard library resides. 622 LazyDeclPtr StdNamespace; 623 624 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++ 625 /// standard library. 626 LazyDeclPtr StdBadAlloc; 627 628 /// \brief The C++ "std::initializer_list" template, which is defined in 629 /// \<initializer_list>. 630 ClassTemplateDecl *StdInitializerList; 631 632 /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>. 633 RecordDecl *CXXTypeInfoDecl; 634 635 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files. 636 RecordDecl *MSVCGuidDecl; 637 638 /// \brief Caches identifiers/selectors for NSFoundation APIs. 639 std::unique_ptr<NSAPI> NSAPIObj; 640 641 /// \brief The declaration of the Objective-C NSNumber class. 642 ObjCInterfaceDecl *NSNumberDecl; 643 644 /// \brief Pointer to NSNumber type (NSNumber *). 645 QualType NSNumberPointer; 646 647 /// \brief The Objective-C NSNumber methods used to create NSNumber literals. 648 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; 649 650 /// \brief The declaration of the Objective-C NSString class. 651 ObjCInterfaceDecl *NSStringDecl; 652 653 /// \brief Pointer to NSString type (NSString *). 654 QualType NSStringPointer; 655 656 /// \brief The declaration of the stringWithUTF8String: method. 657 ObjCMethodDecl *StringWithUTF8StringMethod; 658 659 /// \brief The declaration of the Objective-C NSArray class. 660 ObjCInterfaceDecl *NSArrayDecl; 661 662 /// \brief Pointer to NSMutableArray type (NSMutableArray *). 663 QualType NSMutableArrayPointer; 664 665 /// \brief The declaration of the arrayWithObjects:count: method. 666 ObjCMethodDecl *ArrayWithObjectsMethod; 667 668 /// \brief The declaration of the Objective-C NSDictionary class. 669 ObjCInterfaceDecl *NSDictionaryDecl; 670 671 /// \brief Pointer to NSMutableDictionary type (NSMutableDictionary *). 672 QualType NSMutableDictionaryPointer; 673 674 /// \brief Pointer to NSMutableSet type (NSMutableSet *). 675 QualType NSMutableSetPointer; 676 677 /// \brief Pointer to NSCountedSet type (NSCountedSet *). 678 QualType NSCountedSetPointer; 679 680 /// \brief Pointer to NSMutableOrderedSet type (NSMutableOrderedSet *). 681 QualType NSMutableOrderedSetPointer; 682 683 /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method. 684 ObjCMethodDecl *DictionaryWithObjectsMethod; 685 686 /// \brief id<NSCopying> type. 687 QualType QIDNSCopying; 688 689 /// \brief will hold 'respondsToSelector:' 690 Selector RespondsToSelectorSel; 691 692 /// \brief counter for internal MS Asm label names. 693 unsigned MSAsmLabelNameCounter; 694 695 /// A flag to remember whether the implicit forms of operator new and delete 696 /// have been declared. 697 bool GlobalNewDeleteDeclared; 698 699 /// A flag to indicate that we're in a context that permits abstract 700 /// references to fields. This is really a 701 bool AllowAbstractFieldReference; 702 703 /// \brief Describes how the expressions currently being parsed are 704 /// evaluated at run-time, if at all. 705 enum ExpressionEvaluationContext { 706 /// \brief The current expression and its subexpressions occur within an 707 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of 708 /// \c sizeof, where the type of the expression may be significant but 709 /// no code will be generated to evaluate the value of the expression at 710 /// run time. 711 Unevaluated, 712 713 /// \brief The current expression occurs within an unevaluated 714 /// operand that unconditionally permits abstract references to 715 /// fields, such as a SIZE operator in MS-style inline assembly. 716 UnevaluatedAbstract, 717 718 /// \brief The current context is "potentially evaluated" in C++11 terms, 719 /// but the expression is evaluated at compile-time (like the values of 720 /// cases in a switch statement). 721 ConstantEvaluated, 722 723 /// \brief The current expression is potentially evaluated at run time, 724 /// which means that code may be generated to evaluate the value of the 725 /// expression at run time. 726 PotentiallyEvaluated, 727 728 /// \brief The current expression is potentially evaluated, but any 729 /// declarations referenced inside that expression are only used if 730 /// in fact the current expression is used. 731 /// 732 /// This value is used when parsing default function arguments, for which 733 /// we would like to provide diagnostics (e.g., passing non-POD arguments 734 /// through varargs) but do not want to mark declarations as "referenced" 735 /// until the default argument is used. 736 PotentiallyEvaluatedIfUsed 737 }; 738 739 /// \brief Data structure used to record current or nested 740 /// expression evaluation contexts. 741 struct ExpressionEvaluationContextRecord { 742 /// \brief The expression evaluation context. 743 ExpressionEvaluationContext Context; 744 745 /// \brief Whether the enclosing context needed a cleanup. 746 bool ParentNeedsCleanups; 747 748 /// \brief Whether we are in a decltype expression. 749 bool IsDecltype; 750 751 /// \brief The number of active cleanup objects when we entered 752 /// this expression evaluation context. 753 unsigned NumCleanupObjects; 754 755 /// \brief The number of typos encountered during this expression evaluation 756 /// context (i.e. the number of TypoExprs created). 757 unsigned NumTypos; 758 759 llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs; 760 761 /// \brief The lambdas that are present within this context, if it 762 /// is indeed an unevaluated context. 763 SmallVector<LambdaExpr *, 2> Lambdas; 764 765 /// \brief The declaration that provides context for lambda expressions 766 /// and block literals if the normal declaration context does not 767 /// suffice, e.g., in a default function argument. 768 Decl *ManglingContextDecl; 769 770 /// \brief The context information used to mangle lambda expressions 771 /// and block literals within this context. 772 /// 773 /// This mangling information is allocated lazily, since most contexts 774 /// do not have lambda expressions or block literals. 775 IntrusiveRefCntPtr<MangleNumberingContext> MangleNumbering; 776 777 /// \brief If we are processing a decltype type, a set of call expressions 778 /// for which we have deferred checking the completeness of the return type. 779 SmallVector<CallExpr *, 8> DelayedDecltypeCalls; 780 781 /// \brief If we are processing a decltype type, a set of temporary binding 782 /// expressions for which we have deferred checking the destructor. 783 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; 784 ExpressionEvaluationContextRecordExpressionEvaluationContextRecord785 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, 786 unsigned NumCleanupObjects, 787 bool ParentNeedsCleanups, 788 Decl *ManglingContextDecl, 789 bool IsDecltype) 790 : Context(Context), ParentNeedsCleanups(ParentNeedsCleanups), 791 IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects), 792 NumTypos(0), 793 ManglingContextDecl(ManglingContextDecl), MangleNumbering() { } 794 795 /// \brief Retrieve the mangling numbering context, used to consistently 796 /// number constructs like lambdas for mangling. 797 MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx); 798 isUnevaluatedExpressionEvaluationContextRecord799 bool isUnevaluated() const { 800 return Context == Unevaluated || Context == UnevaluatedAbstract; 801 } 802 }; 803 804 /// A stack of expression evaluation contexts. 805 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; 806 807 /// \brief Compute the mangling number context for a lambda expression or 808 /// block literal. 809 /// 810 /// \param DC - The DeclContext containing the lambda expression or 811 /// block literal. 812 /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl 813 /// associated with the context, if relevant. 814 MangleNumberingContext *getCurrentMangleNumberContext( 815 const DeclContext *DC, 816 Decl *&ManglingContextDecl); 817 818 819 /// SpecialMemberOverloadResult - The overloading result for a special member 820 /// function. 821 /// 822 /// This is basically a wrapper around PointerIntPair. The lowest bits of the 823 /// integer are used to determine whether overload resolution succeeded. 824 class SpecialMemberOverloadResult : public llvm::FastFoldingSetNode { 825 public: 826 enum Kind { 827 NoMemberOrDeleted, 828 Ambiguous, 829 Success 830 }; 831 832 private: 833 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; 834 835 public: SpecialMemberOverloadResult(const llvm::FoldingSetNodeID & ID)836 SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID) 837 : FastFoldingSetNode(ID) 838 {} 839 getMethod()840 CXXMethodDecl *getMethod() const { return Pair.getPointer(); } setMethod(CXXMethodDecl * MD)841 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } 842 getKind()843 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } setKind(Kind K)844 void setKind(Kind K) { Pair.setInt(K); } 845 }; 846 847 /// \brief A cache of special member function overload resolution results 848 /// for C++ records. 849 llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache; 850 851 /// \brief The kind of translation unit we are processing. 852 /// 853 /// When we're processing a complete translation unit, Sema will perform 854 /// end-of-translation-unit semantic tasks (such as creating 855 /// initializers for tentative definitions in C) once parsing has 856 /// completed. Modules and precompiled headers perform different kinds of 857 /// checks. 858 TranslationUnitKind TUKind; 859 860 llvm::BumpPtrAllocator BumpAlloc; 861 862 /// \brief The number of SFINAE diagnostics that have been trapped. 863 unsigned NumSFINAEErrors; 864 865 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>> 866 UnparsedDefaultArgInstantiationsMap; 867 868 /// \brief A mapping from parameters with unparsed default arguments to the 869 /// set of instantiations of each parameter. 870 /// 871 /// This mapping is a temporary data structure used when parsing 872 /// nested class templates or nested classes of class templates, 873 /// where we might end up instantiating an inner class before the 874 /// default arguments of its methods have been parsed. 875 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; 876 877 // Contains the locations of the beginning of unparsed default 878 // argument locations. 879 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs; 880 881 /// UndefinedInternals - all the used, undefined objects which require a 882 /// definition in this translation unit. 883 llvm::DenseMap<NamedDecl *, SourceLocation> UndefinedButUsed; 884 885 /// Obtain a sorted list of functions that are undefined but ODR-used. 886 void getUndefinedButUsed( 887 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined); 888 889 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods; 890 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool; 891 892 /// Method Pool - allows efficient lookup when typechecking messages to "id". 893 /// We need to maintain a list, since selectors can have differing signatures 894 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% 895 /// of selectors are "overloaded"). 896 /// At the head of the list it is recorded whether there were 0, 1, or >= 2 897 /// methods inside categories with a particular selector. 898 GlobalMethodPool MethodPool; 899 900 /// Method selectors used in a \@selector expression. Used for implementation 901 /// of -Wselector. 902 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors; 903 904 /// Kinds of C++ special members. 905 enum CXXSpecialMember { 906 CXXDefaultConstructor, 907 CXXCopyConstructor, 908 CXXMoveConstructor, 909 CXXCopyAssignment, 910 CXXMoveAssignment, 911 CXXDestructor, 912 CXXInvalid 913 }; 914 915 typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl; 916 917 /// The C++ special members which we are currently in the process of 918 /// declaring. If this process recursively triggers the declaration of the 919 /// same special member, we should act as if it is not yet declared. 920 llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; 921 922 void ReadMethodPool(Selector Sel); 923 924 /// Private Helper predicate to check for 'self'. 925 bool isSelfExpr(Expr *RExpr); 926 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method); 927 928 /// \brief Cause the active diagnostic on the DiagosticsEngine to be 929 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and 930 /// should not be used elsewhere. 931 void EmitCurrentDiagnostic(unsigned DiagID); 932 933 /// Records and restores the FP_CONTRACT state on entry/exit of compound 934 /// statements. 935 class FPContractStateRAII { 936 public: FPContractStateRAII(Sema & S)937 FPContractStateRAII(Sema& S) 938 : S(S), OldFPContractState(S.FPFeatures.fp_contract) {} ~FPContractStateRAII()939 ~FPContractStateRAII() { 940 S.FPFeatures.fp_contract = OldFPContractState; 941 } 942 private: 943 Sema& S; 944 bool OldFPContractState : 1; 945 }; 946 947 void addImplicitTypedef(StringRef Name, QualType T); 948 949 public: 950 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 951 TranslationUnitKind TUKind = TU_Complete, 952 CodeCompleteConsumer *CompletionConsumer = nullptr); 953 ~Sema(); 954 955 /// \brief Perform initialization that occurs after the parser has been 956 /// initialized but before it parses anything. 957 void Initialize(); 958 getLangOpts()959 const LangOptions &getLangOpts() const { return LangOpts; } getOpenCLOptions()960 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } getFPOptions()961 FPOptions &getFPOptions() { return FPFeatures; } 962 getDiagnostics()963 DiagnosticsEngine &getDiagnostics() const { return Diags; } getSourceManager()964 SourceManager &getSourceManager() const { return SourceMgr; } getPreprocessor()965 Preprocessor &getPreprocessor() const { return PP; } getASTContext()966 ASTContext &getASTContext() const { return Context; } getASTConsumer()967 ASTConsumer &getASTConsumer() const { return Consumer; } 968 ASTMutationListener *getASTMutationListener() const; getExternalSource()969 ExternalSemaSource* getExternalSource() const { return ExternalSource; } 970 971 ///\brief Registers an external source. If an external source already exists, 972 /// creates a multiplex external source and appends to it. 973 /// 974 ///\param[in] E - A non-null external sema source. 975 /// 976 void addExternalSource(ExternalSemaSource *E); 977 978 void PrintStats() const; 979 980 /// \brief Helper class that creates diagnostics with optional 981 /// template instantiation stacks. 982 /// 983 /// This class provides a wrapper around the basic DiagnosticBuilder 984 /// class that emits diagnostics. SemaDiagnosticBuilder is 985 /// responsible for emitting the diagnostic (as DiagnosticBuilder 986 /// does) and, if the diagnostic comes from inside a template 987 /// instantiation, printing the template instantiation stack as 988 /// well. 989 class SemaDiagnosticBuilder : public DiagnosticBuilder { 990 Sema &SemaRef; 991 unsigned DiagID; 992 993 public: SemaDiagnosticBuilder(DiagnosticBuilder & DB,Sema & SemaRef,unsigned DiagID)994 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) 995 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { } 996 ~SemaDiagnosticBuilder()997 ~SemaDiagnosticBuilder() { 998 // If we aren't active, there is nothing to do. 999 if (!isActive()) return; 1000 1001 // Otherwise, we need to emit the diagnostic. First flush the underlying 1002 // DiagnosticBuilder data, and clear the diagnostic builder itself so it 1003 // won't emit the diagnostic in its own destructor. 1004 // 1005 // This seems wasteful, in that as written the DiagnosticBuilder dtor will 1006 // do its own needless checks to see if the diagnostic needs to be 1007 // emitted. However, because we take care to ensure that the builder 1008 // objects never escape, a sufficiently smart compiler will be able to 1009 // eliminate that code. 1010 FlushCounts(); 1011 Clear(); 1012 1013 // Dispatch to Sema to emit the diagnostic. 1014 SemaRef.EmitCurrentDiagnostic(DiagID); 1015 } 1016 1017 /// Teach operator<< to produce an object of the correct type. 1018 template<typename T> 1019 friend const SemaDiagnosticBuilder &operator<<( 1020 const SemaDiagnosticBuilder &Diag, const T &Value) { 1021 const DiagnosticBuilder &BaseDiag = Diag; 1022 BaseDiag << Value; 1023 return Diag; 1024 } 1025 }; 1026 1027 /// \brief Emit a diagnostic. Diag(SourceLocation Loc,unsigned DiagID)1028 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { 1029 DiagnosticBuilder DB = Diags.Report(Loc, DiagID); 1030 return SemaDiagnosticBuilder(DB, *this, DiagID); 1031 } 1032 1033 /// \brief Emit a partial diagnostic. 1034 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD); 1035 1036 /// \brief Build a partial diagnostic. 1037 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h 1038 1039 bool findMacroSpelling(SourceLocation &loc, StringRef name); 1040 1041 /// \brief Get a string to suggest for zero-initialization of a type. 1042 std::string 1043 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const; 1044 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const; 1045 1046 /// \brief Calls \c Lexer::getLocForEndOfToken() 1047 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); 1048 1049 /// \brief Retrieve the module loader associated with the preprocessor. 1050 ModuleLoader &getModuleLoader() const; 1051 1052 void emitAndClearUnusedLocalTypedefWarnings(); 1053 1054 void ActOnEndOfTranslationUnit(); 1055 1056 void CheckDelegatingCtorCycles(); 1057 1058 Scope *getScopeForContext(DeclContext *Ctx); 1059 1060 void PushFunctionScope(); 1061 void PushBlockScope(Scope *BlockScope, BlockDecl *Block); 1062 sema::LambdaScopeInfo *PushLambdaScope(); 1063 1064 /// \brief This is used to inform Sema what the current TemplateParameterDepth 1065 /// is during Parsing. Currently it is used to pass on the depth 1066 /// when parsing generic lambda 'auto' parameters. 1067 void RecordParsingTemplateParameterDepth(unsigned Depth); 1068 1069 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, 1070 RecordDecl *RD, 1071 CapturedRegionKind K); 1072 void 1073 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, 1074 const Decl *D = nullptr, 1075 const BlockExpr *blkExpr = nullptr); 1076 getCurFunction()1077 sema::FunctionScopeInfo *getCurFunction() const { 1078 return FunctionScopes.back(); 1079 } 1080 getEnclosingFunction()1081 sema::FunctionScopeInfo *getEnclosingFunction() const { 1082 if (FunctionScopes.empty()) 1083 return nullptr; 1084 1085 for (int e = FunctionScopes.size()-1; e >= 0; --e) { 1086 if (isa<sema::BlockScopeInfo>(FunctionScopes[e])) 1087 continue; 1088 return FunctionScopes[e]; 1089 } 1090 return nullptr; 1091 } 1092 1093 template <typename ExprT> 1094 void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) { 1095 if (!isUnevaluatedContext()) 1096 getCurFunction()->recordUseOfWeak(E, IsRead); 1097 } 1098 1099 void PushCompoundScope(); 1100 void PopCompoundScope(); 1101 1102 sema::CompoundScopeInfo &getCurCompoundScope() const; 1103 1104 bool hasAnyUnrecoverableErrorsInThisFunction() const; 1105 1106 /// \brief Retrieve the current block, if any. 1107 sema::BlockScopeInfo *getCurBlock(); 1108 1109 /// \brief Retrieve the current lambda scope info, if any. 1110 sema::LambdaScopeInfo *getCurLambda(); 1111 1112 /// \brief Retrieve the current generic lambda info, if any. 1113 sema::LambdaScopeInfo *getCurGenericLambda(); 1114 1115 /// \brief Retrieve the current captured region, if any. 1116 sema::CapturedRegionScopeInfo *getCurCapturedRegion(); 1117 1118 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls WeakTopLevelDecls()1119 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } 1120 1121 void ActOnComment(SourceRange Comment); 1122 1123 //===--------------------------------------------------------------------===// 1124 // Type Analysis / Processing: SemaType.cpp. 1125 // 1126 1127 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, 1128 const DeclSpec *DS = nullptr); 1129 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, 1130 const DeclSpec *DS = nullptr); 1131 QualType BuildPointerType(QualType T, 1132 SourceLocation Loc, DeclarationName Entity); 1133 QualType BuildReferenceType(QualType T, bool LValueRef, 1134 SourceLocation Loc, DeclarationName Entity); 1135 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, 1136 Expr *ArraySize, unsigned Quals, 1137 SourceRange Brackets, DeclarationName Entity); 1138 QualType BuildExtVectorType(QualType T, Expr *ArraySize, 1139 SourceLocation AttrLoc); 1140 1141 bool CheckFunctionReturnType(QualType T, SourceLocation Loc); 1142 1143 /// \brief Build a function type. 1144 /// 1145 /// This routine checks the function type according to C++ rules and 1146 /// under the assumption that the result type and parameter types have 1147 /// just been instantiated from a template. It therefore duplicates 1148 /// some of the behavior of GetTypeForDeclarator, but in a much 1149 /// simpler form that is only suitable for this narrow use case. 1150 /// 1151 /// \param T The return type of the function. 1152 /// 1153 /// \param ParamTypes The parameter types of the function. This array 1154 /// will be modified to account for adjustments to the types of the 1155 /// function parameters. 1156 /// 1157 /// \param Loc The location of the entity whose type involves this 1158 /// function type or, if there is no such entity, the location of the 1159 /// type that will have function type. 1160 /// 1161 /// \param Entity The name of the entity that involves the function 1162 /// type, if known. 1163 /// 1164 /// \param EPI Extra information about the function type. Usually this will 1165 /// be taken from an existing function with the same prototype. 1166 /// 1167 /// \returns A suitable function type, if there are no errors. The 1168 /// unqualified type will always be a FunctionProtoType. 1169 /// Otherwise, returns a NULL type. 1170 QualType BuildFunctionType(QualType T, 1171 MutableArrayRef<QualType> ParamTypes, 1172 SourceLocation Loc, DeclarationName Entity, 1173 const FunctionProtoType::ExtProtoInfo &EPI); 1174 1175 QualType BuildMemberPointerType(QualType T, QualType Class, 1176 SourceLocation Loc, 1177 DeclarationName Entity); 1178 QualType BuildBlockPointerType(QualType T, 1179 SourceLocation Loc, DeclarationName Entity); 1180 QualType BuildParenType(QualType T); 1181 QualType BuildAtomicType(QualType T, SourceLocation Loc); 1182 1183 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); 1184 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); 1185 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, 1186 TypeSourceInfo *ReturnTypeInfo); 1187 1188 /// \brief Package the given type and TSI into a ParsedType. 1189 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); 1190 DeclarationNameInfo GetNameForDeclarator(Declarator &D); 1191 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); 1192 static QualType GetTypeFromParser(ParsedType Ty, 1193 TypeSourceInfo **TInfo = nullptr); 1194 CanThrowResult canThrow(const Expr *E); 1195 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, 1196 const FunctionProtoType *FPT); 1197 void UpdateExceptionSpec(FunctionDecl *FD, 1198 const FunctionProtoType::ExceptionSpecInfo &ESI); 1199 bool CheckSpecifiedExceptionType(QualType &T, const SourceRange &Range); 1200 bool CheckDistantExceptionSpec(QualType T); 1201 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); 1202 bool CheckEquivalentExceptionSpec( 1203 const FunctionProtoType *Old, SourceLocation OldLoc, 1204 const FunctionProtoType *New, SourceLocation NewLoc); 1205 bool CheckEquivalentExceptionSpec( 1206 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, 1207 const FunctionProtoType *Old, SourceLocation OldLoc, 1208 const FunctionProtoType *New, SourceLocation NewLoc, 1209 bool *MissingExceptionSpecification = nullptr, 1210 bool *MissingEmptyExceptionSpecification = nullptr, 1211 bool AllowNoexceptAllMatchWithNoSpec = false, 1212 bool IsOperatorNew = false); 1213 bool CheckExceptionSpecSubset( 1214 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, 1215 const FunctionProtoType *Superset, SourceLocation SuperLoc, 1216 const FunctionProtoType *Subset, SourceLocation SubLoc); 1217 bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID, 1218 const FunctionProtoType *Target, SourceLocation TargetLoc, 1219 const FunctionProtoType *Source, SourceLocation SourceLoc); 1220 1221 TypeResult ActOnTypeName(Scope *S, Declarator &D); 1222 1223 /// \brief The parser has parsed the context-sensitive type 'instancetype' 1224 /// in an Objective-C message declaration. Return the appropriate type. 1225 ParsedType ActOnObjCInstanceType(SourceLocation Loc); 1226 1227 /// \brief Abstract class used to diagnose incomplete types. 1228 struct TypeDiagnoser { 1229 bool Suppressed; 1230 SuppressedTypeDiagnoser1231 TypeDiagnoser(bool Suppressed = false) : Suppressed(Suppressed) { } 1232 1233 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0; ~TypeDiagnoserTypeDiagnoser1234 virtual ~TypeDiagnoser() {} 1235 }; 1236 getPrintable(int I)1237 static int getPrintable(int I) { return I; } getPrintable(unsigned I)1238 static unsigned getPrintable(unsigned I) { return I; } getPrintable(bool B)1239 static bool getPrintable(bool B) { return B; } getPrintable(const char * S)1240 static const char * getPrintable(const char *S) { return S; } getPrintable(StringRef S)1241 static StringRef getPrintable(StringRef S) { return S; } getPrintable(const std::string & S)1242 static const std::string &getPrintable(const std::string &S) { return S; } getPrintable(const IdentifierInfo * II)1243 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) { 1244 return II; 1245 } getPrintable(DeclarationName N)1246 static DeclarationName getPrintable(DeclarationName N) { return N; } getPrintable(QualType T)1247 static QualType getPrintable(QualType T) { return T; } getPrintable(SourceRange R)1248 static SourceRange getPrintable(SourceRange R) { return R; } getPrintable(SourceLocation L)1249 static SourceRange getPrintable(SourceLocation L) { return L; } getPrintable(const Expr * E)1250 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); } getPrintable(TypeLoc TL)1251 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();} 1252 1253 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser { 1254 unsigned DiagID; 1255 std::tuple<const Ts &...> Args; 1256 1257 template <std::size_t... Is> emit(const SemaDiagnosticBuilder & DB,llvm::index_sequence<Is...>)1258 void emit(const SemaDiagnosticBuilder &DB, 1259 llvm::index_sequence<Is...>) const { 1260 // Apply all tuple elements to the builder in order. 1261 bool Dummy[] = {(DB << getPrintable(std::get<Is>(Args)))...}; 1262 (void)Dummy; 1263 } 1264 1265 public: BoundTypeDiagnoser(unsigned DiagID,const Ts &...Args)1266 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args) 1267 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Args(Args...) {} 1268 diagnose(Sema & S,SourceLocation Loc,QualType T)1269 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 1270 if (Suppressed) 1271 return; 1272 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID); 1273 emit(DB, llvm::index_sequence_for<Ts...>()); 1274 DB << T; 1275 } 1276 }; 1277 1278 private: 1279 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, 1280 TypeDiagnoser &Diagnoser); 1281 public: 1282 /// Determine if \p D has a visible definition. If not, suggest a declaration 1283 /// that should be made visible to expose the definition. 1284 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested); hasVisibleDefinition(const NamedDecl * D)1285 bool hasVisibleDefinition(const NamedDecl *D) { 1286 NamedDecl *Hidden; 1287 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden); 1288 } 1289 1290 bool RequireCompleteType(SourceLocation Loc, QualType T, 1291 TypeDiagnoser &Diagnoser); 1292 bool RequireCompleteType(SourceLocation Loc, QualType T, 1293 unsigned DiagID); 1294 1295 template <typename... Ts> RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)1296 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, 1297 const Ts &...Args) { 1298 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 1299 return RequireCompleteType(Loc, T, Diagnoser); 1300 } 1301 1302 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser); 1303 bool RequireCompleteExprType(Expr *E, unsigned DiagID); 1304 1305 template <typename... Ts> RequireCompleteExprType(Expr * E,unsigned DiagID,const Ts &...Args)1306 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) { 1307 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 1308 return RequireCompleteExprType(E, Diagnoser); 1309 } 1310 1311 bool RequireLiteralType(SourceLocation Loc, QualType T, 1312 TypeDiagnoser &Diagnoser); 1313 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); 1314 1315 template <typename... Ts> RequireLiteralType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)1316 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, 1317 const Ts &...Args) { 1318 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 1319 return RequireLiteralType(Loc, T, Diagnoser); 1320 } 1321 1322 QualType getElaboratedType(ElaboratedTypeKeyword Keyword, 1323 const CXXScopeSpec &SS, QualType T); 1324 1325 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc); 1326 /// If AsUnevaluated is false, E is treated as though it were an evaluated 1327 /// context, such as when building a type for decltype(auto). 1328 QualType BuildDecltypeType(Expr *E, SourceLocation Loc, 1329 bool AsUnevaluated = true); 1330 QualType BuildUnaryTransformType(QualType BaseType, 1331 UnaryTransformType::UTTKind UKind, 1332 SourceLocation Loc); 1333 1334 //===--------------------------------------------------------------------===// 1335 // Symbol table / Decl tracking callbacks: SemaDecl.cpp. 1336 // 1337 1338 /// List of decls defined in a function prototype. This contains EnumConstants 1339 /// that incorrectly end up in translation unit scope because there is no 1340 /// function to pin them on. ActOnFunctionDeclarator reads this list and patches 1341 /// them into the FunctionDecl. 1342 std::vector<NamedDecl*> DeclsInPrototypeScope; 1343 1344 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); 1345 1346 void DiagnoseUseOfUnimplementedSelectors(); 1347 1348 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const; 1349 1350 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 1351 Scope *S, CXXScopeSpec *SS = nullptr, 1352 bool isClassName = false, 1353 bool HasTrailingDot = false, 1354 ParsedType ObjectType = ParsedType(), 1355 bool IsCtorOrDtorName = false, 1356 bool WantNontrivialTypeSourceInfo = false, 1357 IdentifierInfo **CorrectedII = nullptr); 1358 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); 1359 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); 1360 void DiagnoseUnknownTypeName(IdentifierInfo *&II, 1361 SourceLocation IILoc, 1362 Scope *S, 1363 CXXScopeSpec *SS, 1364 ParsedType &SuggestedType, 1365 bool AllowClassTemplates = false); 1366 1367 /// \brief For compatibility with MSVC, we delay parsing of some default 1368 /// template type arguments until instantiation time. Emits a warning and 1369 /// returns a synthesized DependentNameType that isn't really dependent on any 1370 /// other template arguments. 1371 ParsedType ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II, 1372 SourceLocation NameLoc); 1373 1374 /// \brief Describes the result of the name lookup and resolution performed 1375 /// by \c ClassifyName(). 1376 enum NameClassificationKind { 1377 NC_Unknown, 1378 NC_Error, 1379 NC_Keyword, 1380 NC_Type, 1381 NC_Expression, 1382 NC_NestedNameSpecifier, 1383 NC_TypeTemplate, 1384 NC_VarTemplate, 1385 NC_FunctionTemplate 1386 }; 1387 1388 class NameClassification { 1389 NameClassificationKind Kind; 1390 ExprResult Expr; 1391 TemplateName Template; 1392 ParsedType Type; 1393 const IdentifierInfo *Keyword; 1394 NameClassification(NameClassificationKind Kind)1395 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} 1396 1397 public: NameClassification(ExprResult Expr)1398 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {} 1399 NameClassification(ParsedType Type)1400 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} 1401 NameClassification(const IdentifierInfo * Keyword)1402 NameClassification(const IdentifierInfo *Keyword) 1403 : Kind(NC_Keyword), Keyword(Keyword) { } 1404 Error()1405 static NameClassification Error() { 1406 return NameClassification(NC_Error); 1407 } 1408 Unknown()1409 static NameClassification Unknown() { 1410 return NameClassification(NC_Unknown); 1411 } 1412 NestedNameSpecifier()1413 static NameClassification NestedNameSpecifier() { 1414 return NameClassification(NC_NestedNameSpecifier); 1415 } 1416 TypeTemplate(TemplateName Name)1417 static NameClassification TypeTemplate(TemplateName Name) { 1418 NameClassification Result(NC_TypeTemplate); 1419 Result.Template = Name; 1420 return Result; 1421 } 1422 VarTemplate(TemplateName Name)1423 static NameClassification VarTemplate(TemplateName Name) { 1424 NameClassification Result(NC_VarTemplate); 1425 Result.Template = Name; 1426 return Result; 1427 } 1428 FunctionTemplate(TemplateName Name)1429 static NameClassification FunctionTemplate(TemplateName Name) { 1430 NameClassification Result(NC_FunctionTemplate); 1431 Result.Template = Name; 1432 return Result; 1433 } 1434 getKind()1435 NameClassificationKind getKind() const { return Kind; } 1436 getType()1437 ParsedType getType() const { 1438 assert(Kind == NC_Type); 1439 return Type; 1440 } 1441 getExpression()1442 ExprResult getExpression() const { 1443 assert(Kind == NC_Expression); 1444 return Expr; 1445 } 1446 getTemplateName()1447 TemplateName getTemplateName() const { 1448 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || 1449 Kind == NC_VarTemplate); 1450 return Template; 1451 } 1452 getTemplateNameKind()1453 TemplateNameKind getTemplateNameKind() const { 1454 switch (Kind) { 1455 case NC_TypeTemplate: 1456 return TNK_Type_template; 1457 case NC_FunctionTemplate: 1458 return TNK_Function_template; 1459 case NC_VarTemplate: 1460 return TNK_Var_template; 1461 default: 1462 llvm_unreachable("unsupported name classification."); 1463 } 1464 } 1465 }; 1466 1467 /// \brief Perform name lookup on the given name, classifying it based on 1468 /// the results of name lookup and the following token. 1469 /// 1470 /// This routine is used by the parser to resolve identifiers and help direct 1471 /// parsing. When the identifier cannot be found, this routine will attempt 1472 /// to correct the typo and classify based on the resulting name. 1473 /// 1474 /// \param S The scope in which we're performing name lookup. 1475 /// 1476 /// \param SS The nested-name-specifier that precedes the name. 1477 /// 1478 /// \param Name The identifier. If typo correction finds an alternative name, 1479 /// this pointer parameter will be updated accordingly. 1480 /// 1481 /// \param NameLoc The location of the identifier. 1482 /// 1483 /// \param NextToken The token following the identifier. Used to help 1484 /// disambiguate the name. 1485 /// 1486 /// \param IsAddressOfOperand True if this name is the operand of a unary 1487 /// address of ('&') expression, assuming it is classified as an 1488 /// expression. 1489 /// 1490 /// \param CCC The correction callback, if typo correction is desired. 1491 NameClassification 1492 ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 1493 SourceLocation NameLoc, const Token &NextToken, 1494 bool IsAddressOfOperand, 1495 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr); 1496 1497 Decl *ActOnDeclarator(Scope *S, Declarator &D); 1498 1499 NamedDecl *HandleDeclarator(Scope *S, Declarator &D, 1500 MultiTemplateParamsArg TemplateParameterLists); 1501 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S); 1502 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); 1503 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 1504 DeclarationName Name, 1505 SourceLocation Loc); 1506 void 1507 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, 1508 SourceLocation FallbackLoc, 1509 SourceLocation ConstQualLoc = SourceLocation(), 1510 SourceLocation VolatileQualLoc = SourceLocation(), 1511 SourceLocation RestrictQualLoc = SourceLocation(), 1512 SourceLocation AtomicQualLoc = SourceLocation()); 1513 1514 static bool adjustContextForLocalExternDecl(DeclContext *&DC); 1515 void DiagnoseFunctionSpecifiers(const DeclSpec &DS); 1516 void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R); 1517 void CheckShadow(Scope *S, VarDecl *D); 1518 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); 1519 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope); 1520 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 1521 TypedefNameDecl *NewTD); 1522 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); 1523 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 1524 TypeSourceInfo *TInfo, 1525 LookupResult &Previous); 1526 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, 1527 LookupResult &Previous, bool &Redeclaration); 1528 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 1529 TypeSourceInfo *TInfo, 1530 LookupResult &Previous, 1531 MultiTemplateParamsArg TemplateParamLists, 1532 bool &AddToScope); 1533 // Returns true if the variable declaration is a redeclaration 1534 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); 1535 void CheckVariableDeclarationType(VarDecl *NewVD); 1536 void CheckCompleteVariableDeclaration(VarDecl *var); 1537 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); 1538 1539 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, 1540 TypeSourceInfo *TInfo, 1541 LookupResult &Previous, 1542 MultiTemplateParamsArg TemplateParamLists, 1543 bool &AddToScope); 1544 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); 1545 1546 bool CheckConstexprFunctionDecl(const FunctionDecl *FD); 1547 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body); 1548 1549 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); 1550 void FindHiddenVirtualMethods(CXXMethodDecl *MD, 1551 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); 1552 void NoteHiddenVirtualMethods(CXXMethodDecl *MD, 1553 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); 1554 // Returns true if the function declaration is a redeclaration 1555 bool CheckFunctionDeclaration(Scope *S, 1556 FunctionDecl *NewFD, LookupResult &Previous, 1557 bool IsExplicitSpecialization); 1558 void CheckMain(FunctionDecl *FD, const DeclSpec &D); 1559 void CheckMSVCRTEntryPoint(FunctionDecl *FD); 1560 Decl *ActOnParamDeclarator(Scope *S, Declarator &D); 1561 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, 1562 SourceLocation Loc, 1563 QualType T); 1564 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, 1565 SourceLocation NameLoc, IdentifierInfo *Name, 1566 QualType T, TypeSourceInfo *TSInfo, 1567 StorageClass SC); 1568 void ActOnParamDefaultArgument(Decl *param, 1569 SourceLocation EqualLoc, 1570 Expr *defarg); 1571 void ActOnParamUnparsedDefaultArgument(Decl *param, 1572 SourceLocation EqualLoc, 1573 SourceLocation ArgLoc); 1574 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc); 1575 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, 1576 SourceLocation EqualLoc); 1577 1578 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit, 1579 bool TypeMayContainAuto); 1580 void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto); 1581 void ActOnInitializerError(Decl *Dcl); 1582 void ActOnCXXForRangeDecl(Decl *D); 1583 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 1584 IdentifierInfo *Ident, 1585 ParsedAttributes &Attrs, 1586 SourceLocation AttrEnd); 1587 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); 1588 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); 1589 void FinalizeDeclaration(Decl *D); 1590 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 1591 ArrayRef<Decl *> Group); 1592 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group, 1593 bool TypeMayContainAuto = true); 1594 1595 /// Should be called on all declarations that might have attached 1596 /// documentation comments. 1597 void ActOnDocumentableDecl(Decl *D); 1598 void ActOnDocumentableDecls(ArrayRef<Decl *> Group); 1599 1600 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 1601 SourceLocation LocAfterDecls); 1602 void CheckForFunctionRedefinition(FunctionDecl *FD, 1603 const FunctionDecl *EffectiveDefinition = 1604 nullptr); 1605 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D); 1606 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D); 1607 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); isObjCMethodDecl(Decl * D)1608 bool isObjCMethodDecl(Decl *D) { 1609 return D && isa<ObjCMethodDecl>(D); 1610 } 1611 1612 /// \brief Determine whether we can delay parsing the body of a function or 1613 /// function template until it is used, assuming we don't care about emitting 1614 /// code for that function. 1615 /// 1616 /// This will be \c false if we may need the body of the function in the 1617 /// middle of parsing an expression (where it's impractical to switch to 1618 /// parsing a different function), for instance, if it's constexpr in C++11 1619 /// or has an 'auto' return type in C++14. These cases are essentially bugs. 1620 bool canDelayFunctionBody(const Declarator &D); 1621 1622 /// \brief Determine whether we can skip parsing the body of a function 1623 /// definition, assuming we don't care about analyzing its body or emitting 1624 /// code for that function. 1625 /// 1626 /// This will be \c false only if we may need the body of the function in 1627 /// order to parse the rest of the program (for instance, if it is 1628 /// \c constexpr in C++11 or has an 'auto' return type in C++14). 1629 bool canSkipFunctionBody(Decl *D); 1630 1631 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); 1632 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); 1633 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); 1634 Decl *ActOnSkippedFunctionBody(Decl *Decl); 1635 void ActOnFinishInlineMethodDef(CXXMethodDecl *D); 1636 1637 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an 1638 /// attribute for which parsing is delayed. 1639 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); 1640 1641 /// \brief Diagnose any unused parameters in the given sequence of 1642 /// ParmVarDecl pointers. 1643 void DiagnoseUnusedParameters(ParmVarDecl * const *Begin, 1644 ParmVarDecl * const *End); 1645 1646 /// \brief Diagnose whether the size of parameters or return value of a 1647 /// function or obj-c method definition is pass-by-value and larger than a 1648 /// specified threshold. 1649 void DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Begin, 1650 ParmVarDecl * const *End, 1651 QualType ReturnTy, 1652 NamedDecl *D); 1653 1654 void DiagnoseInvalidJumps(Stmt *Body); 1655 Decl *ActOnFileScopeAsmDecl(Expr *expr, 1656 SourceLocation AsmLoc, 1657 SourceLocation RParenLoc); 1658 1659 /// \brief Handle a C++11 empty-declaration and attribute-declaration. 1660 Decl *ActOnEmptyDeclaration(Scope *S, 1661 AttributeList *AttrList, 1662 SourceLocation SemiLoc); 1663 1664 /// \brief The parser has processed a module import declaration. 1665 /// 1666 /// \param AtLoc The location of the '@' symbol, if any. 1667 /// 1668 /// \param ImportLoc The location of the 'import' keyword. 1669 /// 1670 /// \param Path The module access path. 1671 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc, 1672 ModuleIdPath Path); 1673 1674 /// \brief The parser has processed a module import translated from a 1675 /// #include or similar preprocessing directive. 1676 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod); 1677 1678 /// \brief Create an implicit import of the given module at the given 1679 /// source location, for error recovery, if possible. 1680 /// 1681 /// This routine is typically used when an entity found by name lookup 1682 /// is actually hidden within a module that we know about but the user 1683 /// has forgotten to import. 1684 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 1685 Module *Mod); 1686 1687 /// \brief Retrieve a suitable printing policy. getPrintingPolicy()1688 PrintingPolicy getPrintingPolicy() const { 1689 return getPrintingPolicy(Context, PP); 1690 } 1691 1692 /// \brief Retrieve a suitable printing policy. 1693 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, 1694 const Preprocessor &PP); 1695 1696 /// Scope actions. 1697 void ActOnPopScope(SourceLocation Loc, Scope *S); 1698 void ActOnTranslationUnitScope(Scope *S); 1699 1700 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 1701 DeclSpec &DS); 1702 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 1703 DeclSpec &DS, 1704 MultiTemplateParamsArg TemplateParams, 1705 bool IsExplicitInstantiation = false); 1706 1707 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 1708 AccessSpecifier AS, 1709 RecordDecl *Record, 1710 const PrintingPolicy &Policy); 1711 1712 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 1713 RecordDecl *Record); 1714 1715 bool isAcceptableTagRedeclaration(const TagDecl *Previous, 1716 TagTypeKind NewTag, bool isDefinition, 1717 SourceLocation NewTagLoc, 1718 const IdentifierInfo &Name); 1719 1720 enum TagUseKind { 1721 TUK_Reference, // Reference to a tag: 'struct foo *X;' 1722 TUK_Declaration, // Fwd decl of a tag: 'struct foo;' 1723 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' 1724 TUK_Friend // Friend declaration: 'friend struct foo;' 1725 }; 1726 1727 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 1728 SourceLocation KWLoc, CXXScopeSpec &SS, 1729 IdentifierInfo *Name, SourceLocation NameLoc, 1730 AttributeList *Attr, AccessSpecifier AS, 1731 SourceLocation ModulePrivateLoc, 1732 MultiTemplateParamsArg TemplateParameterLists, 1733 bool &OwnedDecl, bool &IsDependent, 1734 SourceLocation ScopedEnumKWLoc, 1735 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 1736 bool IsTypeSpecifier, bool *SkipBody = nullptr); 1737 1738 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 1739 unsigned TagSpec, SourceLocation TagLoc, 1740 CXXScopeSpec &SS, 1741 IdentifierInfo *Name, SourceLocation NameLoc, 1742 AttributeList *Attr, 1743 MultiTemplateParamsArg TempParamLists); 1744 1745 TypeResult ActOnDependentTag(Scope *S, 1746 unsigned TagSpec, 1747 TagUseKind TUK, 1748 const CXXScopeSpec &SS, 1749 IdentifierInfo *Name, 1750 SourceLocation TagLoc, 1751 SourceLocation NameLoc); 1752 1753 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, 1754 IdentifierInfo *ClassName, 1755 SmallVectorImpl<Decl *> &Decls); 1756 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 1757 Declarator &D, Expr *BitfieldWidth); 1758 1759 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, 1760 Declarator &D, Expr *BitfieldWidth, 1761 InClassInitStyle InitStyle, 1762 AccessSpecifier AS); 1763 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, 1764 SourceLocation DeclStart, 1765 Declarator &D, Expr *BitfieldWidth, 1766 InClassInitStyle InitStyle, 1767 AccessSpecifier AS, 1768 AttributeList *MSPropertyAttr); 1769 1770 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, 1771 TypeSourceInfo *TInfo, 1772 RecordDecl *Record, SourceLocation Loc, 1773 bool Mutable, Expr *BitfieldWidth, 1774 InClassInitStyle InitStyle, 1775 SourceLocation TSSL, 1776 AccessSpecifier AS, NamedDecl *PrevDecl, 1777 Declarator *D = nullptr); 1778 1779 bool CheckNontrivialField(FieldDecl *FD); 1780 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM); 1781 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 1782 bool Diagnose = false); 1783 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD); 1784 void ActOnLastBitfield(SourceLocation DeclStart, 1785 SmallVectorImpl<Decl *> &AllIvarDecls); 1786 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, 1787 Declarator &D, Expr *BitfieldWidth, 1788 tok::ObjCKeywordKind visibility); 1789 1790 // This is used for both record definitions and ObjC interface declarations. 1791 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl, 1792 ArrayRef<Decl *> Fields, 1793 SourceLocation LBrac, SourceLocation RBrac, 1794 AttributeList *AttrList); 1795 1796 /// ActOnTagStartDefinition - Invoked when we have entered the 1797 /// scope of a tag's definition (e.g., for an enumeration, class, 1798 /// struct, or union). 1799 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); 1800 1801 /// \brief Invoked when we enter a tag definition that we're skipping. ActOnTagStartSkippedDefinition(Scope * S,Decl * TD)1802 void ActOnTagStartSkippedDefinition(Scope *S, Decl *TD) { 1803 PushDeclContext(S, cast<DeclContext>(TD)); 1804 } 1805 1806 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl); 1807 1808 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a 1809 /// C++ record definition's base-specifiers clause and are starting its 1810 /// member declarations. 1811 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, 1812 SourceLocation FinalLoc, 1813 bool IsFinalSpelledSealed, 1814 SourceLocation LBraceLoc); 1815 1816 /// ActOnTagFinishDefinition - Invoked once we have finished parsing 1817 /// the definition of a tag (enumeration, class, struct, or union). 1818 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, 1819 SourceLocation RBraceLoc); 1820 ActOnTagFinishSkippedDefinition()1821 void ActOnTagFinishSkippedDefinition() { 1822 PopDeclContext(); 1823 } 1824 1825 void ActOnObjCContainerFinishDefinition(); 1826 1827 /// \brief Invoked when we must temporarily exit the objective-c container 1828 /// scope for parsing/looking-up C constructs. 1829 /// 1830 /// Must be followed by a call to \see ActOnObjCReenterContainerContext 1831 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC); 1832 void ActOnObjCReenterContainerContext(DeclContext *DC); 1833 1834 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable 1835 /// error parsing the definition of a tag. 1836 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); 1837 1838 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, 1839 EnumConstantDecl *LastEnumConst, 1840 SourceLocation IdLoc, 1841 IdentifierInfo *Id, 1842 Expr *val); 1843 bool CheckEnumUnderlyingType(TypeSourceInfo *TI); 1844 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 1845 QualType EnumUnderlyingTy, const EnumDecl *Prev); 1846 1847 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, 1848 SourceLocation IdLoc, IdentifierInfo *Id, 1849 AttributeList *Attrs, 1850 SourceLocation EqualLoc, Expr *Val); 1851 void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 1852 SourceLocation RBraceLoc, Decl *EnumDecl, 1853 ArrayRef<Decl *> Elements, 1854 Scope *S, AttributeList *Attr); 1855 1856 DeclContext *getContainingDC(DeclContext *DC); 1857 1858 /// Set the current declaration context until it gets popped. 1859 void PushDeclContext(Scope *S, DeclContext *DC); 1860 void PopDeclContext(); 1861 1862 /// EnterDeclaratorContext - Used when we must lookup names in the context 1863 /// of a declarator's nested name specifier. 1864 void EnterDeclaratorContext(Scope *S, DeclContext *DC); 1865 void ExitDeclaratorContext(Scope *S); 1866 1867 /// Push the parameters of D, which must be a function, into scope. 1868 void ActOnReenterFunctionContext(Scope* S, Decl* D); 1869 void ActOnExitFunctionContext(); 1870 1871 DeclContext *getFunctionLevelDeclContext(); 1872 1873 /// getCurFunctionDecl - If inside of a function body, this returns a pointer 1874 /// to the function decl for the function being parsed. If we're currently 1875 /// in a 'block', this returns the containing context. 1876 FunctionDecl *getCurFunctionDecl(); 1877 1878 /// getCurMethodDecl - If inside of a method body, this returns a pointer to 1879 /// the method decl for the method being parsed. If we're currently 1880 /// in a 'block', this returns the containing context. 1881 ObjCMethodDecl *getCurMethodDecl(); 1882 1883 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method 1884 /// or C function we're in, otherwise return null. If we're currently 1885 /// in a 'block', this returns the containing context. 1886 NamedDecl *getCurFunctionOrMethodDecl(); 1887 1888 /// Add this decl to the scope shadowed decl chains. 1889 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); 1890 1891 /// \brief Make the given externally-produced declaration visible at the 1892 /// top level scope. 1893 /// 1894 /// \param D The externally-produced declaration to push. 1895 /// 1896 /// \param Name The name of the externally-produced declaration. 1897 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name); 1898 1899 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true 1900 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns 1901 /// true if 'D' belongs to the given declaration context. 1902 /// 1903 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the 1904 /// enclosing namespace set of the context, rather than contained 1905 /// directly within it. 1906 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr, 1907 bool AllowInlineNamespace = false); 1908 1909 /// Finds the scope corresponding to the given decl context, if it 1910 /// happens to be an enclosing scope. Otherwise return NULL. 1911 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); 1912 1913 /// Subroutines of ActOnDeclarator(). 1914 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 1915 TypeSourceInfo *TInfo); 1916 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New); 1917 1918 /// Attribute merging methods. Return true if a new attribute was added. 1919 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range, 1920 IdentifierInfo *Platform, 1921 VersionTuple Introduced, 1922 VersionTuple Deprecated, 1923 VersionTuple Obsoleted, 1924 bool IsUnavailable, 1925 StringRef Message, 1926 bool Override, 1927 unsigned AttrSpellingListIndex); 1928 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range, 1929 TypeVisibilityAttr::VisibilityType Vis, 1930 unsigned AttrSpellingListIndex); 1931 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range, 1932 VisibilityAttr::VisibilityType Vis, 1933 unsigned AttrSpellingListIndex); 1934 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range, 1935 unsigned AttrSpellingListIndex); 1936 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range, 1937 unsigned AttrSpellingListIndex); 1938 MSInheritanceAttr * 1939 mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase, 1940 unsigned AttrSpellingListIndex, 1941 MSInheritanceAttr::Spelling SemanticSpelling); 1942 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range, 1943 IdentifierInfo *Format, int FormatIdx, 1944 int FirstArg, unsigned AttrSpellingListIndex); 1945 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name, 1946 unsigned AttrSpellingListIndex); 1947 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range, 1948 IdentifierInfo *Ident, 1949 unsigned AttrSpellingListIndex); 1950 MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range, 1951 unsigned AttrSpellingListIndex); 1952 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range, 1953 unsigned AttrSpellingListIndex); 1954 1955 /// \brief Describes the kind of merge to perform for availability 1956 /// attributes (including "deprecated", "unavailable", and "availability"). 1957 enum AvailabilityMergeKind { 1958 /// \brief Don't merge availability attributes at all. 1959 AMK_None, 1960 /// \brief Merge availability attributes for a redeclaration, which requires 1961 /// an exact match. 1962 AMK_Redeclaration, 1963 /// \brief Merge availability attributes for an override, which requires 1964 /// an exact match or a weakening of constraints. 1965 AMK_Override 1966 }; 1967 1968 void mergeDeclAttributes(NamedDecl *New, Decl *Old, 1969 AvailabilityMergeKind AMK = AMK_Redeclaration); 1970 void MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls); 1971 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, 1972 bool MergeTypeWithOld); 1973 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 1974 Scope *S, bool MergeTypeWithOld); 1975 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); 1976 void MergeVarDecl(VarDecl *New, LookupResult &Previous); 1977 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld); 1978 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); 1979 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); 1980 1981 // AssignmentAction - This is used by all the assignment diagnostic functions 1982 // to represent what is actually causing the operation 1983 enum AssignmentAction { 1984 AA_Assigning, 1985 AA_Passing, 1986 AA_Returning, 1987 AA_Converting, 1988 AA_Initializing, 1989 AA_Sending, 1990 AA_Casting, 1991 AA_Passing_CFAudited 1992 }; 1993 1994 /// C++ Overloading. 1995 enum OverloadKind { 1996 /// This is a legitimate overload: the existing declarations are 1997 /// functions or function templates with different signatures. 1998 Ovl_Overload, 1999 2000 /// This is not an overload because the signature exactly matches 2001 /// an existing declaration. 2002 Ovl_Match, 2003 2004 /// This is not an overload because the lookup results contain a 2005 /// non-function. 2006 Ovl_NonFunction 2007 }; 2008 OverloadKind CheckOverload(Scope *S, 2009 FunctionDecl *New, 2010 const LookupResult &OldDecls, 2011 NamedDecl *&OldDecl, 2012 bool IsForUsingDecl); 2013 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl); 2014 2015 /// \brief Checks availability of the function depending on the current 2016 /// function context.Inside an unavailable function,unavailability is ignored. 2017 /// 2018 /// \returns true if \p FD is unavailable and current context is inside 2019 /// an available function, false otherwise. 2020 bool isFunctionConsideredUnavailable(FunctionDecl *FD); 2021 2022 ImplicitConversionSequence 2023 TryImplicitConversion(Expr *From, QualType ToType, 2024 bool SuppressUserConversions, 2025 bool AllowExplicit, 2026 bool InOverloadResolution, 2027 bool CStyle, 2028 bool AllowObjCWritebackConversion); 2029 2030 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); 2031 bool IsFloatingPointPromotion(QualType FromType, QualType ToType); 2032 bool IsComplexPromotion(QualType FromType, QualType ToType); 2033 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2034 bool InOverloadResolution, 2035 QualType& ConvertedType, bool &IncompatibleObjC); 2036 bool isObjCPointerConversion(QualType FromType, QualType ToType, 2037 QualType& ConvertedType, bool &IncompatibleObjC); 2038 bool isObjCWritebackConversion(QualType FromType, QualType ToType, 2039 QualType &ConvertedType); 2040 bool IsBlockPointerConversion(QualType FromType, QualType ToType, 2041 QualType& ConvertedType); 2042 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2043 const FunctionProtoType *NewType, 2044 unsigned *ArgPos = nullptr); 2045 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2046 QualType FromType, QualType ToType); 2047 2048 CastKind PrepareCastToObjCObjectPointer(ExprResult &E); 2049 bool CheckPointerConversion(Expr *From, QualType ToType, 2050 CastKind &Kind, 2051 CXXCastPath& BasePath, 2052 bool IgnoreBaseAccess); 2053 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, 2054 bool InOverloadResolution, 2055 QualType &ConvertedType); 2056 bool CheckMemberPointerConversion(Expr *From, QualType ToType, 2057 CastKind &Kind, 2058 CXXCastPath &BasePath, 2059 bool IgnoreBaseAccess); 2060 bool IsQualificationConversion(QualType FromType, QualType ToType, 2061 bool CStyle, bool &ObjCLifetimeConversion); 2062 bool IsNoReturnConversion(QualType FromType, QualType ToType, 2063 QualType &ResultTy); 2064 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); 2065 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg); 2066 2067 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, 2068 const VarDecl *NRVOCandidate, 2069 QualType ResultType, 2070 Expr *Value, 2071 bool AllowNRVO = true); 2072 2073 bool CanPerformCopyInitialization(const InitializedEntity &Entity, 2074 ExprResult Init); 2075 ExprResult PerformCopyInitialization(const InitializedEntity &Entity, 2076 SourceLocation EqualLoc, 2077 ExprResult Init, 2078 bool TopLevelOfInitList = false, 2079 bool AllowExplicit = false); 2080 ExprResult PerformObjectArgumentInitialization(Expr *From, 2081 NestedNameSpecifier *Qualifier, 2082 NamedDecl *FoundDecl, 2083 CXXMethodDecl *Method); 2084 2085 ExprResult PerformContextuallyConvertToBool(Expr *From); 2086 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); 2087 2088 /// Contexts in which a converted constant expression is required. 2089 enum CCEKind { 2090 CCEK_CaseValue, ///< Expression in a case label. 2091 CCEK_Enumerator, ///< Enumerator value with fixed underlying type. 2092 CCEK_TemplateArg, ///< Value of a non-type template parameter. 2093 CCEK_NewExpr ///< Constant expression in a noptr-new-declarator. 2094 }; 2095 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, 2096 llvm::APSInt &Value, CCEKind CCE); 2097 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, 2098 APValue &Value, CCEKind CCE); 2099 2100 /// \brief Abstract base class used to perform a contextual implicit 2101 /// conversion from an expression to any type passing a filter. 2102 class ContextualImplicitConverter { 2103 public: 2104 bool Suppress; 2105 bool SuppressConversion; 2106 2107 ContextualImplicitConverter(bool Suppress = false, 2108 bool SuppressConversion = false) Suppress(Suppress)2109 : Suppress(Suppress), SuppressConversion(SuppressConversion) {} 2110 2111 /// \brief Determine whether the specified type is a valid destination type 2112 /// for this conversion. 2113 virtual bool match(QualType T) = 0; 2114 2115 /// \brief Emits a diagnostic complaining that the expression does not have 2116 /// integral or enumeration type. 2117 virtual SemaDiagnosticBuilder 2118 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0; 2119 2120 /// \brief Emits a diagnostic when the expression has incomplete class type. 2121 virtual SemaDiagnosticBuilder 2122 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; 2123 2124 /// \brief Emits a diagnostic when the only matching conversion function 2125 /// is explicit. 2126 virtual SemaDiagnosticBuilder diagnoseExplicitConv( 2127 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; 2128 2129 /// \brief Emits a note for the explicit conversion function. 2130 virtual SemaDiagnosticBuilder 2131 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; 2132 2133 /// \brief Emits a diagnostic when there are multiple possible conversion 2134 /// functions. 2135 virtual SemaDiagnosticBuilder 2136 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0; 2137 2138 /// \brief Emits a note for one of the candidate conversions. 2139 virtual SemaDiagnosticBuilder 2140 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; 2141 2142 /// \brief Emits a diagnostic when we picked a conversion function 2143 /// (for cases when we are not allowed to pick a conversion function). 2144 virtual SemaDiagnosticBuilder diagnoseConversion( 2145 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; 2146 ~ContextualImplicitConverter()2147 virtual ~ContextualImplicitConverter() {} 2148 }; 2149 2150 class ICEConvertDiagnoser : public ContextualImplicitConverter { 2151 bool AllowScopedEnumerations; 2152 2153 public: ICEConvertDiagnoser(bool AllowScopedEnumerations,bool Suppress,bool SuppressConversion)2154 ICEConvertDiagnoser(bool AllowScopedEnumerations, 2155 bool Suppress, bool SuppressConversion) 2156 : ContextualImplicitConverter(Suppress, SuppressConversion), 2157 AllowScopedEnumerations(AllowScopedEnumerations) {} 2158 2159 /// Match an integral or (possibly scoped) enumeration type. 2160 bool match(QualType T) override; 2161 2162 SemaDiagnosticBuilder diagnoseNoMatch(Sema & S,SourceLocation Loc,QualType T)2163 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override { 2164 return diagnoseNotInt(S, Loc, T); 2165 } 2166 2167 /// \brief Emits a diagnostic complaining that the expression does not have 2168 /// integral or enumeration type. 2169 virtual SemaDiagnosticBuilder 2170 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0; 2171 }; 2172 2173 /// Perform a contextual implicit conversion. 2174 ExprResult PerformContextualImplicitConversion( 2175 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter); 2176 2177 2178 enum ObjCSubscriptKind { 2179 OS_Array, 2180 OS_Dictionary, 2181 OS_Error 2182 }; 2183 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); 2184 2185 // Note that LK_String is intentionally after the other literals, as 2186 // this is used for diagnostics logic. 2187 enum ObjCLiteralKind { 2188 LK_Array, 2189 LK_Dictionary, 2190 LK_Numeric, 2191 LK_Boxed, 2192 LK_String, 2193 LK_Block, 2194 LK_None 2195 }; 2196 ObjCLiteralKind CheckLiteralKind(Expr *FromE); 2197 2198 ExprResult PerformObjectMemberConversion(Expr *From, 2199 NestedNameSpecifier *Qualifier, 2200 NamedDecl *FoundDecl, 2201 NamedDecl *Member); 2202 2203 // Members have to be NamespaceDecl* or TranslationUnitDecl*. 2204 // TODO: make this is a typesafe union. 2205 typedef llvm::SmallPtrSet<DeclContext *, 16> AssociatedNamespaceSet; 2206 typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet; 2207 2208 void AddOverloadCandidate(FunctionDecl *Function, 2209 DeclAccessPair FoundDecl, 2210 ArrayRef<Expr *> Args, 2211 OverloadCandidateSet& CandidateSet, 2212 bool SuppressUserConversions = false, 2213 bool PartialOverloading = false, 2214 bool AllowExplicit = false); 2215 void AddFunctionCandidates(const UnresolvedSetImpl &Functions, 2216 ArrayRef<Expr *> Args, 2217 OverloadCandidateSet &CandidateSet, 2218 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, 2219 bool SuppressUserConversions = false, 2220 bool PartialOverloading = false); 2221 void AddMethodCandidate(DeclAccessPair FoundDecl, 2222 QualType ObjectType, 2223 Expr::Classification ObjectClassification, 2224 ArrayRef<Expr *> Args, 2225 OverloadCandidateSet& CandidateSet, 2226 bool SuppressUserConversion = false); 2227 void AddMethodCandidate(CXXMethodDecl *Method, 2228 DeclAccessPair FoundDecl, 2229 CXXRecordDecl *ActingContext, QualType ObjectType, 2230 Expr::Classification ObjectClassification, 2231 ArrayRef<Expr *> Args, 2232 OverloadCandidateSet& CandidateSet, 2233 bool SuppressUserConversions = false, 2234 bool PartialOverloading = false); 2235 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 2236 DeclAccessPair FoundDecl, 2237 CXXRecordDecl *ActingContext, 2238 TemplateArgumentListInfo *ExplicitTemplateArgs, 2239 QualType ObjectType, 2240 Expr::Classification ObjectClassification, 2241 ArrayRef<Expr *> Args, 2242 OverloadCandidateSet& CandidateSet, 2243 bool SuppressUserConversions = false, 2244 bool PartialOverloading = false); 2245 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 2246 DeclAccessPair FoundDecl, 2247 TemplateArgumentListInfo *ExplicitTemplateArgs, 2248 ArrayRef<Expr *> Args, 2249 OverloadCandidateSet& CandidateSet, 2250 bool SuppressUserConversions = false, 2251 bool PartialOverloading = false); 2252 void AddConversionCandidate(CXXConversionDecl *Conversion, 2253 DeclAccessPair FoundDecl, 2254 CXXRecordDecl *ActingContext, 2255 Expr *From, QualType ToType, 2256 OverloadCandidateSet& CandidateSet, 2257 bool AllowObjCConversionOnExplicit); 2258 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 2259 DeclAccessPair FoundDecl, 2260 CXXRecordDecl *ActingContext, 2261 Expr *From, QualType ToType, 2262 OverloadCandidateSet &CandidateSet, 2263 bool AllowObjCConversionOnExplicit); 2264 void AddSurrogateCandidate(CXXConversionDecl *Conversion, 2265 DeclAccessPair FoundDecl, 2266 CXXRecordDecl *ActingContext, 2267 const FunctionProtoType *Proto, 2268 Expr *Object, ArrayRef<Expr *> Args, 2269 OverloadCandidateSet& CandidateSet); 2270 void AddMemberOperatorCandidates(OverloadedOperatorKind Op, 2271 SourceLocation OpLoc, ArrayRef<Expr *> Args, 2272 OverloadCandidateSet& CandidateSet, 2273 SourceRange OpRange = SourceRange()); 2274 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 2275 ArrayRef<Expr *> Args, 2276 OverloadCandidateSet& CandidateSet, 2277 bool IsAssignmentOperator = false, 2278 unsigned NumContextualBoolArguments = 0); 2279 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 2280 SourceLocation OpLoc, ArrayRef<Expr *> Args, 2281 OverloadCandidateSet& CandidateSet); 2282 void AddArgumentDependentLookupCandidates(DeclarationName Name, 2283 SourceLocation Loc, 2284 ArrayRef<Expr *> Args, 2285 TemplateArgumentListInfo *ExplicitTemplateArgs, 2286 OverloadCandidateSet& CandidateSet, 2287 bool PartialOverloading = false); 2288 2289 // Emit as a 'note' the specific overload candidate 2290 void NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType = QualType()); 2291 2292 // Emit as a series of 'note's all template and non-templates 2293 // identified by the expression Expr 2294 void NoteAllOverloadCandidates(Expr* E, QualType DestType = QualType()); 2295 2296 /// Check the enable_if expressions on the given function. Returns the first 2297 /// failing attribute, or NULL if they were all successful. 2298 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 2299 bool MissingImplicitThis = false); 2300 2301 // [PossiblyAFunctionType] --> [Return] 2302 // NonFunctionType --> NonFunctionType 2303 // R (A) --> R(A) 2304 // R (*)(A) --> R (A) 2305 // R (&)(A) --> R (A) 2306 // R (S::*)(A) --> R (A) 2307 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); 2308 2309 FunctionDecl * 2310 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 2311 QualType TargetType, 2312 bool Complain, 2313 DeclAccessPair &Found, 2314 bool *pHadMultipleCandidates = nullptr); 2315 2316 FunctionDecl * 2317 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 2318 bool Complain = false, 2319 DeclAccessPair *Found = nullptr); 2320 2321 bool ResolveAndFixSingleFunctionTemplateSpecialization( 2322 ExprResult &SrcExpr, 2323 bool DoFunctionPointerConverion = false, 2324 bool Complain = false, 2325 const SourceRange& OpRangeForComplaining = SourceRange(), 2326 QualType DestTypeForComplaining = QualType(), 2327 unsigned DiagIDForComplaining = 0); 2328 2329 2330 Expr *FixOverloadedFunctionReference(Expr *E, 2331 DeclAccessPair FoundDecl, 2332 FunctionDecl *Fn); 2333 ExprResult FixOverloadedFunctionReference(ExprResult, 2334 DeclAccessPair FoundDecl, 2335 FunctionDecl *Fn); 2336 2337 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 2338 ArrayRef<Expr *> Args, 2339 OverloadCandidateSet &CandidateSet, 2340 bool PartialOverloading = false); 2341 2342 // An enum used to represent the different possible results of building a 2343 // range-based for loop. 2344 enum ForRangeStatus { 2345 FRS_Success, 2346 FRS_NoViableFunction, 2347 FRS_DiagnosticIssued 2348 }; 2349 2350 // An enum to represent whether something is dealing with a call to begin() 2351 // or a call to end() in a range-based for loop. 2352 enum BeginEndFunction { 2353 BEF_begin, 2354 BEF_end 2355 }; 2356 2357 ForRangeStatus BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 2358 SourceLocation RangeLoc, 2359 VarDecl *Decl, 2360 BeginEndFunction BEF, 2361 const DeclarationNameInfo &NameInfo, 2362 LookupResult &MemberLookup, 2363 OverloadCandidateSet *CandidateSet, 2364 Expr *Range, ExprResult *CallExpr); 2365 2366 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, 2367 UnresolvedLookupExpr *ULE, 2368 SourceLocation LParenLoc, 2369 MultiExprArg Args, 2370 SourceLocation RParenLoc, 2371 Expr *ExecConfig, 2372 bool AllowTypoCorrection=true); 2373 2374 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, 2375 MultiExprArg Args, SourceLocation RParenLoc, 2376 OverloadCandidateSet *CandidateSet, 2377 ExprResult *Result); 2378 2379 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, 2380 unsigned Opc, 2381 const UnresolvedSetImpl &Fns, 2382 Expr *input); 2383 2384 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, 2385 unsigned Opc, 2386 const UnresolvedSetImpl &Fns, 2387 Expr *LHS, Expr *RHS); 2388 2389 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 2390 SourceLocation RLoc, 2391 Expr *Base,Expr *Idx); 2392 2393 ExprResult 2394 BuildCallToMemberFunction(Scope *S, Expr *MemExpr, 2395 SourceLocation LParenLoc, 2396 MultiExprArg Args, 2397 SourceLocation RParenLoc); 2398 ExprResult 2399 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, 2400 MultiExprArg Args, 2401 SourceLocation RParenLoc); 2402 2403 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, 2404 SourceLocation OpLoc, 2405 bool *NoArrowOperatorFound = nullptr); 2406 2407 /// CheckCallReturnType - Checks that a call expression's return type is 2408 /// complete. Returns true on failure. The location passed in is the location 2409 /// that best represents the call. 2410 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 2411 CallExpr *CE, FunctionDecl *FD); 2412 2413 /// Helpers for dealing with blocks and functions. 2414 bool CheckParmsForFunctionDef(ParmVarDecl *const *Param, 2415 ParmVarDecl *const *ParamEnd, 2416 bool CheckParameterNames); 2417 void CheckCXXDefaultArguments(FunctionDecl *FD); 2418 void CheckExtraCXXDefaultArguments(Declarator &D); 2419 Scope *getNonFieldDeclScope(Scope *S); 2420 2421 /// \name Name lookup 2422 /// 2423 /// These routines provide name lookup that is used during semantic 2424 /// analysis to resolve the various kinds of names (identifiers, 2425 /// overloaded operator names, constructor names, etc.) into zero or 2426 /// more declarations within a particular scope. The major entry 2427 /// points are LookupName, which performs unqualified name lookup, 2428 /// and LookupQualifiedName, which performs qualified name lookup. 2429 /// 2430 /// All name lookup is performed based on some specific criteria, 2431 /// which specify what names will be visible to name lookup and how 2432 /// far name lookup should work. These criteria are important both 2433 /// for capturing language semantics (certain lookups will ignore 2434 /// certain names, for example) and for performance, since name 2435 /// lookup is often a bottleneck in the compilation of C++. Name 2436 /// lookup criteria is specified via the LookupCriteria enumeration. 2437 /// 2438 /// The results of name lookup can vary based on the kind of name 2439 /// lookup performed, the current language, and the translation 2440 /// unit. In C, for example, name lookup will either return nothing 2441 /// (no entity found) or a single declaration. In C++, name lookup 2442 /// can additionally refer to a set of overloaded functions or 2443 /// result in an ambiguity. All of the possible results of name 2444 /// lookup are captured by the LookupResult class, which provides 2445 /// the ability to distinguish among them. 2446 //@{ 2447 2448 /// @brief Describes the kind of name lookup to perform. 2449 enum LookupNameKind { 2450 /// Ordinary name lookup, which finds ordinary names (functions, 2451 /// variables, typedefs, etc.) in C and most kinds of names 2452 /// (functions, variables, members, types, etc.) in C++. 2453 LookupOrdinaryName = 0, 2454 /// Tag name lookup, which finds the names of enums, classes, 2455 /// structs, and unions. 2456 LookupTagName, 2457 /// Label name lookup. 2458 LookupLabel, 2459 /// Member name lookup, which finds the names of 2460 /// class/struct/union members. 2461 LookupMemberName, 2462 /// Look up of an operator name (e.g., operator+) for use with 2463 /// operator overloading. This lookup is similar to ordinary name 2464 /// lookup, but will ignore any declarations that are class members. 2465 LookupOperatorName, 2466 /// Look up of a name that precedes the '::' scope resolution 2467 /// operator in C++. This lookup completely ignores operator, object, 2468 /// function, and enumerator names (C++ [basic.lookup.qual]p1). 2469 LookupNestedNameSpecifierName, 2470 /// Look up a namespace name within a C++ using directive or 2471 /// namespace alias definition, ignoring non-namespace names (C++ 2472 /// [basic.lookup.udir]p1). 2473 LookupNamespaceName, 2474 /// Look up all declarations in a scope with the given name, 2475 /// including resolved using declarations. This is appropriate 2476 /// for checking redeclarations for a using declaration. 2477 LookupUsingDeclName, 2478 /// Look up an ordinary name that is going to be redeclared as a 2479 /// name with linkage. This lookup ignores any declarations that 2480 /// are outside of the current scope unless they have linkage. See 2481 /// C99 6.2.2p4-5 and C++ [basic.link]p6. 2482 LookupRedeclarationWithLinkage, 2483 /// Look up a friend of a local class. This lookup does not look 2484 /// outside the innermost non-class scope. See C++11 [class.friend]p11. 2485 LookupLocalFriendName, 2486 /// Look up the name of an Objective-C protocol. 2487 LookupObjCProtocolName, 2488 /// Look up implicit 'self' parameter of an objective-c method. 2489 LookupObjCImplicitSelfParam, 2490 /// \brief Look up any declaration with any name. 2491 LookupAnyName 2492 }; 2493 2494 /// \brief Specifies whether (or how) name lookup is being performed for a 2495 /// redeclaration (vs. a reference). 2496 enum RedeclarationKind { 2497 /// \brief The lookup is a reference to this name that is not for the 2498 /// purpose of redeclaring the name. 2499 NotForRedeclaration = 0, 2500 /// \brief The lookup results will be used for redeclaration of a name, 2501 /// if an entity by that name already exists. 2502 ForRedeclaration 2503 }; 2504 2505 /// \brief The possible outcomes of name lookup for a literal operator. 2506 enum LiteralOperatorLookupResult { 2507 /// \brief The lookup resulted in an error. 2508 LOLR_Error, 2509 /// \brief The lookup found a single 'cooked' literal operator, which 2510 /// expects a normal literal to be built and passed to it. 2511 LOLR_Cooked, 2512 /// \brief The lookup found a single 'raw' literal operator, which expects 2513 /// a string literal containing the spelling of the literal token. 2514 LOLR_Raw, 2515 /// \brief The lookup found an overload set of literal operator templates, 2516 /// which expect the characters of the spelling of the literal token to be 2517 /// passed as a non-type template argument pack. 2518 LOLR_Template, 2519 /// \brief The lookup found an overload set of literal operator templates, 2520 /// which expect the character type and characters of the spelling of the 2521 /// string literal token to be passed as template arguments. 2522 LOLR_StringTemplate 2523 }; 2524 2525 SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D, 2526 CXXSpecialMember SM, 2527 bool ConstArg, 2528 bool VolatileArg, 2529 bool RValueThis, 2530 bool ConstThis, 2531 bool VolatileThis); 2532 2533 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator; 2534 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)> 2535 TypoRecoveryCallback; 2536 2537 private: 2538 bool CppLookupName(LookupResult &R, Scope *S); 2539 2540 struct TypoExprState { 2541 std::unique_ptr<TypoCorrectionConsumer> Consumer; 2542 TypoDiagnosticGenerator DiagHandler; 2543 TypoRecoveryCallback RecoveryHandler; 2544 TypoExprState(); 2545 TypoExprState(TypoExprState&& other) LLVM_NOEXCEPT; 2546 TypoExprState& operator=(TypoExprState&& other) LLVM_NOEXCEPT; 2547 }; 2548 2549 /// \brief The set of unhandled TypoExprs and their associated state. 2550 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos; 2551 2552 /// \brief Creates a new TypoExpr AST node. 2553 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, 2554 TypoDiagnosticGenerator TDG, 2555 TypoRecoveryCallback TRC); 2556 2557 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls. 2558 // 2559 // The boolean value will be true to indicate that the namespace was loaded 2560 // from an AST/PCH file, or false otherwise. 2561 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces; 2562 2563 /// \brief Whether we have already loaded known namespaces from an extenal 2564 /// source. 2565 bool LoadedExternalKnownNamespaces; 2566 2567 /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and 2568 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction 2569 /// should be skipped entirely. 2570 std::unique_ptr<TypoCorrectionConsumer> 2571 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo, 2572 Sema::LookupNameKind LookupKind, Scope *S, 2573 CXXScopeSpec *SS, 2574 std::unique_ptr<CorrectionCandidateCallback> CCC, 2575 DeclContext *MemberContext, bool EnteringContext, 2576 const ObjCObjectPointerType *OPT, 2577 bool ErrorRecovery); 2578 2579 public: 2580 const TypoExprState &getTypoExprState(TypoExpr *TE) const; 2581 2582 /// \brief Clears the state of the given TypoExpr. 2583 void clearDelayedTypo(TypoExpr *TE); 2584 2585 /// \brief Look up a name, looking for a single declaration. Return 2586 /// null if the results were absent, ambiguous, or overloaded. 2587 /// 2588 /// It is preferable to use the elaborated form and explicitly handle 2589 /// ambiguity and overloaded. 2590 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, 2591 SourceLocation Loc, 2592 LookupNameKind NameKind, 2593 RedeclarationKind Redecl 2594 = NotForRedeclaration); 2595 bool LookupName(LookupResult &R, Scope *S, 2596 bool AllowBuiltinCreation = false); 2597 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 2598 bool InUnqualifiedLookup = false); 2599 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 2600 CXXScopeSpec &SS); 2601 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 2602 bool AllowBuiltinCreation = false, 2603 bool EnteringContext = false); 2604 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, 2605 RedeclarationKind Redecl 2606 = NotForRedeclaration); 2607 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class); 2608 2609 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, 2610 QualType T1, QualType T2, 2611 UnresolvedSetImpl &Functions); 2612 void addOverloadedOperatorToUnresolvedSet(UnresolvedSetImpl &Functions, 2613 DeclAccessPair Operator, 2614 QualType T1, QualType T2); 2615 2616 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, 2617 SourceLocation GnuLabelLoc = SourceLocation()); 2618 2619 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); 2620 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); 2621 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, 2622 unsigned Quals); 2623 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, 2624 bool RValueThis, unsigned ThisQuals); 2625 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, 2626 unsigned Quals); 2627 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, 2628 bool RValueThis, unsigned ThisQuals); 2629 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); 2630 2631 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id); 2632 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, 2633 ArrayRef<QualType> ArgTys, 2634 bool AllowRaw, 2635 bool AllowTemplate, 2636 bool AllowStringTemplate); 2637 bool isKnownName(StringRef name); 2638 2639 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, 2640 ArrayRef<Expr *> Args, ADLResult &Functions); 2641 2642 void LookupVisibleDecls(Scope *S, LookupNameKind Kind, 2643 VisibleDeclConsumer &Consumer, 2644 bool IncludeGlobalScope = true); 2645 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, 2646 VisibleDeclConsumer &Consumer, 2647 bool IncludeGlobalScope = true); 2648 2649 enum CorrectTypoKind { 2650 CTK_NonError, // CorrectTypo used in a non error recovery situation. 2651 CTK_ErrorRecovery // CorrectTypo used in normal error recovery. 2652 }; 2653 2654 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, 2655 Sema::LookupNameKind LookupKind, 2656 Scope *S, CXXScopeSpec *SS, 2657 std::unique_ptr<CorrectionCandidateCallback> CCC, 2658 CorrectTypoKind Mode, 2659 DeclContext *MemberContext = nullptr, 2660 bool EnteringContext = false, 2661 const ObjCObjectPointerType *OPT = nullptr, 2662 bool RecordFailure = true); 2663 2664 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo, 2665 Sema::LookupNameKind LookupKind, Scope *S, 2666 CXXScopeSpec *SS, 2667 std::unique_ptr<CorrectionCandidateCallback> CCC, 2668 TypoDiagnosticGenerator TDG, 2669 TypoRecoveryCallback TRC, CorrectTypoKind Mode, 2670 DeclContext *MemberContext = nullptr, 2671 bool EnteringContext = false, 2672 const ObjCObjectPointerType *OPT = nullptr); 2673 2674 ExprResult 2675 CorrectDelayedTyposInExpr(Expr *E, 2676 llvm::function_ref<ExprResult(Expr *)> Filter = 2677 [](Expr *E) -> ExprResult { return E; }); 2678 2679 ExprResult 2680 CorrectDelayedTyposInExpr(ExprResult ER, 2681 llvm::function_ref<ExprResult(Expr *)> Filter = 2682 [](Expr *E) -> ExprResult { return E; }) { 2683 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter); 2684 } 2685 2686 void diagnoseTypo(const TypoCorrection &Correction, 2687 const PartialDiagnostic &TypoDiag, 2688 bool ErrorRecovery = true); 2689 2690 void diagnoseTypo(const TypoCorrection &Correction, 2691 const PartialDiagnostic &TypoDiag, 2692 const PartialDiagnostic &PrevNote, 2693 bool ErrorRecovery = true); 2694 2695 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, 2696 ArrayRef<Expr *> Args, 2697 AssociatedNamespaceSet &AssociatedNamespaces, 2698 AssociatedClassSet &AssociatedClasses); 2699 2700 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 2701 bool ConsiderLinkage, bool AllowInlineNamespace); 2702 2703 void DiagnoseAmbiguousLookup(LookupResult &Result); 2704 //@} 2705 2706 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, 2707 SourceLocation IdLoc, 2708 bool TypoCorrection = false); 2709 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2710 Scope *S, bool ForRedeclaration, 2711 SourceLocation Loc); 2712 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, 2713 Scope *S); 2714 void AddKnownFunctionAttributes(FunctionDecl *FD); 2715 2716 // More parsing and symbol table subroutines. 2717 2718 void ProcessPragmaWeak(Scope *S, Decl *D); 2719 // Decl attributes - this routine is the top level dispatcher. 2720 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); 2721 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL, 2722 bool IncludeCXX11Attributes = true); 2723 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, 2724 const AttributeList *AttrList); 2725 2726 void checkUnusedDeclAttributes(Declarator &D); 2727 2728 /// Determine if type T is a valid subject for a nonnull and similar 2729 /// attributes. By default, we look through references (the behavior used by 2730 /// nonnull), but if the second parameter is true, then we treat a reference 2731 /// type as valid. 2732 bool isValidPointerAttrType(QualType T, bool RefOkay = false); 2733 2734 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value); 2735 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC, 2736 const FunctionDecl *FD = nullptr); 2737 bool CheckNoReturnAttr(const AttributeList &attr); 2738 bool checkStringLiteralArgumentAttr(const AttributeList &Attr, 2739 unsigned ArgNum, StringRef &Str, 2740 SourceLocation *ArgLocation = nullptr); 2741 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str); 2742 bool checkMSInheritanceAttrOnDefinition( 2743 CXXRecordDecl *RD, SourceRange Range, bool BestCase, 2744 MSInheritanceAttr::Spelling SemanticSpelling); 2745 2746 void CheckAlignasUnderalignment(Decl *D); 2747 2748 /// Adjust the calling convention of a method to be the ABI default if it 2749 /// wasn't specified explicitly. This handles method types formed from 2750 /// function type typedefs and typename template arguments. 2751 void adjustMemberFunctionCC(QualType &T, bool IsStatic); 2752 2753 // Check if there is an explicit attribute, but only look through parens. 2754 // The intent is to look for an attribute on the current declarator, but not 2755 // one that came from a typedef. 2756 bool hasExplicitCallingConv(QualType &T); 2757 2758 /// Get the outermost AttributedType node that sets a calling convention. 2759 /// Valid types should not have multiple attributes with different CCs. 2760 const AttributedType *getCallingConvAttributedType(QualType T) const; 2761 2762 /// \brief Stmt attributes - this routine is the top level dispatcher. 2763 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs, 2764 SourceRange Range); 2765 2766 void WarnConflictingTypedMethods(ObjCMethodDecl *Method, 2767 ObjCMethodDecl *MethodDecl, 2768 bool IsProtocolMethodDecl); 2769 2770 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, 2771 ObjCMethodDecl *Overridden, 2772 bool IsProtocolMethodDecl); 2773 2774 /// WarnExactTypedMethods - This routine issues a warning if method 2775 /// implementation declaration matches exactly that of its declaration. 2776 void WarnExactTypedMethods(ObjCMethodDecl *Method, 2777 ObjCMethodDecl *MethodDecl, 2778 bool IsProtocolMethodDecl); 2779 2780 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet; 2781 typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap; 2782 2783 /// CheckImplementationIvars - This routine checks if the instance variables 2784 /// listed in the implelementation match those listed in the interface. 2785 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, 2786 ObjCIvarDecl **Fields, unsigned nIvars, 2787 SourceLocation Loc); 2788 2789 /// ImplMethodsVsClassMethods - This is main routine to warn if any method 2790 /// remains unimplemented in the class or category \@implementation. 2791 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, 2792 ObjCContainerDecl* IDecl, 2793 bool IncompleteImpl = false); 2794 2795 /// DiagnoseUnimplementedProperties - This routine warns on those properties 2796 /// which must be implemented by this implementation. 2797 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, 2798 ObjCContainerDecl *CDecl, 2799 bool SynthesizeProperties); 2800 2801 /// DefaultSynthesizeProperties - This routine default synthesizes all 2802 /// properties which must be synthesized in the class's \@implementation. 2803 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl, 2804 ObjCInterfaceDecl *IDecl); 2805 void DefaultSynthesizeProperties(Scope *S, Decl *D); 2806 2807 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is 2808 /// an ivar synthesized for 'Method' and 'Method' is a property accessor 2809 /// declared in class 'IFace'. 2810 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, 2811 ObjCMethodDecl *Method, ObjCIvarDecl *IV); 2812 2813 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which 2814 /// backs the property is not used in the property's accessor. 2815 void DiagnoseUnusedBackingIvarInAccessor(Scope *S, 2816 const ObjCImplementationDecl *ImplD); 2817 2818 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and 2819 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL. 2820 /// It also returns ivar's property on success. 2821 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, 2822 const ObjCPropertyDecl *&PDecl) const; 2823 2824 /// Called by ActOnProperty to handle \@property declarations in 2825 /// class extensions. 2826 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S, 2827 SourceLocation AtLoc, 2828 SourceLocation LParenLoc, 2829 FieldDeclarator &FD, 2830 Selector GetterSel, 2831 Selector SetterSel, 2832 const bool isAssign, 2833 const bool isReadWrite, 2834 const unsigned Attributes, 2835 const unsigned AttributesAsWritten, 2836 bool *isOverridingProperty, 2837 TypeSourceInfo *T, 2838 tok::ObjCKeywordKind MethodImplKind); 2839 2840 /// Called by ActOnProperty and HandlePropertyInClassExtension to 2841 /// handle creating the ObjcPropertyDecl for a category or \@interface. 2842 ObjCPropertyDecl *CreatePropertyDecl(Scope *S, 2843 ObjCContainerDecl *CDecl, 2844 SourceLocation AtLoc, 2845 SourceLocation LParenLoc, 2846 FieldDeclarator &FD, 2847 Selector GetterSel, 2848 Selector SetterSel, 2849 const bool isAssign, 2850 const bool isReadWrite, 2851 const unsigned Attributes, 2852 const unsigned AttributesAsWritten, 2853 TypeSourceInfo *T, 2854 tok::ObjCKeywordKind MethodImplKind, 2855 DeclContext *lexicalDC = nullptr); 2856 2857 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via 2858 /// warning) when atomic property has one but not the other user-declared 2859 /// setter or getter. 2860 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, 2861 ObjCContainerDecl* IDecl); 2862 2863 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); 2864 2865 void DiagnoseMissingDesignatedInitOverrides( 2866 const ObjCImplementationDecl *ImplD, 2867 const ObjCInterfaceDecl *IFD); 2868 2869 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); 2870 2871 enum MethodMatchStrategy { 2872 MMS_loose, 2873 MMS_strict 2874 }; 2875 2876 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns 2877 /// true, or false, accordingly. 2878 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, 2879 const ObjCMethodDecl *PrevMethod, 2880 MethodMatchStrategy strategy = MMS_strict); 2881 2882 /// MatchAllMethodDeclarations - Check methods declaraed in interface or 2883 /// or protocol against those declared in their implementations. 2884 void MatchAllMethodDeclarations(const SelectorSet &InsMap, 2885 const SelectorSet &ClsMap, 2886 SelectorSet &InsMapSeen, 2887 SelectorSet &ClsMapSeen, 2888 ObjCImplDecl* IMPDecl, 2889 ObjCContainerDecl* IDecl, 2890 bool &IncompleteImpl, 2891 bool ImmediateClass, 2892 bool WarnCategoryMethodImpl=false); 2893 2894 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in 2895 /// category matches with those implemented in its primary class and 2896 /// warns each time an exact match is found. 2897 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); 2898 2899 /// \brief Add the given method to the list of globally-known methods. 2900 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); 2901 2902 private: 2903 /// AddMethodToGlobalPool - Add an instance or factory method to the global 2904 /// pool. See descriptoin of AddInstanceMethodToGlobalPool. 2905 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); 2906 2907 /// LookupMethodInGlobalPool - Returns the instance or factory method and 2908 /// optionally warns if there are multiple signatures. 2909 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, 2910 bool receiverIdOrClass, 2911 bool instance); 2912 2913 public: 2914 /// \brief - Returns instance or factory methods in global method pool for 2915 /// given selector. If no such method or only one method found, function returns 2916 /// false; otherwise, it returns true 2917 bool CollectMultipleMethodsInGlobalPool(Selector Sel, 2918 SmallVectorImpl<ObjCMethodDecl*>& Methods, 2919 bool instance); 2920 2921 bool AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, 2922 SourceRange R, 2923 bool receiverIdOrClass); 2924 2925 void DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, 2926 Selector Sel, SourceRange R, 2927 bool receiverIdOrClass); 2928 2929 private: 2930 /// \brief - Returns a selector which best matches given argument list or 2931 /// nullptr if none could be found 2932 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args, 2933 bool IsInstance); 2934 2935 2936 /// \brief Record the typo correction failure and return an empty correction. 2937 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc, 2938 bool RecordFailure = true) { 2939 if (RecordFailure) 2940 TypoCorrectionFailures[Typo].insert(TypoLoc); 2941 return TypoCorrection(); 2942 } 2943 2944 public: 2945 /// AddInstanceMethodToGlobalPool - All instance methods in a translation 2946 /// unit are added to a global pool. This allows us to efficiently associate 2947 /// a selector with a method declaraation for purposes of typechecking 2948 /// messages sent to "id" (where the class of the object is unknown). 2949 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 2950 AddMethodToGlobalPool(Method, impl, /*instance*/true); 2951 } 2952 2953 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. 2954 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 2955 AddMethodToGlobalPool(Method, impl, /*instance*/false); 2956 } 2957 2958 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global 2959 /// pool. 2960 void AddAnyMethodToGlobalPool(Decl *D); 2961 2962 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if 2963 /// there are multiple signatures. 2964 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, 2965 bool receiverIdOrClass=false) { 2966 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 2967 /*instance*/true); 2968 } 2969 2970 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if 2971 /// there are multiple signatures. 2972 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, 2973 bool receiverIdOrClass=false) { 2974 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 2975 /*instance*/false); 2976 } 2977 2978 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel, 2979 QualType ObjectType=QualType()); 2980 /// LookupImplementedMethodInGlobalPool - Returns the method which has an 2981 /// implementation. 2982 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); 2983 2984 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require 2985 /// initialization. 2986 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, 2987 SmallVectorImpl<ObjCIvarDecl*> &Ivars); 2988 2989 //===--------------------------------------------------------------------===// 2990 // Statement Parsing Callbacks: SemaStmt.cpp. 2991 public: 2992 class FullExprArg { 2993 public: FullExprArg(Sema & actions)2994 FullExprArg(Sema &actions) : E(nullptr) { } 2995 release()2996 ExprResult release() { 2997 return E; 2998 } 2999 get()3000 Expr *get() const { return E; } 3001 3002 Expr *operator->() { 3003 return E; 3004 } 3005 3006 private: 3007 // FIXME: No need to make the entire Sema class a friend when it's just 3008 // Sema::MakeFullExpr that needs access to the constructor below. 3009 friend class Sema; 3010 FullExprArg(Expr * expr)3011 explicit FullExprArg(Expr *expr) : E(expr) {} 3012 3013 Expr *E; 3014 }; 3015 MakeFullExpr(Expr * Arg)3016 FullExprArg MakeFullExpr(Expr *Arg) { 3017 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation()); 3018 } MakeFullExpr(Expr * Arg,SourceLocation CC)3019 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { 3020 return FullExprArg(ActOnFinishFullExpr(Arg, CC).get()); 3021 } MakeFullDiscardedValueExpr(Expr * Arg)3022 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { 3023 ExprResult FE = 3024 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), 3025 /*DiscardedValue*/ true); 3026 return FullExprArg(FE.get()); 3027 } 3028 3029 StmtResult ActOnExprStmt(ExprResult Arg); 3030 StmtResult ActOnExprStmtError(); 3031 3032 StmtResult ActOnNullStmt(SourceLocation SemiLoc, 3033 bool HasLeadingEmptyMacro = false); 3034 3035 void ActOnStartOfCompoundStmt(); 3036 void ActOnFinishOfCompoundStmt(); 3037 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, 3038 ArrayRef<Stmt *> Elts, bool isStmtExpr); 3039 3040 /// \brief A RAII object to enter scope of a compound statement. 3041 class CompoundScopeRAII { 3042 public: CompoundScopeRAII(Sema & S)3043 CompoundScopeRAII(Sema &S): S(S) { 3044 S.ActOnStartOfCompoundStmt(); 3045 } 3046 ~CompoundScopeRAII()3047 ~CompoundScopeRAII() { 3048 S.ActOnFinishOfCompoundStmt(); 3049 } 3050 3051 private: 3052 Sema &S; 3053 }; 3054 3055 /// An RAII helper that pops function a function scope on exit. 3056 struct FunctionScopeRAII { 3057 Sema &S; 3058 bool Active; FunctionScopeRAIIFunctionScopeRAII3059 FunctionScopeRAII(Sema &S) : S(S), Active(true) {} ~FunctionScopeRAIIFunctionScopeRAII3060 ~FunctionScopeRAII() { 3061 if (Active) 3062 S.PopFunctionScopeInfo(); 3063 } disableFunctionScopeRAII3064 void disable() { Active = false; } 3065 }; 3066 3067 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, 3068 SourceLocation StartLoc, 3069 SourceLocation EndLoc); 3070 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); 3071 StmtResult ActOnForEachLValueExpr(Expr *E); 3072 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal, 3073 SourceLocation DotDotDotLoc, Expr *RHSVal, 3074 SourceLocation ColonLoc); 3075 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); 3076 3077 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, 3078 SourceLocation ColonLoc, 3079 Stmt *SubStmt, Scope *CurScope); 3080 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, 3081 SourceLocation ColonLoc, Stmt *SubStmt); 3082 3083 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc, 3084 ArrayRef<const Attr*> Attrs, 3085 Stmt *SubStmt); 3086 3087 StmtResult ActOnIfStmt(SourceLocation IfLoc, 3088 FullExprArg CondVal, Decl *CondVar, 3089 Stmt *ThenVal, 3090 SourceLocation ElseLoc, Stmt *ElseVal); 3091 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, 3092 Expr *Cond, 3093 Decl *CondVar); 3094 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, 3095 Stmt *Switch, Stmt *Body); 3096 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, 3097 FullExprArg Cond, 3098 Decl *CondVar, Stmt *Body); 3099 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 3100 SourceLocation WhileLoc, 3101 SourceLocation CondLParen, Expr *Cond, 3102 SourceLocation CondRParen); 3103 3104 StmtResult ActOnForStmt(SourceLocation ForLoc, 3105 SourceLocation LParenLoc, 3106 Stmt *First, FullExprArg Second, 3107 Decl *SecondVar, 3108 FullExprArg Third, 3109 SourceLocation RParenLoc, 3110 Stmt *Body); 3111 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, 3112 Expr *collection); 3113 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, 3114 Stmt *First, Expr *collection, 3115 SourceLocation RParenLoc); 3116 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body); 3117 3118 enum BuildForRangeKind { 3119 /// Initial building of a for-range statement. 3120 BFRK_Build, 3121 /// Instantiation or recovery rebuild of a for-range statement. Don't 3122 /// attempt any typo-correction. 3123 BFRK_Rebuild, 3124 /// Determining whether a for-range statement could be built. Avoid any 3125 /// unnecessary or irreversible actions. 3126 BFRK_Check 3127 }; 3128 3129 StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc, Stmt *LoopVar, 3130 SourceLocation ColonLoc, Expr *Collection, 3131 SourceLocation RParenLoc, 3132 BuildForRangeKind Kind); 3133 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, 3134 SourceLocation ColonLoc, 3135 Stmt *RangeDecl, Stmt *BeginEndDecl, 3136 Expr *Cond, Expr *Inc, 3137 Stmt *LoopVarDecl, 3138 SourceLocation RParenLoc, 3139 BuildForRangeKind Kind); 3140 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); 3141 3142 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, 3143 SourceLocation LabelLoc, 3144 LabelDecl *TheDecl); 3145 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, 3146 SourceLocation StarLoc, 3147 Expr *DestExp); 3148 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); 3149 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); 3150 3151 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, 3152 CapturedRegionKind Kind, unsigned NumParams); 3153 typedef std::pair<StringRef, QualType> CapturedParamNameType; 3154 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, 3155 CapturedRegionKind Kind, 3156 ArrayRef<CapturedParamNameType> Params); 3157 StmtResult ActOnCapturedRegionEnd(Stmt *S); 3158 void ActOnCapturedRegionError(); 3159 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, 3160 SourceLocation Loc, 3161 unsigned NumParams); 3162 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E, 3163 bool AllowFunctionParameters); 3164 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD, 3165 bool AllowFunctionParameters); 3166 3167 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, 3168 Scope *CurScope); 3169 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); 3170 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); 3171 3172 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, 3173 bool IsVolatile, unsigned NumOutputs, 3174 unsigned NumInputs, IdentifierInfo **Names, 3175 MultiExprArg Constraints, MultiExprArg Exprs, 3176 Expr *AsmString, MultiExprArg Clobbers, 3177 SourceLocation RParenLoc); 3178 3179 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, 3180 SourceLocation TemplateKWLoc, 3181 UnqualifiedId &Id, 3182 llvm::InlineAsmIdentifierInfo &Info, 3183 bool IsUnevaluatedContext); 3184 bool LookupInlineAsmField(StringRef Base, StringRef Member, 3185 unsigned &Offset, SourceLocation AsmLoc); 3186 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, 3187 ArrayRef<Token> AsmToks, 3188 StringRef AsmString, 3189 unsigned NumOutputs, unsigned NumInputs, 3190 ArrayRef<StringRef> Constraints, 3191 ArrayRef<StringRef> Clobbers, 3192 ArrayRef<Expr*> Exprs, 3193 SourceLocation EndLoc); 3194 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName, 3195 SourceLocation Location, 3196 bool AlwaysCreate); 3197 3198 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, 3199 SourceLocation StartLoc, 3200 SourceLocation IdLoc, IdentifierInfo *Id, 3201 bool Invalid = false); 3202 3203 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); 3204 3205 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, 3206 Decl *Parm, Stmt *Body); 3207 3208 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); 3209 3210 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 3211 MultiStmtArg Catch, Stmt *Finally); 3212 3213 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); 3214 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 3215 Scope *CurScope); 3216 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, 3217 Expr *operand); 3218 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, 3219 Expr *SynchExpr, 3220 Stmt *SynchBody); 3221 3222 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); 3223 3224 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, 3225 SourceLocation StartLoc, 3226 SourceLocation IdLoc, 3227 IdentifierInfo *Id); 3228 3229 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); 3230 3231 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, 3232 Decl *ExDecl, Stmt *HandlerBlock); 3233 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 3234 ArrayRef<Stmt *> Handlers); 3235 3236 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? 3237 SourceLocation TryLoc, Stmt *TryBlock, 3238 Stmt *Handler); 3239 StmtResult ActOnSEHExceptBlock(SourceLocation Loc, 3240 Expr *FilterExpr, 3241 Stmt *Block); 3242 void ActOnStartSEHFinallyBlock(); 3243 void ActOnAbortSEHFinallyBlock(); 3244 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block); 3245 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope); 3246 3247 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); 3248 3249 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; 3250 3251 /// \brief If it's a file scoped decl that must warn if not used, keep track 3252 /// of it. 3253 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); 3254 3255 /// DiagnoseUnusedExprResult - If the statement passed in is an expression 3256 /// whose result is unused, warn. 3257 void DiagnoseUnusedExprResult(const Stmt *S); 3258 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D); 3259 void DiagnoseUnusedDecl(const NamedDecl *ND); 3260 3261 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null 3262 /// statement as a \p Body, and it is located on the same line. 3263 /// 3264 /// This helps prevent bugs due to typos, such as: 3265 /// if (condition); 3266 /// do_stuff(); 3267 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 3268 const Stmt *Body, 3269 unsigned DiagID); 3270 3271 /// Warn if a for/while loop statement \p S, which is followed by 3272 /// \p PossibleBody, has a suspicious null statement as a body. 3273 void DiagnoseEmptyLoopBody(const Stmt *S, 3274 const Stmt *PossibleBody); 3275 3276 /// Warn if a value is moved to itself. 3277 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 3278 SourceLocation OpLoc); 3279 PushParsingDeclaration(sema::DelayedDiagnosticPool & pool)3280 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { 3281 return DelayedDiagnostics.push(pool); 3282 } 3283 void PopParsingDeclaration(ParsingDeclState state, Decl *decl); 3284 3285 typedef ProcessingContextState ParsingClassState; PushParsingClass()3286 ParsingClassState PushParsingClass() { 3287 return DelayedDiagnostics.pushUndelayed(); 3288 } PopParsingClass(ParsingClassState state)3289 void PopParsingClass(ParsingClassState state) { 3290 DelayedDiagnostics.popUndelayed(state); 3291 } 3292 3293 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); 3294 3295 enum AvailabilityDiagnostic { AD_Deprecation, AD_Unavailable, AD_Partial }; 3296 3297 void EmitAvailabilityWarning(AvailabilityDiagnostic AD, 3298 NamedDecl *D, StringRef Message, 3299 SourceLocation Loc, 3300 const ObjCInterfaceDecl *UnknownObjCClass, 3301 const ObjCPropertyDecl *ObjCProperty, 3302 bool ObjCPropertyAccess); 3303 3304 bool makeUnavailableInSystemHeader(SourceLocation loc, 3305 StringRef message); 3306 3307 //===--------------------------------------------------------------------===// 3308 // Expression Parsing Callbacks: SemaExpr.cpp. 3309 3310 bool CanUseDecl(NamedDecl *D); 3311 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 3312 const ObjCInterfaceDecl *UnknownObjCClass=nullptr, 3313 bool ObjCPropertyAccess=false); 3314 void NoteDeletedFunction(FunctionDecl *FD); 3315 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD); 3316 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, 3317 ObjCMethodDecl *Getter, 3318 SourceLocation Loc); 3319 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 3320 ArrayRef<Expr *> Args); 3321 3322 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 3323 Decl *LambdaContextDecl = nullptr, 3324 bool IsDecltype = false); 3325 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; 3326 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 3327 ReuseLambdaContextDecl_t, 3328 bool IsDecltype = false); 3329 void PopExpressionEvaluationContext(); 3330 3331 void DiscardCleanupsInEvaluationContext(); 3332 3333 ExprResult TransformToPotentiallyEvaluated(Expr *E); 3334 ExprResult HandleExprEvaluationContextForTypeof(Expr *E); 3335 3336 ExprResult ActOnConstantExpression(ExprResult Res); 3337 3338 // Functions for marking a declaration referenced. These functions also 3339 // contain the relevant logic for marking if a reference to a function or 3340 // variable is an odr-use (in the C++11 sense). There are separate variants 3341 // for expressions referring to a decl; these exist because odr-use marking 3342 // needs to be delayed for some constant variables when we build one of the 3343 // named expressions. 3344 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse); 3345 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 3346 bool OdrUse = true); 3347 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); 3348 void MarkDeclRefReferenced(DeclRefExpr *E); 3349 void MarkMemberReferenced(MemberExpr *E); 3350 3351 void UpdateMarkingForLValueToRValue(Expr *E); 3352 void CleanupVarDeclMarking(); 3353 3354 enum TryCaptureKind { 3355 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef 3356 }; 3357 3358 /// \brief Try to capture the given variable. 3359 /// 3360 /// \param Var The variable to capture. 3361 /// 3362 /// \param Loc The location at which the capture occurs. 3363 /// 3364 /// \param Kind The kind of capture, which may be implicit (for either a 3365 /// block or a lambda), or explicit by-value or by-reference (for a lambda). 3366 /// 3367 /// \param EllipsisLoc The location of the ellipsis, if one is provided in 3368 /// an explicit lambda capture. 3369 /// 3370 /// \param BuildAndDiagnose Whether we are actually supposed to add the 3371 /// captures or diagnose errors. If false, this routine merely check whether 3372 /// the capture can occur without performing the capture itself or complaining 3373 /// if the variable cannot be captured. 3374 /// 3375 /// \param CaptureType Will be set to the type of the field used to capture 3376 /// this variable in the innermost block or lambda. Only valid when the 3377 /// variable can be captured. 3378 /// 3379 /// \param DeclRefType Will be set to the type of a reference to the capture 3380 /// from within the current scope. Only valid when the variable can be 3381 /// captured. 3382 /// 3383 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index 3384 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. 3385 /// This is useful when enclosing lambdas must speculatively capture 3386 /// variables that may or may not be used in certain specializations of 3387 /// a nested generic lambda. 3388 /// 3389 /// \returns true if an error occurred (i.e., the variable cannot be 3390 /// captured) and false if the capture succeeded. 3391 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, 3392 SourceLocation EllipsisLoc, bool BuildAndDiagnose, 3393 QualType &CaptureType, 3394 QualType &DeclRefType, 3395 const unsigned *const FunctionScopeIndexToStopAt); 3396 3397 /// \brief Try to capture the given variable. 3398 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 3399 TryCaptureKind Kind = TryCapture_Implicit, 3400 SourceLocation EllipsisLoc = SourceLocation()); 3401 3402 /// \brief Checks if the variable must be captured. 3403 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc); 3404 3405 /// \brief Given a variable, determine the type that a reference to that 3406 /// variable will have in the given scope. 3407 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); 3408 3409 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); 3410 void MarkDeclarationsReferencedInExpr(Expr *E, 3411 bool SkipLocalVariables = false); 3412 3413 /// \brief Try to recover by turning the given expression into a 3414 /// call. Returns true if recovery was attempted or an error was 3415 /// emitted; this may also leave the ExprResult invalid. 3416 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, 3417 bool ForceComplain = false, 3418 bool (*IsPlausibleResult)(QualType) = nullptr); 3419 3420 /// \brief Figure out if an expression could be turned into a call. 3421 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, 3422 UnresolvedSetImpl &NonTemplateOverloads); 3423 3424 /// \brief Conditionally issue a diagnostic based on the current 3425 /// evaluation context. 3426 /// 3427 /// \param Statement If Statement is non-null, delay reporting the 3428 /// diagnostic until the function body is parsed, and then do a basic 3429 /// reachability analysis to determine if the statement is reachable. 3430 /// If it is unreachable, the diagnostic will not be emitted. 3431 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 3432 const PartialDiagnostic &PD); 3433 3434 // Primary Expressions. 3435 SourceRange getExprRange(Expr *E) const; 3436 3437 ExprResult ActOnIdExpression( 3438 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 3439 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, 3440 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr, 3441 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr); 3442 3443 void DecomposeUnqualifiedId(const UnqualifiedId &Id, 3444 TemplateArgumentListInfo &Buffer, 3445 DeclarationNameInfo &NameInfo, 3446 const TemplateArgumentListInfo *&TemplateArgs); 3447 3448 bool 3449 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 3450 std::unique_ptr<CorrectionCandidateCallback> CCC, 3451 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, 3452 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr); 3453 3454 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, 3455 IdentifierInfo *II, 3456 bool AllowBuiltinCreation=false); 3457 3458 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, 3459 SourceLocation TemplateKWLoc, 3460 const DeclarationNameInfo &NameInfo, 3461 bool isAddressOfOperand, 3462 const TemplateArgumentListInfo *TemplateArgs); 3463 3464 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, 3465 ExprValueKind VK, 3466 SourceLocation Loc, 3467 const CXXScopeSpec *SS = nullptr); 3468 ExprResult 3469 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 3470 const DeclarationNameInfo &NameInfo, 3471 const CXXScopeSpec *SS = nullptr, 3472 NamedDecl *FoundD = nullptr, 3473 const TemplateArgumentListInfo *TemplateArgs = nullptr); 3474 ExprResult 3475 BuildAnonymousStructUnionMemberReference( 3476 const CXXScopeSpec &SS, 3477 SourceLocation nameLoc, 3478 IndirectFieldDecl *indirectField, 3479 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none), 3480 Expr *baseObjectExpr = nullptr, 3481 SourceLocation opLoc = SourceLocation()); 3482 3483 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, 3484 SourceLocation TemplateKWLoc, 3485 LookupResult &R, 3486 const TemplateArgumentListInfo *TemplateArgs); 3487 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, 3488 SourceLocation TemplateKWLoc, 3489 LookupResult &R, 3490 const TemplateArgumentListInfo *TemplateArgs, 3491 bool IsDefiniteInstance); 3492 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, 3493 const LookupResult &R, 3494 bool HasTrailingLParen); 3495 3496 ExprResult BuildQualifiedDeclarationNameExpr( 3497 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 3498 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr); 3499 3500 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, 3501 SourceLocation TemplateKWLoc, 3502 const DeclarationNameInfo &NameInfo, 3503 const TemplateArgumentListInfo *TemplateArgs); 3504 3505 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3506 LookupResult &R, 3507 bool NeedsADL, 3508 bool AcceptInvalidDecl = false); 3509 ExprResult BuildDeclarationNameExpr( 3510 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3511 NamedDecl *FoundD = nullptr, 3512 const TemplateArgumentListInfo *TemplateArgs = nullptr, 3513 bool AcceptInvalidDecl = false); 3514 3515 ExprResult BuildLiteralOperatorCall(LookupResult &R, 3516 DeclarationNameInfo &SuffixInfo, 3517 ArrayRef<Expr *> Args, 3518 SourceLocation LitEndLoc, 3519 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); 3520 3521 ExprResult BuildPredefinedExpr(SourceLocation Loc, 3522 PredefinedExpr::IdentType IT); 3523 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); 3524 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); 3525 3526 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc); 3527 3528 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr); 3529 ExprResult ActOnCharacterConstant(const Token &Tok, 3530 Scope *UDLScope = nullptr); 3531 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); 3532 ExprResult ActOnParenListExpr(SourceLocation L, 3533 SourceLocation R, 3534 MultiExprArg Val); 3535 3536 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 3537 /// fragments (e.g. "foo" "bar" L"baz"). 3538 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks, 3539 Scope *UDLScope = nullptr); 3540 3541 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, 3542 SourceLocation DefaultLoc, 3543 SourceLocation RParenLoc, 3544 Expr *ControllingExpr, 3545 ArrayRef<ParsedType> ArgTypes, 3546 ArrayRef<Expr *> ArgExprs); 3547 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, 3548 SourceLocation DefaultLoc, 3549 SourceLocation RParenLoc, 3550 Expr *ControllingExpr, 3551 ArrayRef<TypeSourceInfo *> Types, 3552 ArrayRef<Expr *> Exprs); 3553 3554 // Binary/Unary Operators. 'Tok' is the token for the operator. 3555 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 3556 Expr *InputExpr); 3557 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, 3558 UnaryOperatorKind Opc, Expr *Input); 3559 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 3560 tok::TokenKind Op, Expr *Input); 3561 3562 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc); 3563 3564 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3565 SourceLocation OpLoc, 3566 UnaryExprOrTypeTrait ExprKind, 3567 SourceRange R); 3568 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3569 UnaryExprOrTypeTrait ExprKind); 3570 ExprResult 3571 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3572 UnaryExprOrTypeTrait ExprKind, 3573 bool IsType, void *TyOrEx, 3574 const SourceRange &ArgRange); 3575 3576 ExprResult CheckPlaceholderExpr(Expr *E); 3577 bool CheckVecStepExpr(Expr *E); 3578 3579 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); 3580 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, 3581 SourceRange ExprRange, 3582 UnaryExprOrTypeTrait ExprKind); 3583 ExprResult ActOnSizeofParameterPackExpr(Scope *S, 3584 SourceLocation OpLoc, 3585 IdentifierInfo &Name, 3586 SourceLocation NameLoc, 3587 SourceLocation RParenLoc); 3588 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3589 tok::TokenKind Kind, Expr *Input); 3590 3591 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, 3592 Expr *Idx, SourceLocation RLoc); 3593 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3594 Expr *Idx, SourceLocation RLoc); 3595 3596 // This struct is for use by ActOnMemberAccess to allow 3597 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after 3598 // changing the access operator from a '.' to a '->' (to see if that is the 3599 // change needed to fix an error about an unknown member, e.g. when the class 3600 // defines a custom operator->). 3601 struct ActOnMemberAccessExtraArgs { 3602 Scope *S; 3603 UnqualifiedId &Id; 3604 Decl *ObjCImpDecl; 3605 }; 3606 3607 ExprResult BuildMemberReferenceExpr( 3608 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, 3609 CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 3610 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, 3611 const TemplateArgumentListInfo *TemplateArgs, 3612 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); 3613 3614 ExprResult 3615 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, 3616 bool IsArrow, const CXXScopeSpec &SS, 3617 SourceLocation TemplateKWLoc, 3618 NamedDecl *FirstQualifierInScope, LookupResult &R, 3619 const TemplateArgumentListInfo *TemplateArgs, 3620 bool SuppressQualifierCheck = false, 3621 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); 3622 3623 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); 3624 3625 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, 3626 const CXXScopeSpec &SS, 3627 const LookupResult &R); 3628 3629 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, 3630 bool IsArrow, SourceLocation OpLoc, 3631 const CXXScopeSpec &SS, 3632 SourceLocation TemplateKWLoc, 3633 NamedDecl *FirstQualifierInScope, 3634 const DeclarationNameInfo &NameInfo, 3635 const TemplateArgumentListInfo *TemplateArgs); 3636 3637 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, 3638 SourceLocation OpLoc, 3639 tok::TokenKind OpKind, 3640 CXXScopeSpec &SS, 3641 SourceLocation TemplateKWLoc, 3642 UnqualifiedId &Member, 3643 Decl *ObjCImpDecl); 3644 3645 void ActOnDefaultCtorInitializers(Decl *CDtorDecl); 3646 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 3647 FunctionDecl *FDecl, 3648 const FunctionProtoType *Proto, 3649 ArrayRef<Expr *> Args, 3650 SourceLocation RParenLoc, 3651 bool ExecConfig = false); 3652 void CheckStaticArrayArgument(SourceLocation CallLoc, 3653 ParmVarDecl *Param, 3654 const Expr *ArgExpr); 3655 3656 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 3657 /// This provides the location of the left/right parens and a list of comma 3658 /// locations. 3659 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 3660 MultiExprArg ArgExprs, SourceLocation RParenLoc, 3661 Expr *ExecConfig = nullptr, 3662 bool IsExecConfig = false); 3663 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 3664 SourceLocation LParenLoc, 3665 ArrayRef<Expr *> Arg, 3666 SourceLocation RParenLoc, 3667 Expr *Config = nullptr, 3668 bool IsExecConfig = false); 3669 3670 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 3671 MultiExprArg ExecConfig, 3672 SourceLocation GGGLoc); 3673 3674 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 3675 Declarator &D, ParsedType &Ty, 3676 SourceLocation RParenLoc, Expr *CastExpr); 3677 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, 3678 TypeSourceInfo *Ty, 3679 SourceLocation RParenLoc, 3680 Expr *Op); 3681 CastKind PrepareScalarCast(ExprResult &src, QualType destType); 3682 3683 /// \brief Build an altivec or OpenCL literal. 3684 ExprResult BuildVectorLiteral(SourceLocation LParenLoc, 3685 SourceLocation RParenLoc, Expr *E, 3686 TypeSourceInfo *TInfo); 3687 3688 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); 3689 3690 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, 3691 ParsedType Ty, 3692 SourceLocation RParenLoc, 3693 Expr *InitExpr); 3694 3695 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, 3696 TypeSourceInfo *TInfo, 3697 SourceLocation RParenLoc, 3698 Expr *LiteralExpr); 3699 3700 ExprResult ActOnInitList(SourceLocation LBraceLoc, 3701 MultiExprArg InitArgList, 3702 SourceLocation RBraceLoc); 3703 3704 ExprResult ActOnDesignatedInitializer(Designation &Desig, 3705 SourceLocation Loc, 3706 bool GNUSyntax, 3707 ExprResult Init); 3708 3709 private: 3710 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind); 3711 3712 public: 3713 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, 3714 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); 3715 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, 3716 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); 3717 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, 3718 Expr *LHSExpr, Expr *RHSExpr); 3719 3720 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 3721 /// in the case of a the GNU conditional expr extension. 3722 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, 3723 SourceLocation ColonLoc, 3724 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); 3725 3726 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 3727 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 3728 LabelDecl *TheDecl); 3729 3730 void ActOnStartStmtExpr(); 3731 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 3732 SourceLocation RPLoc); // "({..})" 3733 void ActOnStmtExprError(); 3734 3735 // __builtin_offsetof(type, identifier(.identifier|[expr])*) 3736 struct OffsetOfComponent { 3737 SourceLocation LocStart, LocEnd; 3738 bool isBrackets; // true if [expr], false if .ident 3739 union { 3740 IdentifierInfo *IdentInfo; 3741 Expr *E; 3742 } U; 3743 }; 3744 3745 /// __builtin_offsetof(type, a.b[123][456].c) 3746 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 3747 TypeSourceInfo *TInfo, 3748 OffsetOfComponent *CompPtr, 3749 unsigned NumComponents, 3750 SourceLocation RParenLoc); 3751 ExprResult ActOnBuiltinOffsetOf(Scope *S, 3752 SourceLocation BuiltinLoc, 3753 SourceLocation TypeLoc, 3754 ParsedType ParsedArgTy, 3755 OffsetOfComponent *CompPtr, 3756 unsigned NumComponents, 3757 SourceLocation RParenLoc); 3758 3759 // __builtin_choose_expr(constExpr, expr1, expr2) 3760 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, 3761 Expr *CondExpr, Expr *LHSExpr, 3762 Expr *RHSExpr, SourceLocation RPLoc); 3763 3764 // __builtin_va_arg(expr, type) 3765 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 3766 SourceLocation RPLoc); 3767 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, 3768 TypeSourceInfo *TInfo, SourceLocation RPLoc); 3769 3770 // __null 3771 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); 3772 3773 bool CheckCaseExpression(Expr *E); 3774 3775 /// \brief Describes the result of an "if-exists" condition check. 3776 enum IfExistsResult { 3777 /// \brief The symbol exists. 3778 IER_Exists, 3779 3780 /// \brief The symbol does not exist. 3781 IER_DoesNotExist, 3782 3783 /// \brief The name is a dependent name, so the results will differ 3784 /// from one instantiation to the next. 3785 IER_Dependent, 3786 3787 /// \brief An error occurred. 3788 IER_Error 3789 }; 3790 3791 IfExistsResult 3792 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, 3793 const DeclarationNameInfo &TargetNameInfo); 3794 3795 IfExistsResult 3796 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, 3797 bool IsIfExists, CXXScopeSpec &SS, 3798 UnqualifiedId &Name); 3799 3800 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, 3801 bool IsIfExists, 3802 NestedNameSpecifierLoc QualifierLoc, 3803 DeclarationNameInfo NameInfo, 3804 Stmt *Nested); 3805 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, 3806 bool IsIfExists, 3807 CXXScopeSpec &SS, UnqualifiedId &Name, 3808 Stmt *Nested); 3809 3810 //===------------------------- "Block" Extension ------------------------===// 3811 3812 /// ActOnBlockStart - This callback is invoked when a block literal is 3813 /// started. 3814 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); 3815 3816 /// ActOnBlockArguments - This callback allows processing of block arguments. 3817 /// If there are no arguments, this is still invoked. 3818 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 3819 Scope *CurScope); 3820 3821 /// ActOnBlockError - If there is an error parsing a block, this callback 3822 /// is invoked to pop the information about the block from the action impl. 3823 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); 3824 3825 /// ActOnBlockStmtExpr - This is called when the body of a block statement 3826 /// literal was successfully completed. ^(int x){...} 3827 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, 3828 Scope *CurScope); 3829 3830 //===---------------------------- Clang Extensions ----------------------===// 3831 3832 /// __builtin_convertvector(...) 3833 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 3834 SourceLocation BuiltinLoc, 3835 SourceLocation RParenLoc); 3836 3837 //===---------------------------- OpenCL Features -----------------------===// 3838 3839 /// __builtin_astype(...) 3840 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 3841 SourceLocation BuiltinLoc, 3842 SourceLocation RParenLoc); 3843 3844 //===---------------------------- C++ Features --------------------------===// 3845 3846 // Act on C++ namespaces 3847 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, 3848 SourceLocation NamespaceLoc, 3849 SourceLocation IdentLoc, 3850 IdentifierInfo *Ident, 3851 SourceLocation LBrace, 3852 AttributeList *AttrList); 3853 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); 3854 3855 NamespaceDecl *getStdNamespace() const; 3856 NamespaceDecl *getOrCreateStdNamespace(); 3857 3858 CXXRecordDecl *getStdBadAlloc() const; 3859 3860 /// \brief Tests whether Ty is an instance of std::initializer_list and, if 3861 /// it is and Element is not NULL, assigns the element type to Element. 3862 bool isStdInitializerList(QualType Ty, QualType *Element); 3863 3864 /// \brief Looks for the std::initializer_list template and instantiates it 3865 /// with Element, or emits an error if it's not found. 3866 /// 3867 /// \returns The instantiated template, or null on error. 3868 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); 3869 3870 /// \brief Determine whether Ctor is an initializer-list constructor, as 3871 /// defined in [dcl.init.list]p2. 3872 bool isInitListConstructor(const CXXConstructorDecl *Ctor); 3873 3874 Decl *ActOnUsingDirective(Scope *CurScope, 3875 SourceLocation UsingLoc, 3876 SourceLocation NamespcLoc, 3877 CXXScopeSpec &SS, 3878 SourceLocation IdentLoc, 3879 IdentifierInfo *NamespcName, 3880 AttributeList *AttrList); 3881 3882 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); 3883 3884 Decl *ActOnNamespaceAliasDef(Scope *CurScope, 3885 SourceLocation NamespaceLoc, 3886 SourceLocation AliasLoc, 3887 IdentifierInfo *Alias, 3888 CXXScopeSpec &SS, 3889 SourceLocation IdentLoc, 3890 IdentifierInfo *Ident); 3891 3892 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); 3893 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, 3894 const LookupResult &PreviousDecls, 3895 UsingShadowDecl *&PrevShadow); 3896 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD, 3897 NamedDecl *Target, 3898 UsingShadowDecl *PrevDecl); 3899 3900 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 3901 bool HasTypenameKeyword, 3902 const CXXScopeSpec &SS, 3903 SourceLocation NameLoc, 3904 const LookupResult &Previous); 3905 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, 3906 const CXXScopeSpec &SS, 3907 const DeclarationNameInfo &NameInfo, 3908 SourceLocation NameLoc); 3909 3910 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 3911 SourceLocation UsingLoc, 3912 CXXScopeSpec &SS, 3913 DeclarationNameInfo NameInfo, 3914 AttributeList *AttrList, 3915 bool IsInstantiation, 3916 bool HasTypenameKeyword, 3917 SourceLocation TypenameLoc); 3918 3919 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); 3920 3921 Decl *ActOnUsingDeclaration(Scope *CurScope, 3922 AccessSpecifier AS, 3923 bool HasUsingKeyword, 3924 SourceLocation UsingLoc, 3925 CXXScopeSpec &SS, 3926 UnqualifiedId &Name, 3927 AttributeList *AttrList, 3928 bool HasTypenameKeyword, 3929 SourceLocation TypenameLoc); 3930 Decl *ActOnAliasDeclaration(Scope *CurScope, 3931 AccessSpecifier AS, 3932 MultiTemplateParamsArg TemplateParams, 3933 SourceLocation UsingLoc, 3934 UnqualifiedId &Name, 3935 AttributeList *AttrList, 3936 TypeResult Type, 3937 Decl *DeclFromDeclSpec); 3938 3939 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 3940 /// including handling of its default argument expressions. 3941 /// 3942 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind 3943 ExprResult 3944 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 3945 CXXConstructorDecl *Constructor, MultiExprArg Exprs, 3946 bool HadMultipleCandidates, bool IsListInitialization, 3947 bool IsStdInitListInitialization, 3948 bool RequiresZeroInit, unsigned ConstructKind, 3949 SourceRange ParenRange); 3950 3951 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if 3952 // the constructor can be elidable? 3953 ExprResult 3954 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 3955 CXXConstructorDecl *Constructor, bool Elidable, 3956 MultiExprArg Exprs, bool HadMultipleCandidates, 3957 bool IsListInitialization, 3958 bool IsStdInitListInitialization, bool RequiresZeroInit, 3959 unsigned ConstructKind, SourceRange ParenRange); 3960 3961 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field); 3962 3963 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating 3964 /// the default expr if needed. 3965 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3966 FunctionDecl *FD, 3967 ParmVarDecl *Param); 3968 3969 /// FinalizeVarWithDestructor - Prepare for calling destructor on the 3970 /// constructed variable. 3971 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); 3972 3973 /// \brief Helper class that collects exception specifications for 3974 /// implicitly-declared special member functions. 3975 class ImplicitExceptionSpecification { 3976 // Pointer to allow copying 3977 Sema *Self; 3978 // We order exception specifications thus: 3979 // noexcept is the most restrictive, but is only used in C++11. 3980 // throw() comes next. 3981 // Then a throw(collected exceptions) 3982 // Finally no specification, which is expressed as noexcept(false). 3983 // throw(...) is used instead if any called function uses it. 3984 ExceptionSpecificationType ComputedEST; 3985 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; 3986 SmallVector<QualType, 4> Exceptions; 3987 ClearExceptions()3988 void ClearExceptions() { 3989 ExceptionsSeen.clear(); 3990 Exceptions.clear(); 3991 } 3992 3993 public: ImplicitExceptionSpecification(Sema & Self)3994 explicit ImplicitExceptionSpecification(Sema &Self) 3995 : Self(&Self), ComputedEST(EST_BasicNoexcept) { 3996 if (!Self.getLangOpts().CPlusPlus11) 3997 ComputedEST = EST_DynamicNone; 3998 } 3999 4000 /// \brief Get the computed exception specification type. getExceptionSpecType()4001 ExceptionSpecificationType getExceptionSpecType() const { 4002 assert(ComputedEST != EST_ComputedNoexcept && 4003 "noexcept(expr) should not be a possible result"); 4004 return ComputedEST; 4005 } 4006 4007 /// \brief The number of exceptions in the exception specification. size()4008 unsigned size() const { return Exceptions.size(); } 4009 4010 /// \brief The set of exceptions in the exception specification. data()4011 const QualType *data() const { return Exceptions.data(); } 4012 4013 /// \brief Integrate another called method into the collected data. 4014 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); 4015 4016 /// \brief Integrate an invoked expression into the collected data. 4017 void CalledExpr(Expr *E); 4018 4019 /// \brief Overwrite an EPI's exception specification with this 4020 /// computed exception specification. getExceptionSpec()4021 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const { 4022 FunctionProtoType::ExceptionSpecInfo ESI; 4023 ESI.Type = getExceptionSpecType(); 4024 if (ESI.Type == EST_Dynamic) { 4025 ESI.Exceptions = Exceptions; 4026 } else if (ESI.Type == EST_None) { 4027 /// C++11 [except.spec]p14: 4028 /// The exception-specification is noexcept(false) if the set of 4029 /// potential exceptions of the special member function contains "any" 4030 ESI.Type = EST_ComputedNoexcept; 4031 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(), 4032 tok::kw_false).get(); 4033 } 4034 return ESI; 4035 } 4036 }; 4037 4038 /// \brief Determine what sort of exception specification a defaulted 4039 /// copy constructor of a class will have. 4040 ImplicitExceptionSpecification 4041 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 4042 CXXMethodDecl *MD); 4043 4044 /// \brief Determine what sort of exception specification a defaulted 4045 /// default constructor of a class will have, and whether the parameter 4046 /// will be const. 4047 ImplicitExceptionSpecification 4048 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD); 4049 4050 /// \brief Determine what sort of exception specification a defautled 4051 /// copy assignment operator of a class will have, and whether the 4052 /// parameter will be const. 4053 ImplicitExceptionSpecification 4054 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD); 4055 4056 /// \brief Determine what sort of exception specification a defaulted move 4057 /// constructor of a class will have. 4058 ImplicitExceptionSpecification 4059 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD); 4060 4061 /// \brief Determine what sort of exception specification a defaulted move 4062 /// assignment operator of a class will have. 4063 ImplicitExceptionSpecification 4064 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD); 4065 4066 /// \brief Determine what sort of exception specification a defaulted 4067 /// destructor of a class will have. 4068 ImplicitExceptionSpecification 4069 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD); 4070 4071 /// \brief Determine what sort of exception specification an inheriting 4072 /// constructor of a class will have. 4073 ImplicitExceptionSpecification 4074 ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD); 4075 4076 /// \brief Evaluate the implicit exception specification for a defaulted 4077 /// special member function. 4078 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD); 4079 4080 /// \brief Check the given exception-specification and update the 4081 /// exception specification information with the results. 4082 void checkExceptionSpecification(bool IsTopLevel, 4083 ExceptionSpecificationType EST, 4084 ArrayRef<ParsedType> DynamicExceptions, 4085 ArrayRef<SourceRange> DynamicExceptionRanges, 4086 Expr *NoexceptExpr, 4087 SmallVectorImpl<QualType> &Exceptions, 4088 FunctionProtoType::ExceptionSpecInfo &ESI); 4089 4090 /// \brief Determine if we're in a case where we need to (incorrectly) eagerly 4091 /// parse an exception specification to work around a libstdc++ bug. 4092 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D); 4093 4094 /// \brief Add an exception-specification to the given member function 4095 /// (or member function template). The exception-specification was parsed 4096 /// after the method itself was declared. 4097 void actOnDelayedExceptionSpecification(Decl *Method, 4098 ExceptionSpecificationType EST, 4099 SourceRange SpecificationRange, 4100 ArrayRef<ParsedType> DynamicExceptions, 4101 ArrayRef<SourceRange> DynamicExceptionRanges, 4102 Expr *NoexceptExpr); 4103 4104 /// \brief Determine if a special member function should have a deleted 4105 /// definition when it is defaulted. 4106 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 4107 bool Diagnose = false); 4108 4109 /// \brief Declare the implicit default constructor for the given class. 4110 /// 4111 /// \param ClassDecl The class declaration into which the implicit 4112 /// default constructor will be added. 4113 /// 4114 /// \returns The implicitly-declared default constructor. 4115 CXXConstructorDecl *DeclareImplicitDefaultConstructor( 4116 CXXRecordDecl *ClassDecl); 4117 4118 /// DefineImplicitDefaultConstructor - Checks for feasibility of 4119 /// defining this constructor as the default constructor. 4120 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 4121 CXXConstructorDecl *Constructor); 4122 4123 /// \brief Declare the implicit destructor for the given class. 4124 /// 4125 /// \param ClassDecl The class declaration into which the implicit 4126 /// destructor will be added. 4127 /// 4128 /// \returns The implicitly-declared destructor. 4129 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); 4130 4131 /// DefineImplicitDestructor - Checks for feasibility of 4132 /// defining this destructor as the default destructor. 4133 void DefineImplicitDestructor(SourceLocation CurrentLocation, 4134 CXXDestructorDecl *Destructor); 4135 4136 /// \brief Build an exception spec for destructors that don't have one. 4137 /// 4138 /// C++11 says that user-defined destructors with no exception spec get one 4139 /// that looks as if the destructor was implicitly declared. 4140 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 4141 CXXDestructorDecl *Destructor); 4142 4143 /// \brief Declare all inheriting constructors for the given class. 4144 /// 4145 /// \param ClassDecl The class declaration into which the inheriting 4146 /// constructors will be added. 4147 void DeclareInheritingConstructors(CXXRecordDecl *ClassDecl); 4148 4149 /// \brief Define the specified inheriting constructor. 4150 void DefineInheritingConstructor(SourceLocation UseLoc, 4151 CXXConstructorDecl *Constructor); 4152 4153 /// \brief Declare the implicit copy constructor for the given class. 4154 /// 4155 /// \param ClassDecl The class declaration into which the implicit 4156 /// copy constructor will be added. 4157 /// 4158 /// \returns The implicitly-declared copy constructor. 4159 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); 4160 4161 /// DefineImplicitCopyConstructor - Checks for feasibility of 4162 /// defining this constructor as the copy constructor. 4163 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 4164 CXXConstructorDecl *Constructor); 4165 4166 /// \brief Declare the implicit move constructor for the given class. 4167 /// 4168 /// \param ClassDecl The Class declaration into which the implicit 4169 /// move constructor will be added. 4170 /// 4171 /// \returns The implicitly-declared move constructor, or NULL if it wasn't 4172 /// declared. 4173 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); 4174 4175 /// DefineImplicitMoveConstructor - Checks for feasibility of 4176 /// defining this constructor as the move constructor. 4177 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 4178 CXXConstructorDecl *Constructor); 4179 4180 /// \brief Declare the implicit copy assignment operator for the given class. 4181 /// 4182 /// \param ClassDecl The class declaration into which the implicit 4183 /// copy assignment operator will be added. 4184 /// 4185 /// \returns The implicitly-declared copy assignment operator. 4186 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); 4187 4188 /// \brief Defines an implicitly-declared copy assignment operator. 4189 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 4190 CXXMethodDecl *MethodDecl); 4191 4192 /// \brief Declare the implicit move assignment operator for the given class. 4193 /// 4194 /// \param ClassDecl The Class declaration into which the implicit 4195 /// move assignment operator will be added. 4196 /// 4197 /// \returns The implicitly-declared move assignment operator, or NULL if it 4198 /// wasn't declared. 4199 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); 4200 4201 /// \brief Defines an implicitly-declared move assignment operator. 4202 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 4203 CXXMethodDecl *MethodDecl); 4204 4205 /// \brief Force the declaration of any implicitly-declared members of this 4206 /// class. 4207 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); 4208 4209 /// \brief Determine whether the given function is an implicitly-deleted 4210 /// special member function. 4211 bool isImplicitlyDeleted(FunctionDecl *FD); 4212 4213 /// \brief Check whether 'this' shows up in the type of a static member 4214 /// function after the (naturally empty) cv-qualifier-seq would be. 4215 /// 4216 /// \returns true if an error occurred. 4217 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); 4218 4219 /// \brief Whether this' shows up in the exception specification of a static 4220 /// member function. 4221 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); 4222 4223 /// \brief Check whether 'this' shows up in the attributes of the given 4224 /// static member function. 4225 /// 4226 /// \returns true if an error occurred. 4227 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); 4228 4229 /// MaybeBindToTemporary - If the passed in expression has a record type with 4230 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise 4231 /// it simply returns the passed in expression. 4232 ExprResult MaybeBindToTemporary(Expr *E); 4233 4234 bool CompleteConstructorCall(CXXConstructorDecl *Constructor, 4235 MultiExprArg ArgsPtr, 4236 SourceLocation Loc, 4237 SmallVectorImpl<Expr*> &ConvertedArgs, 4238 bool AllowExplicit = false, 4239 bool IsListInitialization = false); 4240 4241 ParsedType getInheritingConstructorName(CXXScopeSpec &SS, 4242 SourceLocation NameLoc, 4243 IdentifierInfo &Name); 4244 4245 ParsedType getDestructorName(SourceLocation TildeLoc, 4246 IdentifierInfo &II, SourceLocation NameLoc, 4247 Scope *S, CXXScopeSpec &SS, 4248 ParsedType ObjectType, 4249 bool EnteringContext); 4250 4251 ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType); 4252 4253 // Checks that reinterpret casts don't have undefined behavior. 4254 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, 4255 bool IsDereference, SourceRange Range); 4256 4257 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. 4258 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, 4259 tok::TokenKind Kind, 4260 SourceLocation LAngleBracketLoc, 4261 Declarator &D, 4262 SourceLocation RAngleBracketLoc, 4263 SourceLocation LParenLoc, 4264 Expr *E, 4265 SourceLocation RParenLoc); 4266 4267 ExprResult BuildCXXNamedCast(SourceLocation OpLoc, 4268 tok::TokenKind Kind, 4269 TypeSourceInfo *Ty, 4270 Expr *E, 4271 SourceRange AngleBrackets, 4272 SourceRange Parens); 4273 4274 ExprResult BuildCXXTypeId(QualType TypeInfoType, 4275 SourceLocation TypeidLoc, 4276 TypeSourceInfo *Operand, 4277 SourceLocation RParenLoc); 4278 ExprResult BuildCXXTypeId(QualType TypeInfoType, 4279 SourceLocation TypeidLoc, 4280 Expr *Operand, 4281 SourceLocation RParenLoc); 4282 4283 /// ActOnCXXTypeid - Parse typeid( something ). 4284 ExprResult ActOnCXXTypeid(SourceLocation OpLoc, 4285 SourceLocation LParenLoc, bool isType, 4286 void *TyOrExpr, 4287 SourceLocation RParenLoc); 4288 4289 ExprResult BuildCXXUuidof(QualType TypeInfoType, 4290 SourceLocation TypeidLoc, 4291 TypeSourceInfo *Operand, 4292 SourceLocation RParenLoc); 4293 ExprResult BuildCXXUuidof(QualType TypeInfoType, 4294 SourceLocation TypeidLoc, 4295 Expr *Operand, 4296 SourceLocation RParenLoc); 4297 4298 /// ActOnCXXUuidof - Parse __uuidof( something ). 4299 ExprResult ActOnCXXUuidof(SourceLocation OpLoc, 4300 SourceLocation LParenLoc, bool isType, 4301 void *TyOrExpr, 4302 SourceLocation RParenLoc); 4303 4304 /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ). 4305 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS, 4306 tok::TokenKind Operator, 4307 SourceLocation EllipsisLoc, Expr *RHS, 4308 SourceLocation RParenLoc); 4309 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS, 4310 BinaryOperatorKind Operator, 4311 SourceLocation EllipsisLoc, Expr *RHS, 4312 SourceLocation RParenLoc); 4313 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, 4314 BinaryOperatorKind Operator); 4315 4316 //// ActOnCXXThis - Parse 'this' pointer. 4317 ExprResult ActOnCXXThis(SourceLocation loc); 4318 4319 /// \brief Try to retrieve the type of the 'this' pointer. 4320 /// 4321 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. 4322 QualType getCurrentThisType(); 4323 4324 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the 4325 /// current context not being a non-static member function. In such cases, 4326 /// this provides the type used for 'this'. 4327 QualType CXXThisTypeOverride; 4328 4329 /// \brief RAII object used to temporarily allow the C++ 'this' expression 4330 /// to be used, with the given qualifiers on the current class type. 4331 class CXXThisScopeRAII { 4332 Sema &S; 4333 QualType OldCXXThisTypeOverride; 4334 bool Enabled; 4335 4336 public: 4337 /// \brief Introduce a new scope where 'this' may be allowed (when enabled), 4338 /// using the given declaration (which is either a class template or a 4339 /// class) along with the given qualifiers. 4340 /// along with the qualifiers placed on '*this'. 4341 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals, 4342 bool Enabled = true); 4343 4344 ~CXXThisScopeRAII(); 4345 }; 4346 4347 /// \brief Make sure the value of 'this' is actually available in the current 4348 /// context, if it is a potentially evaluated context. 4349 /// 4350 /// \param Loc The location at which the capture of 'this' occurs. 4351 /// 4352 /// \param Explicit Whether 'this' is explicitly captured in a lambda 4353 /// capture list. 4354 /// 4355 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index 4356 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. 4357 /// This is useful when enclosing lambdas must speculatively capture 4358 /// 'this' that may or may not be used in certain specializations of 4359 /// a nested generic lambda (depending on whether the name resolves to 4360 /// a non-static member function or a static function). 4361 /// \return returns 'true' if failed, 'false' if success. 4362 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false, 4363 bool BuildAndDiagnose = true, 4364 const unsigned *const FunctionScopeIndexToStopAt = nullptr); 4365 4366 /// \brief Determine whether the given type is the type of *this that is used 4367 /// outside of the body of a member function for a type that is currently 4368 /// being defined. 4369 bool isThisOutsideMemberFunctionBody(QualType BaseType); 4370 4371 /// ActOnCXXBoolLiteral - Parse {true,false} literals. 4372 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 4373 4374 4375 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 4376 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 4377 4378 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 4379 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); 4380 4381 //// ActOnCXXThrow - Parse throw expressions. 4382 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); 4383 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, 4384 bool IsThrownVarInScope); 4385 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E); 4386 4387 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 4388 /// Can be interpreted either as function-style casting ("int(x)") 4389 /// or class type construction ("ClassType(x,y,z)") 4390 /// or creation of a value-initialized type ("int()"). 4391 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, 4392 SourceLocation LParenLoc, 4393 MultiExprArg Exprs, 4394 SourceLocation RParenLoc); 4395 4396 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, 4397 SourceLocation LParenLoc, 4398 MultiExprArg Exprs, 4399 SourceLocation RParenLoc); 4400 4401 /// ActOnCXXNew - Parsed a C++ 'new' expression. 4402 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 4403 SourceLocation PlacementLParen, 4404 MultiExprArg PlacementArgs, 4405 SourceLocation PlacementRParen, 4406 SourceRange TypeIdParens, Declarator &D, 4407 Expr *Initializer); 4408 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, 4409 SourceLocation PlacementLParen, 4410 MultiExprArg PlacementArgs, 4411 SourceLocation PlacementRParen, 4412 SourceRange TypeIdParens, 4413 QualType AllocType, 4414 TypeSourceInfo *AllocTypeInfo, 4415 Expr *ArraySize, 4416 SourceRange DirectInitRange, 4417 Expr *Initializer, 4418 bool TypeMayContainAuto = true); 4419 4420 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, 4421 SourceRange R); 4422 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 4423 bool UseGlobal, QualType AllocType, bool IsArray, 4424 MultiExprArg PlaceArgs, 4425 FunctionDecl *&OperatorNew, 4426 FunctionDecl *&OperatorDelete); 4427 bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, 4428 DeclarationName Name, MultiExprArg Args, 4429 DeclContext *Ctx, 4430 bool AllowMissing, FunctionDecl *&Operator, 4431 bool Diagnose = true); 4432 void DeclareGlobalNewDelete(); 4433 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, 4434 QualType Param1, 4435 QualType Param2 = QualType(), 4436 bool addRestrictAttr = false); 4437 4438 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 4439 DeclarationName Name, FunctionDecl* &Operator, 4440 bool Diagnose = true); 4441 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc, 4442 bool CanProvideSize, 4443 DeclarationName Name); 4444 4445 /// ActOnCXXDelete - Parsed a C++ 'delete' expression 4446 ExprResult ActOnCXXDelete(SourceLocation StartLoc, 4447 bool UseGlobal, bool ArrayForm, 4448 Expr *Operand); 4449 4450 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); 4451 ExprResult CheckConditionVariable(VarDecl *ConditionVar, 4452 SourceLocation StmtLoc, 4453 bool ConvertToBoolean); 4454 4455 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, 4456 Expr *Operand, SourceLocation RParen); 4457 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 4458 SourceLocation RParen); 4459 4460 /// \brief Parsed one of the type trait support pseudo-functions. 4461 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 4462 ArrayRef<ParsedType> Args, 4463 SourceLocation RParenLoc); 4464 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 4465 ArrayRef<TypeSourceInfo *> Args, 4466 SourceLocation RParenLoc); 4467 4468 /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support 4469 /// pseudo-functions. 4470 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, 4471 SourceLocation KWLoc, 4472 ParsedType LhsTy, 4473 Expr *DimExpr, 4474 SourceLocation RParen); 4475 4476 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, 4477 SourceLocation KWLoc, 4478 TypeSourceInfo *TSInfo, 4479 Expr *DimExpr, 4480 SourceLocation RParen); 4481 4482 /// ActOnExpressionTrait - Parsed one of the unary type trait support 4483 /// pseudo-functions. 4484 ExprResult ActOnExpressionTrait(ExpressionTrait OET, 4485 SourceLocation KWLoc, 4486 Expr *Queried, 4487 SourceLocation RParen); 4488 4489 ExprResult BuildExpressionTrait(ExpressionTrait OET, 4490 SourceLocation KWLoc, 4491 Expr *Queried, 4492 SourceLocation RParen); 4493 4494 ExprResult ActOnStartCXXMemberReference(Scope *S, 4495 Expr *Base, 4496 SourceLocation OpLoc, 4497 tok::TokenKind OpKind, 4498 ParsedType &ObjectType, 4499 bool &MayBePseudoDestructor); 4500 4501 ExprResult BuildPseudoDestructorExpr(Expr *Base, 4502 SourceLocation OpLoc, 4503 tok::TokenKind OpKind, 4504 const CXXScopeSpec &SS, 4505 TypeSourceInfo *ScopeType, 4506 SourceLocation CCLoc, 4507 SourceLocation TildeLoc, 4508 PseudoDestructorTypeStorage DestroyedType); 4509 4510 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 4511 SourceLocation OpLoc, 4512 tok::TokenKind OpKind, 4513 CXXScopeSpec &SS, 4514 UnqualifiedId &FirstTypeName, 4515 SourceLocation CCLoc, 4516 SourceLocation TildeLoc, 4517 UnqualifiedId &SecondTypeName); 4518 4519 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 4520 SourceLocation OpLoc, 4521 tok::TokenKind OpKind, 4522 SourceLocation TildeLoc, 4523 const DeclSpec& DS); 4524 4525 /// MaybeCreateExprWithCleanups - If the current full-expression 4526 /// requires any cleanups, surround it with a ExprWithCleanups node. 4527 /// Otherwise, just returns the passed-in expression. 4528 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); 4529 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); 4530 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); 4531 ActOnFinishFullExpr(Expr * Expr)4532 ExprResult ActOnFinishFullExpr(Expr *Expr) { 4533 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc() 4534 : SourceLocation()); 4535 } 4536 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, 4537 bool DiscardedValue = false, 4538 bool IsConstexpr = false, 4539 bool IsLambdaInitCaptureInitializer = false); 4540 StmtResult ActOnFinishFullStmt(Stmt *Stmt); 4541 4542 // Marks SS invalid if it represents an incomplete type. 4543 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); 4544 4545 DeclContext *computeDeclContext(QualType T); 4546 DeclContext *computeDeclContext(const CXXScopeSpec &SS, 4547 bool EnteringContext = false); 4548 bool isDependentScopeSpecifier(const CXXScopeSpec &SS); 4549 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); 4550 4551 /// \brief The parser has parsed a global nested-name-specifier '::'. 4552 /// 4553 /// \param CCLoc The location of the '::'. 4554 /// 4555 /// \param SS The nested-name-specifier, which will be updated in-place 4556 /// to reflect the parsed nested-name-specifier. 4557 /// 4558 /// \returns true if an error occurred, false otherwise. 4559 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS); 4560 4561 /// \brief The parser has parsed a '__super' nested-name-specifier. 4562 /// 4563 /// \param SuperLoc The location of the '__super' keyword. 4564 /// 4565 /// \param ColonColonLoc The location of the '::'. 4566 /// 4567 /// \param SS The nested-name-specifier, which will be updated in-place 4568 /// to reflect the parsed nested-name-specifier. 4569 /// 4570 /// \returns true if an error occurred, false otherwise. 4571 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, 4572 SourceLocation ColonColonLoc, CXXScopeSpec &SS); 4573 4574 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, 4575 bool *CanCorrect = nullptr); 4576 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); 4577 4578 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, 4579 SourceLocation IdLoc, 4580 IdentifierInfo &II, 4581 ParsedType ObjectType); 4582 4583 bool BuildCXXNestedNameSpecifier(Scope *S, 4584 IdentifierInfo &Identifier, 4585 SourceLocation IdentifierLoc, 4586 SourceLocation CCLoc, 4587 QualType ObjectType, 4588 bool EnteringContext, 4589 CXXScopeSpec &SS, 4590 NamedDecl *ScopeLookupResult, 4591 bool ErrorRecoveryLookup, 4592 bool *IsCorrectedToColon = nullptr); 4593 4594 /// \brief The parser has parsed a nested-name-specifier 'identifier::'. 4595 /// 4596 /// \param S The scope in which this nested-name-specifier occurs. 4597 /// 4598 /// \param Identifier The identifier preceding the '::'. 4599 /// 4600 /// \param IdentifierLoc The location of the identifier. 4601 /// 4602 /// \param CCLoc The location of the '::'. 4603 /// 4604 /// \param ObjectType The type of the object, if we're parsing 4605 /// nested-name-specifier in a member access expression. 4606 /// 4607 /// \param EnteringContext Whether we're entering the context nominated by 4608 /// this nested-name-specifier. 4609 /// 4610 /// \param SS The nested-name-specifier, which is both an input 4611 /// parameter (the nested-name-specifier before this type) and an 4612 /// output parameter (containing the full nested-name-specifier, 4613 /// including this new type). 4614 /// 4615 /// \param ErrorRecoveryLookup If true, then this method is called to improve 4616 /// error recovery. In this case do not emit error message. 4617 /// 4618 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':' 4619 /// are allowed. The bool value pointed by this parameter is set to 'true' 4620 /// if the identifier is treated as if it was followed by ':', not '::'. 4621 /// 4622 /// \returns true if an error occurred, false otherwise. 4623 bool ActOnCXXNestedNameSpecifier(Scope *S, 4624 IdentifierInfo &Identifier, 4625 SourceLocation IdentifierLoc, 4626 SourceLocation CCLoc, 4627 ParsedType ObjectType, 4628 bool EnteringContext, 4629 CXXScopeSpec &SS, 4630 bool ErrorRecoveryLookup = false, 4631 bool *IsCorrectedToColon = nullptr); 4632 4633 ExprResult ActOnDecltypeExpression(Expr *E); 4634 4635 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, 4636 const DeclSpec &DS, 4637 SourceLocation ColonColonLoc); 4638 4639 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, 4640 IdentifierInfo &Identifier, 4641 SourceLocation IdentifierLoc, 4642 SourceLocation ColonLoc, 4643 ParsedType ObjectType, 4644 bool EnteringContext); 4645 4646 /// \brief The parser has parsed a nested-name-specifier 4647 /// 'template[opt] template-name < template-args >::'. 4648 /// 4649 /// \param S The scope in which this nested-name-specifier occurs. 4650 /// 4651 /// \param SS The nested-name-specifier, which is both an input 4652 /// parameter (the nested-name-specifier before this type) and an 4653 /// output parameter (containing the full nested-name-specifier, 4654 /// including this new type). 4655 /// 4656 /// \param TemplateKWLoc the location of the 'template' keyword, if any. 4657 /// \param TemplateName the template name. 4658 /// \param TemplateNameLoc The location of the template name. 4659 /// \param LAngleLoc The location of the opening angle bracket ('<'). 4660 /// \param TemplateArgs The template arguments. 4661 /// \param RAngleLoc The location of the closing angle bracket ('>'). 4662 /// \param CCLoc The location of the '::'. 4663 /// 4664 /// \param EnteringContext Whether we're entering the context of the 4665 /// nested-name-specifier. 4666 /// 4667 /// 4668 /// \returns true if an error occurred, false otherwise. 4669 bool ActOnCXXNestedNameSpecifier(Scope *S, 4670 CXXScopeSpec &SS, 4671 SourceLocation TemplateKWLoc, 4672 TemplateTy TemplateName, 4673 SourceLocation TemplateNameLoc, 4674 SourceLocation LAngleLoc, 4675 ASTTemplateArgsPtr TemplateArgs, 4676 SourceLocation RAngleLoc, 4677 SourceLocation CCLoc, 4678 bool EnteringContext); 4679 4680 /// \brief Given a C++ nested-name-specifier, produce an annotation value 4681 /// that the parser can use later to reconstruct the given 4682 /// nested-name-specifier. 4683 /// 4684 /// \param SS A nested-name-specifier. 4685 /// 4686 /// \returns A pointer containing all of the information in the 4687 /// nested-name-specifier \p SS. 4688 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); 4689 4690 /// \brief Given an annotation pointer for a nested-name-specifier, restore 4691 /// the nested-name-specifier structure. 4692 /// 4693 /// \param Annotation The annotation pointer, produced by 4694 /// \c SaveNestedNameSpecifierAnnotation(). 4695 /// 4696 /// \param AnnotationRange The source range corresponding to the annotation. 4697 /// 4698 /// \param SS The nested-name-specifier that will be updated with the contents 4699 /// of the annotation pointer. 4700 void RestoreNestedNameSpecifierAnnotation(void *Annotation, 4701 SourceRange AnnotationRange, 4702 CXXScopeSpec &SS); 4703 4704 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 4705 4706 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global 4707 /// scope or nested-name-specifier) is parsed, part of a declarator-id. 4708 /// After this method is called, according to [C++ 3.4.3p3], names should be 4709 /// looked up in the declarator-id's scope, until the declarator is parsed and 4710 /// ActOnCXXExitDeclaratorScope is called. 4711 /// The 'SS' should be a non-empty valid CXXScopeSpec. 4712 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); 4713 4714 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously 4715 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same 4716 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. 4717 /// Used to indicate that names should revert to being looked up in the 4718 /// defining scope. 4719 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 4720 4721 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an 4722 /// initializer for the declaration 'Dcl'. 4723 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 4724 /// static data member of class X, names should be looked up in the scope of 4725 /// class X. 4726 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); 4727 4728 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 4729 /// initializer for the declaration 'Dcl'. 4730 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); 4731 4732 /// \brief Create a new lambda closure type. 4733 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, 4734 TypeSourceInfo *Info, 4735 bool KnownDependent, 4736 LambdaCaptureDefault CaptureDefault); 4737 4738 /// \brief Start the definition of a lambda expression. 4739 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class, 4740 SourceRange IntroducerRange, 4741 TypeSourceInfo *MethodType, 4742 SourceLocation EndLoc, 4743 ArrayRef<ParmVarDecl *> Params); 4744 4745 /// \brief Endow the lambda scope info with the relevant properties. 4746 void buildLambdaScope(sema::LambdaScopeInfo *LSI, 4747 CXXMethodDecl *CallOperator, 4748 SourceRange IntroducerRange, 4749 LambdaCaptureDefault CaptureDefault, 4750 SourceLocation CaptureDefaultLoc, 4751 bool ExplicitParams, 4752 bool ExplicitResultType, 4753 bool Mutable); 4754 4755 /// \brief Perform initialization analysis of the init-capture and perform 4756 /// any implicit conversions such as an lvalue-to-rvalue conversion if 4757 /// not being used to initialize a reference. 4758 QualType performLambdaInitCaptureInitialization(SourceLocation Loc, 4759 bool ByRef, IdentifierInfo *Id, Expr *&Init); 4760 /// \brief Create a dummy variable within the declcontext of the lambda's 4761 /// call operator, for name lookup purposes for a lambda init capture. 4762 /// 4763 /// CodeGen handles emission of lambda captures, ignoring these dummy 4764 /// variables appropriately. 4765 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc, 4766 QualType InitCaptureType, IdentifierInfo *Id, Expr *Init); 4767 4768 /// \brief Build the implicit field for an init-capture. 4769 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var); 4770 4771 /// \brief Note that we have finished the explicit captures for the 4772 /// given lambda. 4773 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); 4774 4775 /// \brief Introduce the lambda parameters into scope. 4776 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope); 4777 4778 /// \brief Deduce a block or lambda's return type based on the return 4779 /// statements present in the body. 4780 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); 4781 4782 /// ActOnStartOfLambdaDefinition - This is called just before we start 4783 /// parsing the body of a lambda; it analyzes the explicit captures and 4784 /// arguments, and sets up various data-structures for the body of the 4785 /// lambda. 4786 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, 4787 Declarator &ParamInfo, Scope *CurScope); 4788 4789 /// ActOnLambdaError - If there is an error parsing a lambda, this callback 4790 /// is invoked to pop the information about the lambda. 4791 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, 4792 bool IsInstantiation = false); 4793 4794 /// ActOnLambdaExpr - This is called when the body of a lambda expression 4795 /// was successfully completed. 4796 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, 4797 Scope *CurScope, 4798 bool IsInstantiation = false); 4799 4800 /// \brief Define the "body" of the conversion from a lambda object to a 4801 /// function pointer. 4802 /// 4803 /// This routine doesn't actually define a sensible body; rather, it fills 4804 /// in the initialization expression needed to copy the lambda object into 4805 /// the block, and IR generation actually generates the real body of the 4806 /// block pointer conversion. 4807 void DefineImplicitLambdaToFunctionPointerConversion( 4808 SourceLocation CurrentLoc, CXXConversionDecl *Conv); 4809 4810 /// \brief Define the "body" of the conversion from a lambda object to a 4811 /// block pointer. 4812 /// 4813 /// This routine doesn't actually define a sensible body; rather, it fills 4814 /// in the initialization expression needed to copy the lambda object into 4815 /// the block, and IR generation actually generates the real body of the 4816 /// block pointer conversion. 4817 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, 4818 CXXConversionDecl *Conv); 4819 4820 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, 4821 SourceLocation ConvLocation, 4822 CXXConversionDecl *Conv, 4823 Expr *Src); 4824 4825 // ParseObjCStringLiteral - Parse Objective-C string literals. 4826 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, 4827 Expr **Strings, 4828 unsigned NumStrings); 4829 4830 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); 4831 4832 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the 4833 /// numeric literal expression. Type of the expression will be "NSNumber *" 4834 /// or "id" if NSNumber is unavailable. 4835 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); 4836 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, 4837 bool Value); 4838 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); 4839 4840 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the 4841 /// '@' prefixed parenthesized expression. The type of the expression will 4842 /// either be "NSNumber *" or "NSString *" depending on the type of 4843 /// ValueType, which is allowed to be a built-in numeric type or 4844 /// "char *" or "const char *". 4845 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); 4846 4847 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, 4848 Expr *IndexExpr, 4849 ObjCMethodDecl *getterMethod, 4850 ObjCMethodDecl *setterMethod); 4851 4852 ExprResult BuildObjCDictionaryLiteral(SourceRange SR, 4853 ObjCDictionaryElement *Elements, 4854 unsigned NumElements); 4855 4856 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, 4857 TypeSourceInfo *EncodedTypeInfo, 4858 SourceLocation RParenLoc); 4859 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, 4860 CXXConversionDecl *Method, 4861 bool HadMultipleCandidates); 4862 4863 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, 4864 SourceLocation EncodeLoc, 4865 SourceLocation LParenLoc, 4866 ParsedType Ty, 4867 SourceLocation RParenLoc); 4868 4869 /// ParseObjCSelectorExpression - Build selector expression for \@selector 4870 ExprResult ParseObjCSelectorExpression(Selector Sel, 4871 SourceLocation AtLoc, 4872 SourceLocation SelLoc, 4873 SourceLocation LParenLoc, 4874 SourceLocation RParenLoc, 4875 bool WarnMultipleSelectors); 4876 4877 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol 4878 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, 4879 SourceLocation AtLoc, 4880 SourceLocation ProtoLoc, 4881 SourceLocation LParenLoc, 4882 SourceLocation ProtoIdLoc, 4883 SourceLocation RParenLoc); 4884 4885 //===--------------------------------------------------------------------===// 4886 // C++ Declarations 4887 // 4888 Decl *ActOnStartLinkageSpecification(Scope *S, 4889 SourceLocation ExternLoc, 4890 Expr *LangStr, 4891 SourceLocation LBraceLoc); 4892 Decl *ActOnFinishLinkageSpecification(Scope *S, 4893 Decl *LinkageSpec, 4894 SourceLocation RBraceLoc); 4895 4896 4897 //===--------------------------------------------------------------------===// 4898 // C++ Classes 4899 // 4900 bool isCurrentClassName(const IdentifierInfo &II, Scope *S, 4901 const CXXScopeSpec *SS = nullptr); 4902 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS); 4903 4904 bool ActOnAccessSpecifier(AccessSpecifier Access, 4905 SourceLocation ASLoc, 4906 SourceLocation ColonLoc, 4907 AttributeList *Attrs = nullptr); 4908 4909 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, 4910 Declarator &D, 4911 MultiTemplateParamsArg TemplateParameterLists, 4912 Expr *BitfieldWidth, const VirtSpecifiers &VS, 4913 InClassInitStyle InitStyle); 4914 4915 void ActOnStartCXXInClassMemberInitializer(); 4916 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, 4917 SourceLocation EqualLoc, 4918 Expr *Init); 4919 4920 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 4921 Scope *S, 4922 CXXScopeSpec &SS, 4923 IdentifierInfo *MemberOrBase, 4924 ParsedType TemplateTypeTy, 4925 const DeclSpec &DS, 4926 SourceLocation IdLoc, 4927 SourceLocation LParenLoc, 4928 ArrayRef<Expr *> Args, 4929 SourceLocation RParenLoc, 4930 SourceLocation EllipsisLoc); 4931 4932 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 4933 Scope *S, 4934 CXXScopeSpec &SS, 4935 IdentifierInfo *MemberOrBase, 4936 ParsedType TemplateTypeTy, 4937 const DeclSpec &DS, 4938 SourceLocation IdLoc, 4939 Expr *InitList, 4940 SourceLocation EllipsisLoc); 4941 4942 MemInitResult BuildMemInitializer(Decl *ConstructorD, 4943 Scope *S, 4944 CXXScopeSpec &SS, 4945 IdentifierInfo *MemberOrBase, 4946 ParsedType TemplateTypeTy, 4947 const DeclSpec &DS, 4948 SourceLocation IdLoc, 4949 Expr *Init, 4950 SourceLocation EllipsisLoc); 4951 4952 MemInitResult BuildMemberInitializer(ValueDecl *Member, 4953 Expr *Init, 4954 SourceLocation IdLoc); 4955 4956 MemInitResult BuildBaseInitializer(QualType BaseType, 4957 TypeSourceInfo *BaseTInfo, 4958 Expr *Init, 4959 CXXRecordDecl *ClassDecl, 4960 SourceLocation EllipsisLoc); 4961 4962 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, 4963 Expr *Init, 4964 CXXRecordDecl *ClassDecl); 4965 4966 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4967 CXXCtorInitializer *Initializer); 4968 4969 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4970 ArrayRef<CXXCtorInitializer *> Initializers = None); 4971 4972 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); 4973 4974 4975 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, 4976 /// mark all the non-trivial destructors of its members and bases as 4977 /// referenced. 4978 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, 4979 CXXRecordDecl *Record); 4980 4981 /// \brief The list of classes whose vtables have been used within 4982 /// this translation unit, and the source locations at which the 4983 /// first use occurred. 4984 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; 4985 4986 /// \brief The list of vtables that are required but have not yet been 4987 /// materialized. 4988 SmallVector<VTableUse, 16> VTableUses; 4989 4990 /// \brief The set of classes whose vtables have been used within 4991 /// this translation unit, and a bit that will be true if the vtable is 4992 /// required to be emitted (otherwise, it should be emitted only if needed 4993 /// by code generation). 4994 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; 4995 4996 /// \brief Load any externally-stored vtable uses. 4997 void LoadExternalVTableUses(); 4998 4999 /// \brief Note that the vtable for the given class was used at the 5000 /// given location. 5001 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 5002 bool DefinitionRequired = false); 5003 5004 /// \brief Mark the exception specifications of all virtual member functions 5005 /// in the given class as needed. 5006 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 5007 const CXXRecordDecl *RD); 5008 5009 /// MarkVirtualMembersReferenced - Will mark all members of the given 5010 /// CXXRecordDecl referenced. 5011 void MarkVirtualMembersReferenced(SourceLocation Loc, 5012 const CXXRecordDecl *RD); 5013 5014 /// \brief Define all of the vtables that have been used in this 5015 /// translation unit and reference any virtual members used by those 5016 /// vtables. 5017 /// 5018 /// \returns true if any work was done, false otherwise. 5019 bool DefineUsedVTables(); 5020 5021 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); 5022 5023 void ActOnMemInitializers(Decl *ConstructorDecl, 5024 SourceLocation ColonLoc, 5025 ArrayRef<CXXCtorInitializer*> MemInits, 5026 bool AnyErrors); 5027 5028 void CheckCompletedCXXClass(CXXRecordDecl *Record); 5029 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 5030 Decl *TagDecl, 5031 SourceLocation LBrac, 5032 SourceLocation RBrac, 5033 AttributeList *AttrList); 5034 void ActOnFinishCXXMemberDecls(); 5035 void ActOnFinishCXXMemberDefaultArgs(Decl *D); 5036 5037 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param); 5038 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template); 5039 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); 5040 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 5041 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); 5042 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); 5043 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 5044 void ActOnFinishDelayedMemberInitializers(Decl *Record); 5045 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, 5046 CachedTokens &Toks); 5047 void UnmarkAsLateParsedTemplate(FunctionDecl *FD); 5048 bool IsInsideALocalClassWithinATemplateFunction(); 5049 5050 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 5051 Expr *AssertExpr, 5052 Expr *AssertMessageExpr, 5053 SourceLocation RParenLoc); 5054 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 5055 Expr *AssertExpr, 5056 StringLiteral *AssertMessageExpr, 5057 SourceLocation RParenLoc, 5058 bool Failed); 5059 5060 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, 5061 SourceLocation FriendLoc, 5062 TypeSourceInfo *TSInfo); 5063 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 5064 MultiTemplateParamsArg TemplateParams); 5065 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, 5066 MultiTemplateParamsArg TemplateParams); 5067 5068 QualType CheckConstructorDeclarator(Declarator &D, QualType R, 5069 StorageClass& SC); 5070 void CheckConstructor(CXXConstructorDecl *Constructor); 5071 QualType CheckDestructorDeclarator(Declarator &D, QualType R, 5072 StorageClass& SC); 5073 bool CheckDestructor(CXXDestructorDecl *Destructor); 5074 void CheckConversionDeclarator(Declarator &D, QualType &R, 5075 StorageClass& SC); 5076 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); 5077 5078 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD); 5079 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD, 5080 const FunctionProtoType *T); 5081 void CheckDelayedMemberExceptionSpecs(); 5082 5083 //===--------------------------------------------------------------------===// 5084 // C++ Derived Classes 5085 // 5086 5087 /// ActOnBaseSpecifier - Parsed a base specifier 5088 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, 5089 SourceRange SpecifierRange, 5090 bool Virtual, AccessSpecifier Access, 5091 TypeSourceInfo *TInfo, 5092 SourceLocation EllipsisLoc); 5093 5094 BaseResult ActOnBaseSpecifier(Decl *classdecl, 5095 SourceRange SpecifierRange, 5096 ParsedAttributes &Attrs, 5097 bool Virtual, AccessSpecifier Access, 5098 ParsedType basetype, 5099 SourceLocation BaseLoc, 5100 SourceLocation EllipsisLoc); 5101 5102 bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 5103 unsigned NumBases); 5104 void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 5105 unsigned NumBases); 5106 5107 bool IsDerivedFrom(QualType Derived, QualType Base); 5108 bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths); 5109 5110 // FIXME: I don't like this name. 5111 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); 5112 5113 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 5114 SourceLocation Loc, SourceRange Range, 5115 CXXCastPath *BasePath = nullptr, 5116 bool IgnoreAccess = false); 5117 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 5118 unsigned InaccessibleBaseID, 5119 unsigned AmbigiousBaseConvID, 5120 SourceLocation Loc, SourceRange Range, 5121 DeclarationName Name, 5122 CXXCastPath *BasePath); 5123 5124 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); 5125 5126 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 5127 const CXXMethodDecl *Old); 5128 5129 /// CheckOverridingFunctionReturnType - Checks whether the return types are 5130 /// covariant, according to C++ [class.virtual]p5. 5131 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 5132 const CXXMethodDecl *Old); 5133 5134 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception 5135 /// spec is a subset of base spec. 5136 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, 5137 const CXXMethodDecl *Old); 5138 5139 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); 5140 5141 /// CheckOverrideControl - Check C++11 override control semantics. 5142 void CheckOverrideControl(NamedDecl *D); 5143 5144 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was 5145 /// not used in the declaration of an overriding method. 5146 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D); 5147 5148 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function 5149 /// overrides a virtual member function marked 'final', according to 5150 /// C++11 [class.virtual]p4. 5151 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 5152 const CXXMethodDecl *Old); 5153 5154 5155 //===--------------------------------------------------------------------===// 5156 // C++ Access Control 5157 // 5158 5159 enum AccessResult { 5160 AR_accessible, 5161 AR_inaccessible, 5162 AR_dependent, 5163 AR_delayed 5164 }; 5165 5166 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, 5167 NamedDecl *PrevMemberDecl, 5168 AccessSpecifier LexicalAS); 5169 5170 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, 5171 DeclAccessPair FoundDecl); 5172 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, 5173 DeclAccessPair FoundDecl); 5174 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, 5175 SourceRange PlacementRange, 5176 CXXRecordDecl *NamingClass, 5177 DeclAccessPair FoundDecl, 5178 bool Diagnose = true); 5179 AccessResult CheckConstructorAccess(SourceLocation Loc, 5180 CXXConstructorDecl *D, 5181 const InitializedEntity &Entity, 5182 AccessSpecifier Access, 5183 bool IsCopyBindingRefToTemp = false); 5184 AccessResult CheckConstructorAccess(SourceLocation Loc, 5185 CXXConstructorDecl *D, 5186 const InitializedEntity &Entity, 5187 AccessSpecifier Access, 5188 const PartialDiagnostic &PDiag); 5189 AccessResult CheckDestructorAccess(SourceLocation Loc, 5190 CXXDestructorDecl *Dtor, 5191 const PartialDiagnostic &PDiag, 5192 QualType objectType = QualType()); 5193 AccessResult CheckFriendAccess(NamedDecl *D); 5194 AccessResult CheckMemberAccess(SourceLocation UseLoc, 5195 CXXRecordDecl *NamingClass, 5196 DeclAccessPair Found); 5197 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, 5198 Expr *ObjectExpr, 5199 Expr *ArgExpr, 5200 DeclAccessPair FoundDecl); 5201 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, 5202 DeclAccessPair FoundDecl); 5203 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, 5204 QualType Base, QualType Derived, 5205 const CXXBasePath &Path, 5206 unsigned DiagID, 5207 bool ForceCheck = false, 5208 bool ForceUnprivileged = false); 5209 void CheckLookupAccess(const LookupResult &R); 5210 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx); 5211 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl, 5212 AccessSpecifier access, 5213 QualType objectType); 5214 5215 void HandleDependentAccessCheck(const DependentDiagnostic &DD, 5216 const MultiLevelTemplateArgumentList &TemplateArgs); 5217 void PerformDependentDiagnostics(const DeclContext *Pattern, 5218 const MultiLevelTemplateArgumentList &TemplateArgs); 5219 5220 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 5221 5222 /// \brief When true, access checking violations are treated as SFINAE 5223 /// failures rather than hard errors. 5224 bool AccessCheckingSFINAE; 5225 5226 enum AbstractDiagSelID { 5227 AbstractNone = -1, 5228 AbstractReturnType, 5229 AbstractParamType, 5230 AbstractVariableType, 5231 AbstractFieldType, 5232 AbstractIvarType, 5233 AbstractSynthesizedIvarType, 5234 AbstractArrayType 5235 }; 5236 5237 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 5238 TypeDiagnoser &Diagnoser); 5239 template <typename... Ts> RequireNonAbstractType(SourceLocation Loc,QualType T,unsigned DiagID,const Ts &...Args)5240 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, 5241 const Ts &...Args) { 5242 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 5243 return RequireNonAbstractType(Loc, T, Diagnoser); 5244 } 5245 5246 void DiagnoseAbstractType(const CXXRecordDecl *RD); 5247 5248 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, 5249 AbstractDiagSelID SelID = AbstractNone); 5250 5251 //===--------------------------------------------------------------------===// 5252 // C++ Overloaded Operators [C++ 13.5] 5253 // 5254 5255 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); 5256 5257 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); 5258 5259 //===--------------------------------------------------------------------===// 5260 // C++ Templates [C++ 14] 5261 // 5262 void FilterAcceptableTemplateNames(LookupResult &R, 5263 bool AllowFunctionTemplates = true); 5264 bool hasAnyAcceptableTemplateNames(LookupResult &R, 5265 bool AllowFunctionTemplates = true); 5266 5267 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, 5268 QualType ObjectType, bool EnteringContext, 5269 bool &MemberOfUnknownSpecialization); 5270 5271 TemplateNameKind isTemplateName(Scope *S, 5272 CXXScopeSpec &SS, 5273 bool hasTemplateKeyword, 5274 UnqualifiedId &Name, 5275 ParsedType ObjectType, 5276 bool EnteringContext, 5277 TemplateTy &Template, 5278 bool &MemberOfUnknownSpecialization); 5279 5280 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, 5281 SourceLocation IILoc, 5282 Scope *S, 5283 const CXXScopeSpec *SS, 5284 TemplateTy &SuggestedTemplate, 5285 TemplateNameKind &SuggestedKind); 5286 5287 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); 5288 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); 5289 5290 Decl *ActOnTypeParameter(Scope *S, bool Typename, 5291 SourceLocation EllipsisLoc, 5292 SourceLocation KeyLoc, 5293 IdentifierInfo *ParamName, 5294 SourceLocation ParamNameLoc, 5295 unsigned Depth, unsigned Position, 5296 SourceLocation EqualLoc, 5297 ParsedType DefaultArg); 5298 5299 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); 5300 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 5301 unsigned Depth, 5302 unsigned Position, 5303 SourceLocation EqualLoc, 5304 Expr *DefaultArg); 5305 Decl *ActOnTemplateTemplateParameter(Scope *S, 5306 SourceLocation TmpLoc, 5307 TemplateParameterList *Params, 5308 SourceLocation EllipsisLoc, 5309 IdentifierInfo *ParamName, 5310 SourceLocation ParamNameLoc, 5311 unsigned Depth, 5312 unsigned Position, 5313 SourceLocation EqualLoc, 5314 ParsedTemplateArgument DefaultArg); 5315 5316 TemplateParameterList * 5317 ActOnTemplateParameterList(unsigned Depth, 5318 SourceLocation ExportLoc, 5319 SourceLocation TemplateLoc, 5320 SourceLocation LAngleLoc, 5321 Decl **Params, unsigned NumParams, 5322 SourceLocation RAngleLoc); 5323 5324 /// \brief The context in which we are checking a template parameter list. 5325 enum TemplateParamListContext { 5326 TPC_ClassTemplate, 5327 TPC_VarTemplate, 5328 TPC_FunctionTemplate, 5329 TPC_ClassTemplateMember, 5330 TPC_FriendClassTemplate, 5331 TPC_FriendFunctionTemplate, 5332 TPC_FriendFunctionTemplateDefinition, 5333 TPC_TypeAliasTemplate 5334 }; 5335 5336 bool CheckTemplateParameterList(TemplateParameterList *NewParams, 5337 TemplateParameterList *OldParams, 5338 TemplateParamListContext TPC); 5339 TemplateParameterList *MatchTemplateParametersToScopeSpecifier( 5340 SourceLocation DeclStartLoc, SourceLocation DeclLoc, 5341 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, 5342 ArrayRef<TemplateParameterList *> ParamLists, 5343 bool IsFriend, bool &IsExplicitSpecialization, bool &Invalid); 5344 5345 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, 5346 SourceLocation KWLoc, CXXScopeSpec &SS, 5347 IdentifierInfo *Name, SourceLocation NameLoc, 5348 AttributeList *Attr, 5349 TemplateParameterList *TemplateParams, 5350 AccessSpecifier AS, 5351 SourceLocation ModulePrivateLoc, 5352 SourceLocation FriendLoc, 5353 unsigned NumOuterTemplateParamLists, 5354 TemplateParameterList **OuterTemplateParamLists, 5355 bool *SkipBody = nullptr); 5356 5357 void translateTemplateArguments(const ASTTemplateArgsPtr &In, 5358 TemplateArgumentListInfo &Out); 5359 5360 void NoteAllFoundTemplates(TemplateName Name); 5361 5362 QualType CheckTemplateIdType(TemplateName Template, 5363 SourceLocation TemplateLoc, 5364 TemplateArgumentListInfo &TemplateArgs); 5365 5366 TypeResult 5367 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 5368 TemplateTy Template, SourceLocation TemplateLoc, 5369 SourceLocation LAngleLoc, 5370 ASTTemplateArgsPtr TemplateArgs, 5371 SourceLocation RAngleLoc, 5372 bool IsCtorOrDtorName = false); 5373 5374 /// \brief Parsed an elaborated-type-specifier that refers to a template-id, 5375 /// such as \c class T::template apply<U>. 5376 TypeResult ActOnTagTemplateIdType(TagUseKind TUK, 5377 TypeSpecifierType TagSpec, 5378 SourceLocation TagLoc, 5379 CXXScopeSpec &SS, 5380 SourceLocation TemplateKWLoc, 5381 TemplateTy TemplateD, 5382 SourceLocation TemplateLoc, 5383 SourceLocation LAngleLoc, 5384 ASTTemplateArgsPtr TemplateArgsIn, 5385 SourceLocation RAngleLoc); 5386 5387 DeclResult ActOnVarTemplateSpecialization( 5388 Scope *S, Declarator &D, TypeSourceInfo *DI, 5389 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, 5390 StorageClass SC, bool IsPartialSpecialization); 5391 5392 DeclResult CheckVarTemplateId(VarTemplateDecl *Template, 5393 SourceLocation TemplateLoc, 5394 SourceLocation TemplateNameLoc, 5395 const TemplateArgumentListInfo &TemplateArgs); 5396 5397 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, 5398 const DeclarationNameInfo &NameInfo, 5399 VarTemplateDecl *Template, 5400 SourceLocation TemplateLoc, 5401 const TemplateArgumentListInfo *TemplateArgs); 5402 5403 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, 5404 SourceLocation TemplateKWLoc, 5405 LookupResult &R, 5406 bool RequiresADL, 5407 const TemplateArgumentListInfo *TemplateArgs); 5408 5409 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, 5410 SourceLocation TemplateKWLoc, 5411 const DeclarationNameInfo &NameInfo, 5412 const TemplateArgumentListInfo *TemplateArgs); 5413 5414 TemplateNameKind ActOnDependentTemplateName(Scope *S, 5415 CXXScopeSpec &SS, 5416 SourceLocation TemplateKWLoc, 5417 UnqualifiedId &Name, 5418 ParsedType ObjectType, 5419 bool EnteringContext, 5420 TemplateTy &Template); 5421 5422 DeclResult 5423 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, 5424 SourceLocation KWLoc, 5425 SourceLocation ModulePrivateLoc, 5426 TemplateIdAnnotation &TemplateId, 5427 AttributeList *Attr, 5428 MultiTemplateParamsArg TemplateParameterLists); 5429 5430 Decl *ActOnTemplateDeclarator(Scope *S, 5431 MultiTemplateParamsArg TemplateParameterLists, 5432 Declarator &D); 5433 5434 Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope, 5435 MultiTemplateParamsArg TemplateParameterLists, 5436 Declarator &D); 5437 5438 bool 5439 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, 5440 TemplateSpecializationKind NewTSK, 5441 NamedDecl *PrevDecl, 5442 TemplateSpecializationKind PrevTSK, 5443 SourceLocation PrevPtOfInstantiation, 5444 bool &SuppressNew); 5445 5446 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, 5447 const TemplateArgumentListInfo &ExplicitTemplateArgs, 5448 LookupResult &Previous); 5449 5450 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, 5451 TemplateArgumentListInfo *ExplicitTemplateArgs, 5452 LookupResult &Previous); 5453 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); 5454 5455 DeclResult 5456 ActOnExplicitInstantiation(Scope *S, 5457 SourceLocation ExternLoc, 5458 SourceLocation TemplateLoc, 5459 unsigned TagSpec, 5460 SourceLocation KWLoc, 5461 const CXXScopeSpec &SS, 5462 TemplateTy Template, 5463 SourceLocation TemplateNameLoc, 5464 SourceLocation LAngleLoc, 5465 ASTTemplateArgsPtr TemplateArgs, 5466 SourceLocation RAngleLoc, 5467 AttributeList *Attr); 5468 5469 DeclResult 5470 ActOnExplicitInstantiation(Scope *S, 5471 SourceLocation ExternLoc, 5472 SourceLocation TemplateLoc, 5473 unsigned TagSpec, 5474 SourceLocation KWLoc, 5475 CXXScopeSpec &SS, 5476 IdentifierInfo *Name, 5477 SourceLocation NameLoc, 5478 AttributeList *Attr); 5479 5480 DeclResult ActOnExplicitInstantiation(Scope *S, 5481 SourceLocation ExternLoc, 5482 SourceLocation TemplateLoc, 5483 Declarator &D); 5484 5485 TemplateArgumentLoc 5486 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, 5487 SourceLocation TemplateLoc, 5488 SourceLocation RAngleLoc, 5489 Decl *Param, 5490 SmallVectorImpl<TemplateArgument> 5491 &Converted, 5492 bool &HasDefaultArg); 5493 5494 /// \brief Specifies the context in which a particular template 5495 /// argument is being checked. 5496 enum CheckTemplateArgumentKind { 5497 /// \brief The template argument was specified in the code or was 5498 /// instantiated with some deduced template arguments. 5499 CTAK_Specified, 5500 5501 /// \brief The template argument was deduced via template argument 5502 /// deduction. 5503 CTAK_Deduced, 5504 5505 /// \brief The template argument was deduced from an array bound 5506 /// via template argument deduction. 5507 CTAK_DeducedFromArrayBound 5508 }; 5509 5510 bool CheckTemplateArgument(NamedDecl *Param, 5511 TemplateArgumentLoc &Arg, 5512 NamedDecl *Template, 5513 SourceLocation TemplateLoc, 5514 SourceLocation RAngleLoc, 5515 unsigned ArgumentPackIndex, 5516 SmallVectorImpl<TemplateArgument> &Converted, 5517 CheckTemplateArgumentKind CTAK = CTAK_Specified); 5518 5519 /// \brief Check that the given template arguments can be be provided to 5520 /// the given template, converting the arguments along the way. 5521 /// 5522 /// \param Template The template to which the template arguments are being 5523 /// provided. 5524 /// 5525 /// \param TemplateLoc The location of the template name in the source. 5526 /// 5527 /// \param TemplateArgs The list of template arguments. If the template is 5528 /// a template template parameter, this function may extend the set of 5529 /// template arguments to also include substituted, defaulted template 5530 /// arguments. 5531 /// 5532 /// \param PartialTemplateArgs True if the list of template arguments is 5533 /// intentionally partial, e.g., because we're checking just the initial 5534 /// set of template arguments. 5535 /// 5536 /// \param Converted Will receive the converted, canonicalized template 5537 /// arguments. 5538 /// 5539 /// \returns true if an error occurred, false otherwise. 5540 bool CheckTemplateArgumentList(TemplateDecl *Template, 5541 SourceLocation TemplateLoc, 5542 TemplateArgumentListInfo &TemplateArgs, 5543 bool PartialTemplateArgs, 5544 SmallVectorImpl<TemplateArgument> &Converted); 5545 5546 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, 5547 TemplateArgumentLoc &Arg, 5548 SmallVectorImpl<TemplateArgument> &Converted); 5549 5550 bool CheckTemplateArgument(TemplateTypeParmDecl *Param, 5551 TypeSourceInfo *Arg); 5552 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 5553 QualType InstantiatedParamType, Expr *Arg, 5554 TemplateArgument &Converted, 5555 CheckTemplateArgumentKind CTAK = CTAK_Specified); 5556 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param, 5557 TemplateArgumentLoc &Arg, 5558 unsigned ArgumentPackIndex); 5559 5560 ExprResult 5561 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, 5562 QualType ParamType, 5563 SourceLocation Loc); 5564 ExprResult 5565 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, 5566 SourceLocation Loc); 5567 5568 /// \brief Enumeration describing how template parameter lists are compared 5569 /// for equality. 5570 enum TemplateParameterListEqualKind { 5571 /// \brief We are matching the template parameter lists of two templates 5572 /// that might be redeclarations. 5573 /// 5574 /// \code 5575 /// template<typename T> struct X; 5576 /// template<typename T> struct X; 5577 /// \endcode 5578 TPL_TemplateMatch, 5579 5580 /// \brief We are matching the template parameter lists of two template 5581 /// template parameters as part of matching the template parameter lists 5582 /// of two templates that might be redeclarations. 5583 /// 5584 /// \code 5585 /// template<template<int I> class TT> struct X; 5586 /// template<template<int Value> class Other> struct X; 5587 /// \endcode 5588 TPL_TemplateTemplateParmMatch, 5589 5590 /// \brief We are matching the template parameter lists of a template 5591 /// template argument against the template parameter lists of a template 5592 /// template parameter. 5593 /// 5594 /// \code 5595 /// template<template<int Value> class Metafun> struct X; 5596 /// template<int Value> struct integer_c; 5597 /// X<integer_c> xic; 5598 /// \endcode 5599 TPL_TemplateTemplateArgumentMatch 5600 }; 5601 5602 bool TemplateParameterListsAreEqual(TemplateParameterList *New, 5603 TemplateParameterList *Old, 5604 bool Complain, 5605 TemplateParameterListEqualKind Kind, 5606 SourceLocation TemplateArgLoc 5607 = SourceLocation()); 5608 5609 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); 5610 5611 /// \brief Called when the parser has parsed a C++ typename 5612 /// specifier, e.g., "typename T::type". 5613 /// 5614 /// \param S The scope in which this typename type occurs. 5615 /// \param TypenameLoc the location of the 'typename' keyword 5616 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 5617 /// \param II the identifier we're retrieving (e.g., 'type' in the example). 5618 /// \param IdLoc the location of the identifier. 5619 TypeResult 5620 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 5621 const CXXScopeSpec &SS, const IdentifierInfo &II, 5622 SourceLocation IdLoc); 5623 5624 /// \brief Called when the parser has parsed a C++ typename 5625 /// specifier that ends in a template-id, e.g., 5626 /// "typename MetaFun::template apply<T1, T2>". 5627 /// 5628 /// \param S The scope in which this typename type occurs. 5629 /// \param TypenameLoc the location of the 'typename' keyword 5630 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 5631 /// \param TemplateLoc the location of the 'template' keyword, if any. 5632 /// \param TemplateName The template name. 5633 /// \param TemplateNameLoc The location of the template name. 5634 /// \param LAngleLoc The location of the opening angle bracket ('<'). 5635 /// \param TemplateArgs The template arguments. 5636 /// \param RAngleLoc The location of the closing angle bracket ('>'). 5637 TypeResult 5638 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 5639 const CXXScopeSpec &SS, 5640 SourceLocation TemplateLoc, 5641 TemplateTy TemplateName, 5642 SourceLocation TemplateNameLoc, 5643 SourceLocation LAngleLoc, 5644 ASTTemplateArgsPtr TemplateArgs, 5645 SourceLocation RAngleLoc); 5646 5647 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, 5648 SourceLocation KeywordLoc, 5649 NestedNameSpecifierLoc QualifierLoc, 5650 const IdentifierInfo &II, 5651 SourceLocation IILoc); 5652 5653 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, 5654 SourceLocation Loc, 5655 DeclarationName Name); 5656 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); 5657 5658 ExprResult RebuildExprInCurrentInstantiation(Expr *E); 5659 bool RebuildTemplateParamsInCurrentInstantiation( 5660 TemplateParameterList *Params); 5661 5662 std::string 5663 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 5664 const TemplateArgumentList &Args); 5665 5666 std::string 5667 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 5668 const TemplateArgument *Args, 5669 unsigned NumArgs); 5670 5671 //===--------------------------------------------------------------------===// 5672 // C++ Variadic Templates (C++0x [temp.variadic]) 5673 //===--------------------------------------------------------------------===// 5674 5675 /// Determine whether an unexpanded parameter pack might be permitted in this 5676 /// location. Useful for error recovery. 5677 bool isUnexpandedParameterPackPermitted(); 5678 5679 /// \brief The context in which an unexpanded parameter pack is 5680 /// being diagnosed. 5681 /// 5682 /// Note that the values of this enumeration line up with the first 5683 /// argument to the \c err_unexpanded_parameter_pack diagnostic. 5684 enum UnexpandedParameterPackContext { 5685 /// \brief An arbitrary expression. 5686 UPPC_Expression = 0, 5687 5688 /// \brief The base type of a class type. 5689 UPPC_BaseType, 5690 5691 /// \brief The type of an arbitrary declaration. 5692 UPPC_DeclarationType, 5693 5694 /// \brief The type of a data member. 5695 UPPC_DataMemberType, 5696 5697 /// \brief The size of a bit-field. 5698 UPPC_BitFieldWidth, 5699 5700 /// \brief The expression in a static assertion. 5701 UPPC_StaticAssertExpression, 5702 5703 /// \brief The fixed underlying type of an enumeration. 5704 UPPC_FixedUnderlyingType, 5705 5706 /// \brief The enumerator value. 5707 UPPC_EnumeratorValue, 5708 5709 /// \brief A using declaration. 5710 UPPC_UsingDeclaration, 5711 5712 /// \brief A friend declaration. 5713 UPPC_FriendDeclaration, 5714 5715 /// \brief A declaration qualifier. 5716 UPPC_DeclarationQualifier, 5717 5718 /// \brief An initializer. 5719 UPPC_Initializer, 5720 5721 /// \brief A default argument. 5722 UPPC_DefaultArgument, 5723 5724 /// \brief The type of a non-type template parameter. 5725 UPPC_NonTypeTemplateParameterType, 5726 5727 /// \brief The type of an exception. 5728 UPPC_ExceptionType, 5729 5730 /// \brief Partial specialization. 5731 UPPC_PartialSpecialization, 5732 5733 /// \brief Microsoft __if_exists. 5734 UPPC_IfExists, 5735 5736 /// \brief Microsoft __if_not_exists. 5737 UPPC_IfNotExists, 5738 5739 /// \brief Lambda expression. 5740 UPPC_Lambda, 5741 5742 /// \brief Block expression, 5743 UPPC_Block 5744 }; 5745 5746 /// \brief Diagnose unexpanded parameter packs. 5747 /// 5748 /// \param Loc The location at which we should emit the diagnostic. 5749 /// 5750 /// \param UPPC The context in which we are diagnosing unexpanded 5751 /// parameter packs. 5752 /// 5753 /// \param Unexpanded the set of unexpanded parameter packs. 5754 /// 5755 /// \returns true if an error occurred, false otherwise. 5756 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, 5757 UnexpandedParameterPackContext UPPC, 5758 ArrayRef<UnexpandedParameterPack> Unexpanded); 5759 5760 /// \brief If the given type contains an unexpanded parameter pack, 5761 /// diagnose the error. 5762 /// 5763 /// \param Loc The source location where a diagnostc should be emitted. 5764 /// 5765 /// \param T The type that is being checked for unexpanded parameter 5766 /// packs. 5767 /// 5768 /// \returns true if an error occurred, false otherwise. 5769 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, 5770 UnexpandedParameterPackContext UPPC); 5771 5772 /// \brief If the given expression contains an unexpanded parameter 5773 /// pack, diagnose the error. 5774 /// 5775 /// \param E The expression that is being checked for unexpanded 5776 /// parameter packs. 5777 /// 5778 /// \returns true if an error occurred, false otherwise. 5779 bool DiagnoseUnexpandedParameterPack(Expr *E, 5780 UnexpandedParameterPackContext UPPC = UPPC_Expression); 5781 5782 /// \brief If the given nested-name-specifier contains an unexpanded 5783 /// parameter pack, diagnose the error. 5784 /// 5785 /// \param SS The nested-name-specifier that is being checked for 5786 /// unexpanded parameter packs. 5787 /// 5788 /// \returns true if an error occurred, false otherwise. 5789 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, 5790 UnexpandedParameterPackContext UPPC); 5791 5792 /// \brief If the given name contains an unexpanded parameter pack, 5793 /// diagnose the error. 5794 /// 5795 /// \param NameInfo The name (with source location information) that 5796 /// is being checked for unexpanded parameter packs. 5797 /// 5798 /// \returns true if an error occurred, false otherwise. 5799 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, 5800 UnexpandedParameterPackContext UPPC); 5801 5802 /// \brief If the given template name contains an unexpanded parameter pack, 5803 /// diagnose the error. 5804 /// 5805 /// \param Loc The location of the template name. 5806 /// 5807 /// \param Template The template name that is being checked for unexpanded 5808 /// parameter packs. 5809 /// 5810 /// \returns true if an error occurred, false otherwise. 5811 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, 5812 TemplateName Template, 5813 UnexpandedParameterPackContext UPPC); 5814 5815 /// \brief If the given template argument contains an unexpanded parameter 5816 /// pack, diagnose the error. 5817 /// 5818 /// \param Arg The template argument that is being checked for unexpanded 5819 /// parameter packs. 5820 /// 5821 /// \returns true if an error occurred, false otherwise. 5822 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, 5823 UnexpandedParameterPackContext UPPC); 5824 5825 /// \brief Collect the set of unexpanded parameter packs within the given 5826 /// template argument. 5827 /// 5828 /// \param Arg The template argument that will be traversed to find 5829 /// unexpanded parameter packs. 5830 void collectUnexpandedParameterPacks(TemplateArgument Arg, 5831 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5832 5833 /// \brief Collect the set of unexpanded parameter packs within the given 5834 /// template argument. 5835 /// 5836 /// \param Arg The template argument that will be traversed to find 5837 /// unexpanded parameter packs. 5838 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, 5839 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5840 5841 /// \brief Collect the set of unexpanded parameter packs within the given 5842 /// type. 5843 /// 5844 /// \param T The type that will be traversed to find 5845 /// unexpanded parameter packs. 5846 void collectUnexpandedParameterPacks(QualType T, 5847 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5848 5849 /// \brief Collect the set of unexpanded parameter packs within the given 5850 /// type. 5851 /// 5852 /// \param TL The type that will be traversed to find 5853 /// unexpanded parameter packs. 5854 void collectUnexpandedParameterPacks(TypeLoc TL, 5855 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5856 5857 /// \brief Collect the set of unexpanded parameter packs within the given 5858 /// nested-name-specifier. 5859 /// 5860 /// \param SS The nested-name-specifier that will be traversed to find 5861 /// unexpanded parameter packs. 5862 void collectUnexpandedParameterPacks(CXXScopeSpec &SS, 5863 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5864 5865 /// \brief Collect the set of unexpanded parameter packs within the given 5866 /// name. 5867 /// 5868 /// \param NameInfo The name that will be traversed to find 5869 /// unexpanded parameter packs. 5870 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, 5871 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5872 5873 /// \brief Invoked when parsing a template argument followed by an 5874 /// ellipsis, which creates a pack expansion. 5875 /// 5876 /// \param Arg The template argument preceding the ellipsis, which 5877 /// may already be invalid. 5878 /// 5879 /// \param EllipsisLoc The location of the ellipsis. 5880 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, 5881 SourceLocation EllipsisLoc); 5882 5883 /// \brief Invoked when parsing a type followed by an ellipsis, which 5884 /// creates a pack expansion. 5885 /// 5886 /// \param Type The type preceding the ellipsis, which will become 5887 /// the pattern of the pack expansion. 5888 /// 5889 /// \param EllipsisLoc The location of the ellipsis. 5890 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); 5891 5892 /// \brief Construct a pack expansion type from the pattern of the pack 5893 /// expansion. 5894 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, 5895 SourceLocation EllipsisLoc, 5896 Optional<unsigned> NumExpansions); 5897 5898 /// \brief Construct a pack expansion type from the pattern of the pack 5899 /// expansion. 5900 QualType CheckPackExpansion(QualType Pattern, 5901 SourceRange PatternRange, 5902 SourceLocation EllipsisLoc, 5903 Optional<unsigned> NumExpansions); 5904 5905 /// \brief Invoked when parsing an expression followed by an ellipsis, which 5906 /// creates a pack expansion. 5907 /// 5908 /// \param Pattern The expression preceding the ellipsis, which will become 5909 /// the pattern of the pack expansion. 5910 /// 5911 /// \param EllipsisLoc The location of the ellipsis. 5912 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); 5913 5914 /// \brief Invoked when parsing an expression followed by an ellipsis, which 5915 /// creates a pack expansion. 5916 /// 5917 /// \param Pattern The expression preceding the ellipsis, which will become 5918 /// the pattern of the pack expansion. 5919 /// 5920 /// \param EllipsisLoc The location of the ellipsis. 5921 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, 5922 Optional<unsigned> NumExpansions); 5923 5924 /// \brief Determine whether we could expand a pack expansion with the 5925 /// given set of parameter packs into separate arguments by repeatedly 5926 /// transforming the pattern. 5927 /// 5928 /// \param EllipsisLoc The location of the ellipsis that identifies the 5929 /// pack expansion. 5930 /// 5931 /// \param PatternRange The source range that covers the entire pattern of 5932 /// the pack expansion. 5933 /// 5934 /// \param Unexpanded The set of unexpanded parameter packs within the 5935 /// pattern. 5936 /// 5937 /// \param ShouldExpand Will be set to \c true if the transformer should 5938 /// expand the corresponding pack expansions into separate arguments. When 5939 /// set, \c NumExpansions must also be set. 5940 /// 5941 /// \param RetainExpansion Whether the caller should add an unexpanded 5942 /// pack expansion after all of the expanded arguments. This is used 5943 /// when extending explicitly-specified template argument packs per 5944 /// C++0x [temp.arg.explicit]p9. 5945 /// 5946 /// \param NumExpansions The number of separate arguments that will be in 5947 /// the expanded form of the corresponding pack expansion. This is both an 5948 /// input and an output parameter, which can be set by the caller if the 5949 /// number of expansions is known a priori (e.g., due to a prior substitution) 5950 /// and will be set by the callee when the number of expansions is known. 5951 /// The callee must set this value when \c ShouldExpand is \c true; it may 5952 /// set this value in other cases. 5953 /// 5954 /// \returns true if an error occurred (e.g., because the parameter packs 5955 /// are to be instantiated with arguments of different lengths), false 5956 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) 5957 /// must be set. 5958 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, 5959 SourceRange PatternRange, 5960 ArrayRef<UnexpandedParameterPack> Unexpanded, 5961 const MultiLevelTemplateArgumentList &TemplateArgs, 5962 bool &ShouldExpand, 5963 bool &RetainExpansion, 5964 Optional<unsigned> &NumExpansions); 5965 5966 /// \brief Determine the number of arguments in the given pack expansion 5967 /// type. 5968 /// 5969 /// This routine assumes that the number of arguments in the expansion is 5970 /// consistent across all of the unexpanded parameter packs in its pattern. 5971 /// 5972 /// Returns an empty Optional if the type can't be expanded. 5973 Optional<unsigned> getNumArgumentsInExpansion(QualType T, 5974 const MultiLevelTemplateArgumentList &TemplateArgs); 5975 5976 /// \brief Determine whether the given declarator contains any unexpanded 5977 /// parameter packs. 5978 /// 5979 /// This routine is used by the parser to disambiguate function declarators 5980 /// with an ellipsis prior to the ')', e.g., 5981 /// 5982 /// \code 5983 /// void f(T...); 5984 /// \endcode 5985 /// 5986 /// To determine whether we have an (unnamed) function parameter pack or 5987 /// a variadic function. 5988 /// 5989 /// \returns true if the declarator contains any unexpanded parameter packs, 5990 /// false otherwise. 5991 bool containsUnexpandedParameterPacks(Declarator &D); 5992 5993 /// \brief Returns the pattern of the pack expansion for a template argument. 5994 /// 5995 /// \param OrigLoc The template argument to expand. 5996 /// 5997 /// \param Ellipsis Will be set to the location of the ellipsis. 5998 /// 5999 /// \param NumExpansions Will be set to the number of expansions that will 6000 /// be generated from this pack expansion, if known a priori. 6001 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( 6002 TemplateArgumentLoc OrigLoc, 6003 SourceLocation &Ellipsis, 6004 Optional<unsigned> &NumExpansions) const; 6005 6006 //===--------------------------------------------------------------------===// 6007 // C++ Template Argument Deduction (C++ [temp.deduct]) 6008 //===--------------------------------------------------------------------===// 6009 6010 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType); 6011 6012 /// \brief Describes the result of template argument deduction. 6013 /// 6014 /// The TemplateDeductionResult enumeration describes the result of 6015 /// template argument deduction, as returned from 6016 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo 6017 /// structure provides additional information about the results of 6018 /// template argument deduction, e.g., the deduced template argument 6019 /// list (if successful) or the specific template parameters or 6020 /// deduced arguments that were involved in the failure. 6021 enum TemplateDeductionResult { 6022 /// \brief Template argument deduction was successful. 6023 TDK_Success = 0, 6024 /// \brief The declaration was invalid; do nothing. 6025 TDK_Invalid, 6026 /// \brief Template argument deduction exceeded the maximum template 6027 /// instantiation depth (which has already been diagnosed). 6028 TDK_InstantiationDepth, 6029 /// \brief Template argument deduction did not deduce a value 6030 /// for every template parameter. 6031 TDK_Incomplete, 6032 /// \brief Template argument deduction produced inconsistent 6033 /// deduced values for the given template parameter. 6034 TDK_Inconsistent, 6035 /// \brief Template argument deduction failed due to inconsistent 6036 /// cv-qualifiers on a template parameter type that would 6037 /// otherwise be deduced, e.g., we tried to deduce T in "const T" 6038 /// but were given a non-const "X". 6039 TDK_Underqualified, 6040 /// \brief Substitution of the deduced template argument values 6041 /// resulted in an error. 6042 TDK_SubstitutionFailure, 6043 /// \brief A non-depnedent component of the parameter did not match the 6044 /// corresponding component of the argument. 6045 TDK_NonDeducedMismatch, 6046 /// \brief When performing template argument deduction for a function 6047 /// template, there were too many call arguments. 6048 TDK_TooManyArguments, 6049 /// \brief When performing template argument deduction for a function 6050 /// template, there were too few call arguments. 6051 TDK_TooFewArguments, 6052 /// \brief The explicitly-specified template arguments were not valid 6053 /// template arguments for the given template. 6054 TDK_InvalidExplicitArguments, 6055 /// \brief The arguments included an overloaded function name that could 6056 /// not be resolved to a suitable function. 6057 TDK_FailedOverloadResolution, 6058 /// \brief Deduction failed; that's all we know. 6059 TDK_MiscellaneousDeductionFailure 6060 }; 6061 6062 TemplateDeductionResult 6063 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, 6064 const TemplateArgumentList &TemplateArgs, 6065 sema::TemplateDeductionInfo &Info); 6066 6067 TemplateDeductionResult 6068 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, 6069 const TemplateArgumentList &TemplateArgs, 6070 sema::TemplateDeductionInfo &Info); 6071 6072 TemplateDeductionResult SubstituteExplicitTemplateArguments( 6073 FunctionTemplateDecl *FunctionTemplate, 6074 TemplateArgumentListInfo &ExplicitTemplateArgs, 6075 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 6076 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, 6077 sema::TemplateDeductionInfo &Info); 6078 6079 /// brief A function argument from which we performed template argument 6080 // deduction for a call. 6081 struct OriginalCallArg { OriginalCallArgOriginalCallArg6082 OriginalCallArg(QualType OriginalParamType, 6083 unsigned ArgIdx, 6084 QualType OriginalArgType) 6085 : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx), 6086 OriginalArgType(OriginalArgType) { } 6087 6088 QualType OriginalParamType; 6089 unsigned ArgIdx; 6090 QualType OriginalArgType; 6091 }; 6092 6093 TemplateDeductionResult 6094 FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate, 6095 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 6096 unsigned NumExplicitlySpecified, 6097 FunctionDecl *&Specialization, 6098 sema::TemplateDeductionInfo &Info, 6099 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr, 6100 bool PartialOverloading = false); 6101 6102 TemplateDeductionResult 6103 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 6104 TemplateArgumentListInfo *ExplicitTemplateArgs, 6105 ArrayRef<Expr *> Args, 6106 FunctionDecl *&Specialization, 6107 sema::TemplateDeductionInfo &Info, 6108 bool PartialOverloading = false); 6109 6110 TemplateDeductionResult 6111 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 6112 TemplateArgumentListInfo *ExplicitTemplateArgs, 6113 QualType ArgFunctionType, 6114 FunctionDecl *&Specialization, 6115 sema::TemplateDeductionInfo &Info, 6116 bool InOverloadResolution = false); 6117 6118 TemplateDeductionResult 6119 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 6120 QualType ToType, 6121 CXXConversionDecl *&Specialization, 6122 sema::TemplateDeductionInfo &Info); 6123 6124 TemplateDeductionResult 6125 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 6126 TemplateArgumentListInfo *ExplicitTemplateArgs, 6127 FunctionDecl *&Specialization, 6128 sema::TemplateDeductionInfo &Info, 6129 bool InOverloadResolution = false); 6130 6131 /// \brief Substitute Replacement for \p auto in \p TypeWithAuto 6132 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); 6133 /// \brief Substitute Replacement for auto in TypeWithAuto 6134 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, 6135 QualType Replacement); 6136 6137 /// \brief Result type of DeduceAutoType. 6138 enum DeduceAutoResult { 6139 DAR_Succeeded, 6140 DAR_Failed, 6141 DAR_FailedAlreadyDiagnosed 6142 }; 6143 6144 DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, 6145 QualType &Result); 6146 DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, 6147 QualType &Result); 6148 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); 6149 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, 6150 bool Diagnose = true); 6151 6152 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const; 6153 6154 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, 6155 SourceLocation ReturnLoc, 6156 Expr *&RetExpr, AutoType *AT); 6157 6158 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, 6159 FunctionTemplateDecl *FT2, 6160 SourceLocation Loc, 6161 TemplatePartialOrderingContext TPOC, 6162 unsigned NumCallArguments1, 6163 unsigned NumCallArguments2); 6164 UnresolvedSetIterator 6165 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, 6166 TemplateSpecCandidateSet &FailedCandidates, 6167 SourceLocation Loc, 6168 const PartialDiagnostic &NoneDiag, 6169 const PartialDiagnostic &AmbigDiag, 6170 const PartialDiagnostic &CandidateDiag, 6171 bool Complain = true, QualType TargetType = QualType()); 6172 6173 ClassTemplatePartialSpecializationDecl * 6174 getMoreSpecializedPartialSpecialization( 6175 ClassTemplatePartialSpecializationDecl *PS1, 6176 ClassTemplatePartialSpecializationDecl *PS2, 6177 SourceLocation Loc); 6178 6179 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( 6180 VarTemplatePartialSpecializationDecl *PS1, 6181 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); 6182 6183 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, 6184 bool OnlyDeduced, 6185 unsigned Depth, 6186 llvm::SmallBitVector &Used); MarkDeducedTemplateParameters(const FunctionTemplateDecl * FunctionTemplate,llvm::SmallBitVector & Deduced)6187 void MarkDeducedTemplateParameters( 6188 const FunctionTemplateDecl *FunctionTemplate, 6189 llvm::SmallBitVector &Deduced) { 6190 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); 6191 } 6192 static void MarkDeducedTemplateParameters(ASTContext &Ctx, 6193 const FunctionTemplateDecl *FunctionTemplate, 6194 llvm::SmallBitVector &Deduced); 6195 6196 //===--------------------------------------------------------------------===// 6197 // C++ Template Instantiation 6198 // 6199 6200 MultiLevelTemplateArgumentList 6201 getTemplateInstantiationArgs(NamedDecl *D, 6202 const TemplateArgumentList *Innermost = nullptr, 6203 bool RelativeToPrimary = false, 6204 const FunctionDecl *Pattern = nullptr); 6205 6206 /// \brief A template instantiation that is currently in progress. 6207 struct ActiveTemplateInstantiation { 6208 /// \brief The kind of template instantiation we are performing 6209 enum InstantiationKind { 6210 /// We are instantiating a template declaration. The entity is 6211 /// the declaration we're instantiating (e.g., a CXXRecordDecl). 6212 TemplateInstantiation, 6213 6214 /// We are instantiating a default argument for a template 6215 /// parameter. The Entity is the template, and 6216 /// TemplateArgs/NumTemplateArguments provides the template 6217 /// arguments as specified. 6218 /// FIXME: Use a TemplateArgumentList 6219 DefaultTemplateArgumentInstantiation, 6220 6221 /// We are instantiating a default argument for a function. 6222 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs 6223 /// provides the template arguments as specified. 6224 DefaultFunctionArgumentInstantiation, 6225 6226 /// We are substituting explicit template arguments provided for 6227 /// a function template. The entity is a FunctionTemplateDecl. 6228 ExplicitTemplateArgumentSubstitution, 6229 6230 /// We are substituting template argument determined as part of 6231 /// template argument deduction for either a class template 6232 /// partial specialization or a function template. The 6233 /// Entity is either a ClassTemplatePartialSpecializationDecl or 6234 /// a FunctionTemplateDecl. 6235 DeducedTemplateArgumentSubstitution, 6236 6237 /// We are substituting prior template arguments into a new 6238 /// template parameter. The template parameter itself is either a 6239 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. 6240 PriorTemplateArgumentSubstitution, 6241 6242 /// We are checking the validity of a default template argument that 6243 /// has been used when naming a template-id. 6244 DefaultTemplateArgumentChecking, 6245 6246 /// We are instantiating the exception specification for a function 6247 /// template which was deferred until it was needed. 6248 ExceptionSpecInstantiation 6249 } Kind; 6250 6251 /// \brief The point of instantiation within the source code. 6252 SourceLocation PointOfInstantiation; 6253 6254 /// \brief The template (or partial specialization) in which we are 6255 /// performing the instantiation, for substitutions of prior template 6256 /// arguments. 6257 NamedDecl *Template; 6258 6259 /// \brief The entity that is being instantiated. 6260 Decl *Entity; 6261 6262 /// \brief The list of template arguments we are substituting, if they 6263 /// are not part of the entity. 6264 const TemplateArgument *TemplateArgs; 6265 6266 /// \brief The number of template arguments in TemplateArgs. 6267 unsigned NumTemplateArgs; 6268 6269 /// \brief The template deduction info object associated with the 6270 /// substitution or checking of explicit or deduced template arguments. 6271 sema::TemplateDeductionInfo *DeductionInfo; 6272 6273 /// \brief The source range that covers the construct that cause 6274 /// the instantiation, e.g., the template-id that causes a class 6275 /// template instantiation. 6276 SourceRange InstantiationRange; 6277 ActiveTemplateInstantiationActiveTemplateInstantiation6278 ActiveTemplateInstantiation() 6279 : Kind(TemplateInstantiation), Template(nullptr), Entity(nullptr), 6280 TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {} 6281 6282 /// \brief Determines whether this template is an actual instantiation 6283 /// that should be counted toward the maximum instantiation depth. 6284 bool isInstantiationRecord() const; 6285 6286 friend bool operator==(const ActiveTemplateInstantiation &X, 6287 const ActiveTemplateInstantiation &Y) { 6288 if (X.Kind != Y.Kind) 6289 return false; 6290 6291 if (X.Entity != Y.Entity) 6292 return false; 6293 6294 switch (X.Kind) { 6295 case TemplateInstantiation: 6296 case ExceptionSpecInstantiation: 6297 return true; 6298 6299 case PriorTemplateArgumentSubstitution: 6300 case DefaultTemplateArgumentChecking: 6301 return X.Template == Y.Template && X.TemplateArgs == Y.TemplateArgs; 6302 6303 case DefaultTemplateArgumentInstantiation: 6304 case ExplicitTemplateArgumentSubstitution: 6305 case DeducedTemplateArgumentSubstitution: 6306 case DefaultFunctionArgumentInstantiation: 6307 return X.TemplateArgs == Y.TemplateArgs; 6308 6309 } 6310 6311 llvm_unreachable("Invalid InstantiationKind!"); 6312 } 6313 6314 friend bool operator!=(const ActiveTemplateInstantiation &X, 6315 const ActiveTemplateInstantiation &Y) { 6316 return !(X == Y); 6317 } 6318 }; 6319 6320 /// \brief List of active template instantiations. 6321 /// 6322 /// This vector is treated as a stack. As one template instantiation 6323 /// requires another template instantiation, additional 6324 /// instantiations are pushed onto the stack up to a 6325 /// user-configurable limit LangOptions::InstantiationDepth. 6326 SmallVector<ActiveTemplateInstantiation, 16> 6327 ActiveTemplateInstantiations; 6328 6329 /// \brief Extra modules inspected when performing a lookup during a template 6330 /// instantiation. Computed lazily. 6331 SmallVector<Module*, 16> ActiveTemplateInstantiationLookupModules; 6332 6333 /// \brief Cache of additional modules that should be used for name lookup 6334 /// within the current template instantiation. Computed lazily; use 6335 /// getLookupModules() to get a complete set. 6336 llvm::DenseSet<Module*> LookupModulesCache; 6337 6338 /// \brief Get the set of additional modules that should be checked during 6339 /// name lookup. A module and its imports become visible when instanting a 6340 /// template defined within it. 6341 llvm::DenseSet<Module*> &getLookupModules(); 6342 6343 /// \brief Whether we are in a SFINAE context that is not associated with 6344 /// template instantiation. 6345 /// 6346 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside 6347 /// of a template instantiation or template argument deduction. 6348 bool InNonInstantiationSFINAEContext; 6349 6350 /// \brief The number of ActiveTemplateInstantiation entries in 6351 /// \c ActiveTemplateInstantiations that are not actual instantiations and, 6352 /// therefore, should not be counted as part of the instantiation depth. 6353 unsigned NonInstantiationEntries; 6354 6355 /// \brief The last template from which a template instantiation 6356 /// error or warning was produced. 6357 /// 6358 /// This value is used to suppress printing of redundant template 6359 /// instantiation backtraces when there are multiple errors in the 6360 /// same instantiation. FIXME: Does this belong in Sema? It's tough 6361 /// to implement it anywhere else. 6362 ActiveTemplateInstantiation LastTemplateInstantiationErrorContext; 6363 6364 /// \brief The current index into pack expansion arguments that will be 6365 /// used for substitution of parameter packs. 6366 /// 6367 /// The pack expansion index will be -1 to indicate that parameter packs 6368 /// should be instantiated as themselves. Otherwise, the index specifies 6369 /// which argument within the parameter pack will be used for substitution. 6370 int ArgumentPackSubstitutionIndex; 6371 6372 /// \brief RAII object used to change the argument pack substitution index 6373 /// within a \c Sema object. 6374 /// 6375 /// See \c ArgumentPackSubstitutionIndex for more information. 6376 class ArgumentPackSubstitutionIndexRAII { 6377 Sema &Self; 6378 int OldSubstitutionIndex; 6379 6380 public: ArgumentPackSubstitutionIndexRAII(Sema & Self,int NewSubstitutionIndex)6381 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) 6382 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { 6383 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; 6384 } 6385 ~ArgumentPackSubstitutionIndexRAII()6386 ~ArgumentPackSubstitutionIndexRAII() { 6387 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; 6388 } 6389 }; 6390 6391 friend class ArgumentPackSubstitutionRAII; 6392 6393 /// \brief The stack of calls expression undergoing template instantiation. 6394 /// 6395 /// The top of this stack is used by a fixit instantiating unresolved 6396 /// function calls to fix the AST to match the textual change it prints. 6397 SmallVector<CallExpr *, 8> CallsUndergoingInstantiation; 6398 6399 /// \brief For each declaration that involved template argument deduction, the 6400 /// set of diagnostics that were suppressed during that template argument 6401 /// deduction. 6402 /// 6403 /// FIXME: Serialize this structure to the AST file. 6404 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > 6405 SuppressedDiagnosticsMap; 6406 SuppressedDiagnosticsMap SuppressedDiagnostics; 6407 6408 /// \brief A stack object to be created when performing template 6409 /// instantiation. 6410 /// 6411 /// Construction of an object of type \c InstantiatingTemplate 6412 /// pushes the current instantiation onto the stack of active 6413 /// instantiations. If the size of this stack exceeds the maximum 6414 /// number of recursive template instantiations, construction 6415 /// produces an error and evaluates true. 6416 /// 6417 /// Destruction of this object will pop the named instantiation off 6418 /// the stack. 6419 struct InstantiatingTemplate { 6420 /// \brief Note that we are instantiating a class template, 6421 /// function template, or a member thereof. 6422 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6423 Decl *Entity, 6424 SourceRange InstantiationRange = SourceRange()); 6425 6426 struct ExceptionSpecification {}; 6427 /// \brief Note that we are instantiating an exception specification 6428 /// of a function template. 6429 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6430 FunctionDecl *Entity, ExceptionSpecification, 6431 SourceRange InstantiationRange = SourceRange()); 6432 6433 /// \brief Note that we are instantiating a default argument in a 6434 /// template-id. 6435 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6436 TemplateDecl *Template, 6437 ArrayRef<TemplateArgument> TemplateArgs, 6438 SourceRange InstantiationRange = SourceRange()); 6439 6440 /// \brief Note that we are instantiating a default argument in a 6441 /// template-id. 6442 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6443 FunctionTemplateDecl *FunctionTemplate, 6444 ArrayRef<TemplateArgument> TemplateArgs, 6445 ActiveTemplateInstantiation::InstantiationKind Kind, 6446 sema::TemplateDeductionInfo &DeductionInfo, 6447 SourceRange InstantiationRange = SourceRange()); 6448 6449 /// \brief Note that we are instantiating as part of template 6450 /// argument deduction for a class template partial 6451 /// specialization. 6452 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6453 ClassTemplatePartialSpecializationDecl *PartialSpec, 6454 ArrayRef<TemplateArgument> TemplateArgs, 6455 sema::TemplateDeductionInfo &DeductionInfo, 6456 SourceRange InstantiationRange = SourceRange()); 6457 6458 /// \brief Note that we are instantiating as part of template 6459 /// argument deduction for a variable template partial 6460 /// specialization. 6461 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6462 VarTemplatePartialSpecializationDecl *PartialSpec, 6463 ArrayRef<TemplateArgument> TemplateArgs, 6464 sema::TemplateDeductionInfo &DeductionInfo, 6465 SourceRange InstantiationRange = SourceRange()); 6466 6467 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6468 ParmVarDecl *Param, 6469 ArrayRef<TemplateArgument> TemplateArgs, 6470 SourceRange InstantiationRange = SourceRange()); 6471 6472 /// \brief Note that we are substituting prior template arguments into a 6473 /// non-type parameter. 6474 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6475 NamedDecl *Template, 6476 NonTypeTemplateParmDecl *Param, 6477 ArrayRef<TemplateArgument> TemplateArgs, 6478 SourceRange InstantiationRange); 6479 6480 /// \brief Note that we are substituting prior template arguments into a 6481 /// template template parameter. 6482 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6483 NamedDecl *Template, 6484 TemplateTemplateParmDecl *Param, 6485 ArrayRef<TemplateArgument> TemplateArgs, 6486 SourceRange InstantiationRange); 6487 6488 /// \brief Note that we are checking the default template argument 6489 /// against the template parameter for a given template-id. 6490 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6491 TemplateDecl *Template, 6492 NamedDecl *Param, 6493 ArrayRef<TemplateArgument> TemplateArgs, 6494 SourceRange InstantiationRange); 6495 6496 6497 /// \brief Note that we have finished instantiating this template. 6498 void Clear(); 6499 ~InstantiatingTemplateInstantiatingTemplate6500 ~InstantiatingTemplate() { Clear(); } 6501 6502 /// \brief Determines whether we have exceeded the maximum 6503 /// recursive template instantiations. isInvalidInstantiatingTemplate6504 bool isInvalid() const { return Invalid; } 6505 6506 private: 6507 Sema &SemaRef; 6508 bool Invalid; 6509 bool SavedInNonInstantiationSFINAEContext; 6510 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, 6511 SourceRange InstantiationRange); 6512 6513 InstantiatingTemplate( 6514 Sema &SemaRef, ActiveTemplateInstantiation::InstantiationKind Kind, 6515 SourceLocation PointOfInstantiation, SourceRange InstantiationRange, 6516 Decl *Entity, NamedDecl *Template = nullptr, 6517 ArrayRef<TemplateArgument> TemplateArgs = ArrayRef<TemplateArgument>(), 6518 sema::TemplateDeductionInfo *DeductionInfo = nullptr); 6519 6520 InstantiatingTemplate(const InstantiatingTemplate&) = delete; 6521 6522 InstantiatingTemplate& 6523 operator=(const InstantiatingTemplate&) = delete; 6524 }; 6525 6526 void PrintInstantiationStack(); 6527 6528 /// \brief Determines whether we are currently in a context where 6529 /// template argument substitution failures are not considered 6530 /// errors. 6531 /// 6532 /// \returns An empty \c Optional if we're not in a SFINAE context. 6533 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest 6534 /// template-deduction context object, which can be used to capture 6535 /// diagnostics that will be suppressed. 6536 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; 6537 6538 /// \brief Determines whether we are currently in a context that 6539 /// is not evaluated as per C++ [expr] p5. isUnevaluatedContext()6540 bool isUnevaluatedContext() const { 6541 assert(!ExprEvalContexts.empty() && 6542 "Must be in an expression evaluation context"); 6543 return ExprEvalContexts.back().isUnevaluated(); 6544 } 6545 6546 /// \brief RAII class used to determine whether SFINAE has 6547 /// trapped any errors that occur during template argument 6548 /// deduction. 6549 class SFINAETrap { 6550 Sema &SemaRef; 6551 unsigned PrevSFINAEErrors; 6552 bool PrevInNonInstantiationSFINAEContext; 6553 bool PrevAccessCheckingSFINAE; 6554 6555 public: 6556 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) SemaRef(SemaRef)6557 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), 6558 PrevInNonInstantiationSFINAEContext( 6559 SemaRef.InNonInstantiationSFINAEContext), 6560 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE) 6561 { 6562 if (!SemaRef.isSFINAEContext()) 6563 SemaRef.InNonInstantiationSFINAEContext = true; 6564 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; 6565 } 6566 ~SFINAETrap()6567 ~SFINAETrap() { 6568 SemaRef.NumSFINAEErrors = PrevSFINAEErrors; 6569 SemaRef.InNonInstantiationSFINAEContext 6570 = PrevInNonInstantiationSFINAEContext; 6571 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; 6572 } 6573 6574 /// \brief Determine whether any SFINAE errors have been trapped. hasErrorOccurred()6575 bool hasErrorOccurred() const { 6576 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; 6577 } 6578 }; 6579 6580 /// \brief RAII class used to indicate that we are performing provisional 6581 /// semantic analysis to determine the validity of a construct, so 6582 /// typo-correction and diagnostics in the immediate context (not within 6583 /// implicitly-instantiated templates) should be suppressed. 6584 class TentativeAnalysisScope { 6585 Sema &SemaRef; 6586 // FIXME: Using a SFINAETrap for this is a hack. 6587 SFINAETrap Trap; 6588 bool PrevDisableTypoCorrection; 6589 public: TentativeAnalysisScope(Sema & SemaRef)6590 explicit TentativeAnalysisScope(Sema &SemaRef) 6591 : SemaRef(SemaRef), Trap(SemaRef, true), 6592 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) { 6593 SemaRef.DisableTypoCorrection = true; 6594 } ~TentativeAnalysisScope()6595 ~TentativeAnalysisScope() { 6596 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection; 6597 } 6598 }; 6599 6600 /// \brief The current instantiation scope used to store local 6601 /// variables. 6602 LocalInstantiationScope *CurrentInstantiationScope; 6603 6604 /// \brief Tracks whether we are in a context where typo correction is 6605 /// disabled. 6606 bool DisableTypoCorrection; 6607 6608 /// \brief The number of typos corrected by CorrectTypo. 6609 unsigned TyposCorrected; 6610 6611 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet; 6612 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations; 6613 6614 /// \brief A cache containing identifiers for which typo correction failed and 6615 /// their locations, so that repeated attempts to correct an identifier in a 6616 /// given location are ignored if typo correction already failed for it. 6617 IdentifierSourceLocations TypoCorrectionFailures; 6618 6619 /// \brief Worker object for performing CFG-based warnings. 6620 sema::AnalysisBasedWarnings AnalysisWarnings; 6621 threadSafety::BeforeSet *ThreadSafetyDeclCache; 6622 6623 /// \brief An entity for which implicit template instantiation is required. 6624 /// 6625 /// The source location associated with the declaration is the first place in 6626 /// the source code where the declaration was "used". It is not necessarily 6627 /// the point of instantiation (which will be either before or after the 6628 /// namespace-scope declaration that triggered this implicit instantiation), 6629 /// However, it is the location that diagnostics should generally refer to, 6630 /// because users will need to know what code triggered the instantiation. 6631 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; 6632 6633 /// \brief The queue of implicit template instantiations that are required 6634 /// but have not yet been performed. 6635 std::deque<PendingImplicitInstantiation> PendingInstantiations; 6636 6637 class SavePendingInstantiationsAndVTableUsesRAII { 6638 public: SavePendingInstantiationsAndVTableUsesRAII(Sema & S,bool Enabled)6639 SavePendingInstantiationsAndVTableUsesRAII(Sema &S, bool Enabled) 6640 : S(S), Enabled(Enabled) { 6641 if (!Enabled) return; 6642 6643 SavedPendingInstantiations.swap(S.PendingInstantiations); 6644 SavedVTableUses.swap(S.VTableUses); 6645 } 6646 ~SavePendingInstantiationsAndVTableUsesRAII()6647 ~SavePendingInstantiationsAndVTableUsesRAII() { 6648 if (!Enabled) return; 6649 6650 // Restore the set of pending vtables. 6651 assert(S.VTableUses.empty() && 6652 "VTableUses should be empty before it is discarded."); 6653 S.VTableUses.swap(SavedVTableUses); 6654 6655 // Restore the set of pending implicit instantiations. 6656 assert(S.PendingInstantiations.empty() && 6657 "PendingInstantiations should be empty before it is discarded."); 6658 S.PendingInstantiations.swap(SavedPendingInstantiations); 6659 } 6660 6661 private: 6662 Sema &S; 6663 SmallVector<VTableUse, 16> SavedVTableUses; 6664 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; 6665 bool Enabled; 6666 }; 6667 6668 /// \brief The queue of implicit template instantiations that are required 6669 /// and must be performed within the current local scope. 6670 /// 6671 /// This queue is only used for member functions of local classes in 6672 /// templates, which must be instantiated in the same scope as their 6673 /// enclosing function, so that they can reference function-local 6674 /// types, static variables, enumerators, etc. 6675 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; 6676 6677 class SavePendingLocalImplicitInstantiationsRAII { 6678 public: SavePendingLocalImplicitInstantiationsRAII(Sema & S)6679 SavePendingLocalImplicitInstantiationsRAII(Sema &S): S(S) { 6680 SavedPendingLocalImplicitInstantiations.swap( 6681 S.PendingLocalImplicitInstantiations); 6682 } 6683 ~SavePendingLocalImplicitInstantiationsRAII()6684 ~SavePendingLocalImplicitInstantiationsRAII() { 6685 assert(S.PendingLocalImplicitInstantiations.empty() && 6686 "there shouldn't be any pending local implicit instantiations"); 6687 SavedPendingLocalImplicitInstantiations.swap( 6688 S.PendingLocalImplicitInstantiations); 6689 } 6690 6691 private: 6692 Sema &S; 6693 std::deque<PendingImplicitInstantiation> 6694 SavedPendingLocalImplicitInstantiations; 6695 }; 6696 6697 void PerformPendingInstantiations(bool LocalOnly = false); 6698 6699 TypeSourceInfo *SubstType(TypeSourceInfo *T, 6700 const MultiLevelTemplateArgumentList &TemplateArgs, 6701 SourceLocation Loc, DeclarationName Entity); 6702 6703 QualType SubstType(QualType T, 6704 const MultiLevelTemplateArgumentList &TemplateArgs, 6705 SourceLocation Loc, DeclarationName Entity); 6706 6707 TypeSourceInfo *SubstType(TypeLoc TL, 6708 const MultiLevelTemplateArgumentList &TemplateArgs, 6709 SourceLocation Loc, DeclarationName Entity); 6710 6711 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, 6712 const MultiLevelTemplateArgumentList &TemplateArgs, 6713 SourceLocation Loc, 6714 DeclarationName Entity, 6715 CXXRecordDecl *ThisContext, 6716 unsigned ThisTypeQuals); 6717 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, 6718 const MultiLevelTemplateArgumentList &Args); 6719 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, 6720 const MultiLevelTemplateArgumentList &TemplateArgs, 6721 int indexAdjustment, 6722 Optional<unsigned> NumExpansions, 6723 bool ExpectParameterPack); 6724 bool SubstParmTypes(SourceLocation Loc, 6725 ParmVarDecl **Params, unsigned NumParams, 6726 const MultiLevelTemplateArgumentList &TemplateArgs, 6727 SmallVectorImpl<QualType> &ParamTypes, 6728 SmallVectorImpl<ParmVarDecl *> *OutParams = nullptr); 6729 ExprResult SubstExpr(Expr *E, 6730 const MultiLevelTemplateArgumentList &TemplateArgs); 6731 6732 /// \brief Substitute the given template arguments into a list of 6733 /// expressions, expanding pack expansions if required. 6734 /// 6735 /// \param Exprs The list of expressions to substitute into. 6736 /// 6737 /// \param NumExprs The number of expressions in \p Exprs. 6738 /// 6739 /// \param IsCall Whether this is some form of call, in which case 6740 /// default arguments will be dropped. 6741 /// 6742 /// \param TemplateArgs The set of template arguments to substitute. 6743 /// 6744 /// \param Outputs Will receive all of the substituted arguments. 6745 /// 6746 /// \returns true if an error occurred, false otherwise. 6747 bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall, 6748 const MultiLevelTemplateArgumentList &TemplateArgs, 6749 SmallVectorImpl<Expr *> &Outputs); 6750 6751 StmtResult SubstStmt(Stmt *S, 6752 const MultiLevelTemplateArgumentList &TemplateArgs); 6753 6754 Decl *SubstDecl(Decl *D, DeclContext *Owner, 6755 const MultiLevelTemplateArgumentList &TemplateArgs); 6756 6757 ExprResult SubstInitializer(Expr *E, 6758 const MultiLevelTemplateArgumentList &TemplateArgs, 6759 bool CXXDirectInit); 6760 6761 bool 6762 SubstBaseSpecifiers(CXXRecordDecl *Instantiation, 6763 CXXRecordDecl *Pattern, 6764 const MultiLevelTemplateArgumentList &TemplateArgs); 6765 6766 bool 6767 InstantiateClass(SourceLocation PointOfInstantiation, 6768 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, 6769 const MultiLevelTemplateArgumentList &TemplateArgs, 6770 TemplateSpecializationKind TSK, 6771 bool Complain = true); 6772 6773 bool InstantiateEnum(SourceLocation PointOfInstantiation, 6774 EnumDecl *Instantiation, EnumDecl *Pattern, 6775 const MultiLevelTemplateArgumentList &TemplateArgs, 6776 TemplateSpecializationKind TSK); 6777 6778 bool InstantiateInClassInitializer( 6779 SourceLocation PointOfInstantiation, FieldDecl *Instantiation, 6780 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); 6781 6782 struct LateInstantiatedAttribute { 6783 const Attr *TmplAttr; 6784 LocalInstantiationScope *Scope; 6785 Decl *NewDecl; 6786 LateInstantiatedAttributeLateInstantiatedAttribute6787 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, 6788 Decl *D) 6789 : TmplAttr(A), Scope(S), NewDecl(D) 6790 { } 6791 }; 6792 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; 6793 6794 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, 6795 const Decl *Pattern, Decl *Inst, 6796 LateInstantiatedAttrVec *LateAttrs = nullptr, 6797 LocalInstantiationScope *OuterMostScope = nullptr); 6798 6799 bool 6800 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, 6801 ClassTemplateSpecializationDecl *ClassTemplateSpec, 6802 TemplateSpecializationKind TSK, 6803 bool Complain = true); 6804 6805 void InstantiateClassMembers(SourceLocation PointOfInstantiation, 6806 CXXRecordDecl *Instantiation, 6807 const MultiLevelTemplateArgumentList &TemplateArgs, 6808 TemplateSpecializationKind TSK); 6809 6810 void InstantiateClassTemplateSpecializationMembers( 6811 SourceLocation PointOfInstantiation, 6812 ClassTemplateSpecializationDecl *ClassTemplateSpec, 6813 TemplateSpecializationKind TSK); 6814 6815 NestedNameSpecifierLoc 6816 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 6817 const MultiLevelTemplateArgumentList &TemplateArgs); 6818 6819 DeclarationNameInfo 6820 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 6821 const MultiLevelTemplateArgumentList &TemplateArgs); 6822 TemplateName 6823 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, 6824 SourceLocation Loc, 6825 const MultiLevelTemplateArgumentList &TemplateArgs); 6826 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, 6827 TemplateArgumentListInfo &Result, 6828 const MultiLevelTemplateArgumentList &TemplateArgs); 6829 6830 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, 6831 FunctionDecl *Function); 6832 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 6833 FunctionDecl *Function, 6834 bool Recursive = false, 6835 bool DefinitionRequired = false); 6836 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation( 6837 VarTemplateDecl *VarTemplate, VarDecl *FromVar, 6838 const TemplateArgumentList &TemplateArgList, 6839 const TemplateArgumentListInfo &TemplateArgsInfo, 6840 SmallVectorImpl<TemplateArgument> &Converted, 6841 SourceLocation PointOfInstantiation, void *InsertPos, 6842 LateInstantiatedAttrVec *LateAttrs = nullptr, 6843 LocalInstantiationScope *StartingScope = nullptr); 6844 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl( 6845 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, 6846 const MultiLevelTemplateArgumentList &TemplateArgs); 6847 void 6848 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, 6849 const MultiLevelTemplateArgumentList &TemplateArgs, 6850 LateInstantiatedAttrVec *LateAttrs, 6851 DeclContext *Owner, 6852 LocalInstantiationScope *StartingScope, 6853 bool InstantiatingVarTemplate = false); 6854 void InstantiateVariableInitializer( 6855 VarDecl *Var, VarDecl *OldVar, 6856 const MultiLevelTemplateArgumentList &TemplateArgs); 6857 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, 6858 VarDecl *Var, bool Recursive = false, 6859 bool DefinitionRequired = false); 6860 void InstantiateStaticDataMemberDefinition( 6861 SourceLocation PointOfInstantiation, 6862 VarDecl *Var, 6863 bool Recursive = false, 6864 bool DefinitionRequired = false); 6865 6866 void InstantiateMemInitializers(CXXConstructorDecl *New, 6867 const CXXConstructorDecl *Tmpl, 6868 const MultiLevelTemplateArgumentList &TemplateArgs); 6869 6870 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 6871 const MultiLevelTemplateArgumentList &TemplateArgs); 6872 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, 6873 const MultiLevelTemplateArgumentList &TemplateArgs); 6874 6875 // Objective-C declarations. 6876 enum ObjCContainerKind { 6877 OCK_None = -1, 6878 OCK_Interface = 0, 6879 OCK_Protocol, 6880 OCK_Category, 6881 OCK_ClassExtension, 6882 OCK_Implementation, 6883 OCK_CategoryImplementation 6884 }; 6885 ObjCContainerKind getObjCContainerKind() const; 6886 6887 Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc, 6888 IdentifierInfo *ClassName, 6889 SourceLocation ClassLoc, 6890 IdentifierInfo *SuperName, 6891 SourceLocation SuperLoc, 6892 Decl * const *ProtoRefs, 6893 unsigned NumProtoRefs, 6894 const SourceLocation *ProtoLocs, 6895 SourceLocation EndProtoLoc, 6896 AttributeList *AttrList); 6897 6898 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, 6899 IdentifierInfo *SuperName, 6900 SourceLocation SuperLoc); 6901 6902 Decl *ActOnCompatibilityAlias( 6903 SourceLocation AtCompatibilityAliasLoc, 6904 IdentifierInfo *AliasName, SourceLocation AliasLocation, 6905 IdentifierInfo *ClassName, SourceLocation ClassLocation); 6906 6907 bool CheckForwardProtocolDeclarationForCircularDependency( 6908 IdentifierInfo *PName, 6909 SourceLocation &PLoc, SourceLocation PrevLoc, 6910 const ObjCList<ObjCProtocolDecl> &PList); 6911 6912 Decl *ActOnStartProtocolInterface( 6913 SourceLocation AtProtoInterfaceLoc, 6914 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, 6915 Decl * const *ProtoRefNames, unsigned NumProtoRefs, 6916 const SourceLocation *ProtoLocs, 6917 SourceLocation EndProtoLoc, 6918 AttributeList *AttrList); 6919 6920 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc, 6921 IdentifierInfo *ClassName, 6922 SourceLocation ClassLoc, 6923 IdentifierInfo *CategoryName, 6924 SourceLocation CategoryLoc, 6925 Decl * const *ProtoRefs, 6926 unsigned NumProtoRefs, 6927 const SourceLocation *ProtoLocs, 6928 SourceLocation EndProtoLoc); 6929 6930 Decl *ActOnStartClassImplementation( 6931 SourceLocation AtClassImplLoc, 6932 IdentifierInfo *ClassName, SourceLocation ClassLoc, 6933 IdentifierInfo *SuperClassname, 6934 SourceLocation SuperClassLoc); 6935 6936 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, 6937 IdentifierInfo *ClassName, 6938 SourceLocation ClassLoc, 6939 IdentifierInfo *CatName, 6940 SourceLocation CatLoc); 6941 6942 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, 6943 ArrayRef<Decl *> Decls); 6944 6945 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, 6946 IdentifierInfo **IdentList, 6947 SourceLocation *IdentLocs, 6948 unsigned NumElts); 6949 6950 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, 6951 const IdentifierLocPair *IdentList, 6952 unsigned NumElts, 6953 AttributeList *attrList); 6954 6955 void FindProtocolDeclaration(bool WarnOnDeclarations, 6956 const IdentifierLocPair *ProtocolId, 6957 unsigned NumProtocols, 6958 SmallVectorImpl<Decl *> &Protocols); 6959 6960 /// Ensure attributes are consistent with type. 6961 /// \param [in, out] Attributes The attributes to check; they will 6962 /// be modified to be consistent with \p PropertyTy. 6963 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, 6964 SourceLocation Loc, 6965 unsigned &Attributes, 6966 bool propertyInPrimaryClass); 6967 6968 /// Process the specified property declaration and create decls for the 6969 /// setters and getters as needed. 6970 /// \param property The property declaration being processed 6971 /// \param CD The semantic container for the property 6972 /// \param redeclaredProperty Declaration for property if redeclared 6973 /// in class extension. 6974 /// \param lexicalDC Container for redeclaredProperty. 6975 void ProcessPropertyDecl(ObjCPropertyDecl *property, 6976 ObjCContainerDecl *CD, 6977 ObjCPropertyDecl *redeclaredProperty = nullptr, 6978 ObjCContainerDecl *lexicalDC = nullptr); 6979 6980 6981 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, 6982 ObjCPropertyDecl *SuperProperty, 6983 const IdentifierInfo *Name, 6984 bool OverridingProtocolProperty); 6985 6986 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, 6987 ObjCInterfaceDecl *ID); 6988 6989 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, 6990 ArrayRef<Decl *> allMethods = None, 6991 ArrayRef<DeclGroupPtrTy> allTUVars = None); 6992 6993 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, 6994 SourceLocation LParenLoc, 6995 FieldDeclarator &FD, ObjCDeclSpec &ODS, 6996 Selector GetterSel, Selector SetterSel, 6997 bool *OverridingProperty, 6998 tok::ObjCKeywordKind MethodImplKind, 6999 DeclContext *lexicalDC = nullptr); 7000 7001 Decl *ActOnPropertyImplDecl(Scope *S, 7002 SourceLocation AtLoc, 7003 SourceLocation PropertyLoc, 7004 bool ImplKind, 7005 IdentifierInfo *PropertyId, 7006 IdentifierInfo *PropertyIvar, 7007 SourceLocation PropertyIvarLoc); 7008 7009 enum ObjCSpecialMethodKind { 7010 OSMK_None, 7011 OSMK_Alloc, 7012 OSMK_New, 7013 OSMK_Copy, 7014 OSMK_RetainingInit, 7015 OSMK_NonRetainingInit 7016 }; 7017 7018 struct ObjCArgInfo { 7019 IdentifierInfo *Name; 7020 SourceLocation NameLoc; 7021 // The Type is null if no type was specified, and the DeclSpec is invalid 7022 // in this case. 7023 ParsedType Type; 7024 ObjCDeclSpec DeclSpec; 7025 7026 /// ArgAttrs - Attribute list for this argument. 7027 AttributeList *ArgAttrs; 7028 }; 7029 7030 Decl *ActOnMethodDeclaration( 7031 Scope *S, 7032 SourceLocation BeginLoc, // location of the + or -. 7033 SourceLocation EndLoc, // location of the ; or {. 7034 tok::TokenKind MethodType, 7035 ObjCDeclSpec &ReturnQT, ParsedType ReturnType, 7036 ArrayRef<SourceLocation> SelectorLocs, Selector Sel, 7037 // optional arguments. The number of types/arguments is obtained 7038 // from the Sel.getNumArgs(). 7039 ObjCArgInfo *ArgInfo, 7040 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args 7041 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind, 7042 bool isVariadic, bool MethodDefinition); 7043 7044 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, 7045 const ObjCObjectPointerType *OPT, 7046 bool IsInstance); 7047 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, 7048 bool IsInstance); 7049 7050 bool CheckARCMethodDecl(ObjCMethodDecl *method); 7051 bool inferObjCARCLifetime(ValueDecl *decl); 7052 7053 ExprResult 7054 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, 7055 Expr *BaseExpr, 7056 SourceLocation OpLoc, 7057 DeclarationName MemberName, 7058 SourceLocation MemberLoc, 7059 SourceLocation SuperLoc, QualType SuperType, 7060 bool Super); 7061 7062 ExprResult 7063 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, 7064 IdentifierInfo &propertyName, 7065 SourceLocation receiverNameLoc, 7066 SourceLocation propertyNameLoc); 7067 7068 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); 7069 7070 /// \brief Describes the kind of message expression indicated by a message 7071 /// send that starts with an identifier. 7072 enum ObjCMessageKind { 7073 /// \brief The message is sent to 'super'. 7074 ObjCSuperMessage, 7075 /// \brief The message is an instance message. 7076 ObjCInstanceMessage, 7077 /// \brief The message is a class message, and the identifier is a type 7078 /// name. 7079 ObjCClassMessage 7080 }; 7081 7082 ObjCMessageKind getObjCMessageKind(Scope *S, 7083 IdentifierInfo *Name, 7084 SourceLocation NameLoc, 7085 bool IsSuper, 7086 bool HasTrailingDot, 7087 ParsedType &ReceiverType); 7088 7089 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, 7090 Selector Sel, 7091 SourceLocation LBracLoc, 7092 ArrayRef<SourceLocation> SelectorLocs, 7093 SourceLocation RBracLoc, 7094 MultiExprArg Args); 7095 7096 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, 7097 QualType ReceiverType, 7098 SourceLocation SuperLoc, 7099 Selector Sel, 7100 ObjCMethodDecl *Method, 7101 SourceLocation LBracLoc, 7102 ArrayRef<SourceLocation> SelectorLocs, 7103 SourceLocation RBracLoc, 7104 MultiExprArg Args, 7105 bool isImplicit = false); 7106 7107 ExprResult BuildClassMessageImplicit(QualType ReceiverType, 7108 bool isSuperReceiver, 7109 SourceLocation Loc, 7110 Selector Sel, 7111 ObjCMethodDecl *Method, 7112 MultiExprArg Args); 7113 7114 ExprResult ActOnClassMessage(Scope *S, 7115 ParsedType Receiver, 7116 Selector Sel, 7117 SourceLocation LBracLoc, 7118 ArrayRef<SourceLocation> SelectorLocs, 7119 SourceLocation RBracLoc, 7120 MultiExprArg Args); 7121 7122 ExprResult BuildInstanceMessage(Expr *Receiver, 7123 QualType ReceiverType, 7124 SourceLocation SuperLoc, 7125 Selector Sel, 7126 ObjCMethodDecl *Method, 7127 SourceLocation LBracLoc, 7128 ArrayRef<SourceLocation> SelectorLocs, 7129 SourceLocation RBracLoc, 7130 MultiExprArg Args, 7131 bool isImplicit = false); 7132 7133 ExprResult BuildInstanceMessageImplicit(Expr *Receiver, 7134 QualType ReceiverType, 7135 SourceLocation Loc, 7136 Selector Sel, 7137 ObjCMethodDecl *Method, 7138 MultiExprArg Args); 7139 7140 ExprResult ActOnInstanceMessage(Scope *S, 7141 Expr *Receiver, 7142 Selector Sel, 7143 SourceLocation LBracLoc, 7144 ArrayRef<SourceLocation> SelectorLocs, 7145 SourceLocation RBracLoc, 7146 MultiExprArg Args); 7147 7148 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, 7149 ObjCBridgeCastKind Kind, 7150 SourceLocation BridgeKeywordLoc, 7151 TypeSourceInfo *TSInfo, 7152 Expr *SubExpr); 7153 7154 ExprResult ActOnObjCBridgedCast(Scope *S, 7155 SourceLocation LParenLoc, 7156 ObjCBridgeCastKind Kind, 7157 SourceLocation BridgeKeywordLoc, 7158 ParsedType Type, 7159 SourceLocation RParenLoc, 7160 Expr *SubExpr); 7161 7162 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr); 7163 7164 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr); 7165 7166 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, 7167 CastKind &Kind); 7168 7169 bool checkObjCBridgeRelatedComponents(SourceLocation Loc, 7170 QualType DestType, QualType SrcType, 7171 ObjCInterfaceDecl *&RelatedClass, 7172 ObjCMethodDecl *&ClassMethod, 7173 ObjCMethodDecl *&InstanceMethod, 7174 TypedefNameDecl *&TDNDecl, 7175 bool CfToNs); 7176 7177 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, 7178 QualType DestType, QualType SrcType, 7179 Expr *&SrcExpr); 7180 7181 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr); 7182 7183 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); 7184 7185 /// \brief Check whether the given new method is a valid override of the 7186 /// given overridden method, and set any properties that should be inherited. 7187 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, 7188 const ObjCMethodDecl *Overridden); 7189 7190 /// \brief Describes the compatibility of a result type with its method. 7191 enum ResultTypeCompatibilityKind { 7192 RTC_Compatible, 7193 RTC_Incompatible, 7194 RTC_Unknown 7195 }; 7196 7197 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, 7198 ObjCInterfaceDecl *CurrentClass, 7199 ResultTypeCompatibilityKind RTC); 7200 7201 enum PragmaOptionsAlignKind { 7202 POAK_Native, // #pragma options align=native 7203 POAK_Natural, // #pragma options align=natural 7204 POAK_Packed, // #pragma options align=packed 7205 POAK_Power, // #pragma options align=power 7206 POAK_Mac68k, // #pragma options align=mac68k 7207 POAK_Reset // #pragma options align=reset 7208 }; 7209 7210 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. 7211 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, 7212 SourceLocation PragmaLoc); 7213 7214 enum PragmaPackKind { 7215 PPK_Default, // #pragma pack([n]) 7216 PPK_Show, // #pragma pack(show), only supported by MSVC. 7217 PPK_Push, // #pragma pack(push, [identifier], [n]) 7218 PPK_Pop // #pragma pack(pop, [identifier], [n]) 7219 }; 7220 7221 enum PragmaMSStructKind { 7222 PMSST_OFF, // #pragms ms_struct off 7223 PMSST_ON // #pragms ms_struct on 7224 }; 7225 7226 enum PragmaMSCommentKind { 7227 PCK_Unknown, 7228 PCK_Linker, // #pragma comment(linker, ...) 7229 PCK_Lib, // #pragma comment(lib, ...) 7230 PCK_Compiler, // #pragma comment(compiler, ...) 7231 PCK_ExeStr, // #pragma comment(exestr, ...) 7232 PCK_User // #pragma comment(user, ...) 7233 }; 7234 7235 /// ActOnPragmaPack - Called on well formed \#pragma pack(...). 7236 void ActOnPragmaPack(PragmaPackKind Kind, 7237 IdentifierInfo *Name, 7238 Expr *Alignment, 7239 SourceLocation PragmaLoc, 7240 SourceLocation LParenLoc, 7241 SourceLocation RParenLoc); 7242 7243 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. 7244 void ActOnPragmaMSStruct(PragmaMSStructKind Kind); 7245 7246 /// ActOnPragmaMSComment - Called on well formed 7247 /// \#pragma comment(kind, "arg"). 7248 void ActOnPragmaMSComment(PragmaMSCommentKind Kind, StringRef Arg); 7249 7250 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma 7251 /// pointers_to_members(representation method[, general purpose 7252 /// representation]). 7253 void ActOnPragmaMSPointersToMembers( 7254 LangOptions::PragmaMSPointersToMembersKind Kind, 7255 SourceLocation PragmaLoc); 7256 7257 /// \brief Called on well formed \#pragma vtordisp(). 7258 void ActOnPragmaMSVtorDisp(PragmaVtorDispKind Kind, SourceLocation PragmaLoc, 7259 MSVtorDispAttr::Mode Value); 7260 7261 enum PragmaSectionKind { 7262 PSK_DataSeg, 7263 PSK_BSSSeg, 7264 PSK_ConstSeg, 7265 PSK_CodeSeg, 7266 }; 7267 7268 bool UnifySection(StringRef SectionName, 7269 int SectionFlags, 7270 DeclaratorDecl *TheDecl); 7271 bool UnifySection(StringRef SectionName, 7272 int SectionFlags, 7273 SourceLocation PragmaSectionLocation); 7274 7275 /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg. 7276 void ActOnPragmaMSSeg(SourceLocation PragmaLocation, 7277 PragmaMsStackAction Action, 7278 llvm::StringRef StackSlotLabel, 7279 StringLiteral *SegmentName, 7280 llvm::StringRef PragmaName); 7281 7282 /// \brief Called on well formed \#pragma section(). 7283 void ActOnPragmaMSSection(SourceLocation PragmaLocation, 7284 int SectionFlags, StringLiteral *SegmentName); 7285 7286 /// \brief Called on well-formed \#pragma init_seg(). 7287 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, 7288 StringLiteral *SegmentName); 7289 7290 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch 7291 void ActOnPragmaDetectMismatch(StringRef Name, StringRef Value); 7292 7293 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. 7294 void ActOnPragmaUnused(const Token &Identifier, 7295 Scope *curScope, 7296 SourceLocation PragmaLoc); 7297 7298 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . 7299 void ActOnPragmaVisibility(const IdentifierInfo* VisType, 7300 SourceLocation PragmaLoc); 7301 7302 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, 7303 SourceLocation Loc); 7304 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); 7305 7306 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. 7307 void ActOnPragmaWeakID(IdentifierInfo* WeakName, 7308 SourceLocation PragmaLoc, 7309 SourceLocation WeakNameLoc); 7310 7311 /// ActOnPragmaRedefineExtname - Called on well formed 7312 /// \#pragma redefine_extname oldname newname. 7313 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, 7314 IdentifierInfo* AliasName, 7315 SourceLocation PragmaLoc, 7316 SourceLocation WeakNameLoc, 7317 SourceLocation AliasNameLoc); 7318 7319 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. 7320 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, 7321 IdentifierInfo* AliasName, 7322 SourceLocation PragmaLoc, 7323 SourceLocation WeakNameLoc, 7324 SourceLocation AliasNameLoc); 7325 7326 /// ActOnPragmaFPContract - Called on well formed 7327 /// \#pragma {STDC,OPENCL} FP_CONTRACT 7328 void ActOnPragmaFPContract(tok::OnOffSwitch OOS); 7329 7330 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to 7331 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. 7332 void AddAlignmentAttributesForRecord(RecordDecl *RD); 7333 7334 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. 7335 void AddMsStructLayoutForRecord(RecordDecl *RD); 7336 7337 /// FreePackedContext - Deallocate and null out PackContext. 7338 void FreePackedContext(); 7339 7340 /// PushNamespaceVisibilityAttr - Note that we've entered a 7341 /// namespace with a visibility attribute. 7342 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, 7343 SourceLocation Loc); 7344 7345 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, 7346 /// add an appropriate visibility attribute. 7347 void AddPushedVisibilityAttribute(Decl *RD); 7348 7349 /// PopPragmaVisibility - Pop the top element of the visibility stack; used 7350 /// for '\#pragma GCC visibility' and visibility attributes on namespaces. 7351 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); 7352 7353 /// FreeVisContext - Deallocate and null out VisContext. 7354 void FreeVisContext(); 7355 7356 /// AddCFAuditedAttribute - Check whether we're currently within 7357 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding 7358 /// the appropriate attribute. 7359 void AddCFAuditedAttribute(Decl *D); 7360 7361 /// \brief Called on well formed \#pragma clang optimize. 7362 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); 7363 7364 /// \brief Get the location for the currently active "\#pragma clang optimize 7365 /// off". If this location is invalid, then the state of the pragma is "on". getOptimizeOffPragmaLocation()7366 SourceLocation getOptimizeOffPragmaLocation() const { 7367 return OptimizeOffPragmaLocation; 7368 } 7369 7370 /// \brief Only called on function definitions; if there is a pragma in scope 7371 /// with the effect of a range-based optnone, consider marking the function 7372 /// with attribute optnone. 7373 void AddRangeBasedOptnone(FunctionDecl *FD); 7374 7375 /// \brief Adds the 'optnone' attribute to the function declaration if there 7376 /// are no conflicts; Loc represents the location causing the 'optnone' 7377 /// attribute to be added (usually because of a pragma). 7378 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc); 7379 7380 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. 7381 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, 7382 unsigned SpellingListIndex, bool IsPackExpansion); 7383 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T, 7384 unsigned SpellingListIndex, bool IsPackExpansion); 7385 7386 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular 7387 /// declaration. 7388 void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE, 7389 unsigned SpellingListIndex); 7390 7391 /// AddAlignValueAttr - Adds an align_value attribute to a particular 7392 /// declaration. 7393 void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E, 7394 unsigned SpellingListIndex); 7395 7396 // OpenMP directives and clauses. 7397 private: 7398 void *VarDataSharingAttributesStack; 7399 /// \brief Initialization of data-sharing attributes stack. 7400 void InitDataSharingAttributesStack(); 7401 void DestroyDataSharingAttributesStack(); 7402 ExprResult VerifyPositiveIntegerConstantInClause(Expr *Op, 7403 OpenMPClauseKind CKind); 7404 /// \brief Checks if the specified variable is used in one of the private 7405 /// clauses in OpenMP constructs. 7406 bool IsOpenMPCapturedVar(VarDecl *VD); 7407 7408 public: 7409 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc, 7410 Expr *Op); 7411 /// \brief Called on start of new data sharing attribute block. 7412 void StartOpenMPDSABlock(OpenMPDirectiveKind K, 7413 const DeclarationNameInfo &DirName, Scope *CurScope, 7414 SourceLocation Loc); 7415 /// \brief Called on end of data sharing attribute block. 7416 void EndOpenMPDSABlock(Stmt *CurDirective); 7417 7418 // OpenMP directives and clauses. 7419 /// \brief Called on correct id-expression from the '#pragma omp 7420 /// threadprivate'. 7421 ExprResult ActOnOpenMPIdExpression(Scope *CurScope, 7422 CXXScopeSpec &ScopeSpec, 7423 const DeclarationNameInfo &Id); 7424 /// \brief Called on well-formed '#pragma omp threadprivate'. 7425 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective( 7426 SourceLocation Loc, 7427 ArrayRef<Expr *> VarList); 7428 /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness. 7429 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl( 7430 SourceLocation Loc, 7431 ArrayRef<Expr *> VarList); 7432 7433 /// \brief Initialization of captured region for OpenMP region. 7434 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope); 7435 /// \brief End of OpenMP region. 7436 /// 7437 /// \param S Statement associated with the current OpenMP region. 7438 /// \param Clauses List of clauses for the current OpenMP region. 7439 /// 7440 /// \returns Statement for finished OpenMP region. 7441 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses); 7442 StmtResult ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind, 7443 const DeclarationNameInfo &DirName, 7444 ArrayRef<OMPClause *> Clauses, 7445 Stmt *AStmt, 7446 SourceLocation StartLoc, 7447 SourceLocation EndLoc); 7448 /// \brief Called on well-formed '\#pragma omp parallel' after parsing 7449 /// of the associated statement. 7450 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 7451 Stmt *AStmt, 7452 SourceLocation StartLoc, 7453 SourceLocation EndLoc); 7454 /// \brief Called on well-formed '\#pragma omp simd' after parsing 7455 /// of the associated statement. 7456 StmtResult ActOnOpenMPSimdDirective( 7457 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7458 SourceLocation EndLoc, 7459 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA); 7460 /// \brief Called on well-formed '\#pragma omp for' after parsing 7461 /// of the associated statement. 7462 StmtResult ActOnOpenMPForDirective( 7463 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7464 SourceLocation EndLoc, 7465 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA); 7466 /// \brief Called on well-formed '\#pragma omp for simd' after parsing 7467 /// of the associated statement. 7468 StmtResult ActOnOpenMPForSimdDirective( 7469 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7470 SourceLocation EndLoc, 7471 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA); 7472 /// \brief Called on well-formed '\#pragma omp sections' after parsing 7473 /// of the associated statement. 7474 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 7475 Stmt *AStmt, SourceLocation StartLoc, 7476 SourceLocation EndLoc); 7477 /// \brief Called on well-formed '\#pragma omp section' after parsing of the 7478 /// associated statement. 7479 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc, 7480 SourceLocation EndLoc); 7481 /// \brief Called on well-formed '\#pragma omp single' after parsing of the 7482 /// associated statement. 7483 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 7484 Stmt *AStmt, SourceLocation StartLoc, 7485 SourceLocation EndLoc); 7486 /// \brief Called on well-formed '\#pragma omp master' after parsing of the 7487 /// associated statement. 7488 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc, 7489 SourceLocation EndLoc); 7490 /// \brief Called on well-formed '\#pragma omp critical' after parsing of the 7491 /// associated statement. 7492 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, 7493 Stmt *AStmt, SourceLocation StartLoc, 7494 SourceLocation EndLoc); 7495 /// \brief Called on well-formed '\#pragma omp parallel for' after parsing 7496 /// of the associated statement. 7497 StmtResult ActOnOpenMPParallelForDirective( 7498 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7499 SourceLocation EndLoc, 7500 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA); 7501 /// \brief Called on well-formed '\#pragma omp parallel for simd' after 7502 /// parsing of the associated statement. 7503 StmtResult ActOnOpenMPParallelForSimdDirective( 7504 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7505 SourceLocation EndLoc, 7506 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA); 7507 /// \brief Called on well-formed '\#pragma omp parallel sections' after 7508 /// parsing of the associated statement. 7509 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 7510 Stmt *AStmt, 7511 SourceLocation StartLoc, 7512 SourceLocation EndLoc); 7513 /// \brief Called on well-formed '\#pragma omp task' after parsing of the 7514 /// associated statement. 7515 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 7516 Stmt *AStmt, SourceLocation StartLoc, 7517 SourceLocation EndLoc); 7518 /// \brief Called on well-formed '\#pragma omp taskyield'. 7519 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 7520 SourceLocation EndLoc); 7521 /// \brief Called on well-formed '\#pragma omp barrier'. 7522 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 7523 SourceLocation EndLoc); 7524 /// \brief Called on well-formed '\#pragma omp taskwait'. 7525 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 7526 SourceLocation EndLoc); 7527 /// \brief Called on well-formed '\#pragma omp flush'. 7528 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 7529 SourceLocation StartLoc, 7530 SourceLocation EndLoc); 7531 /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the 7532 /// associated statement. 7533 StmtResult ActOnOpenMPOrderedDirective(Stmt *AStmt, SourceLocation StartLoc, 7534 SourceLocation EndLoc); 7535 /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the 7536 /// associated statement. 7537 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 7538 Stmt *AStmt, SourceLocation StartLoc, 7539 SourceLocation EndLoc); 7540 /// \brief Called on well-formed '\#pragma omp target' after parsing of the 7541 /// associated statement. 7542 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 7543 Stmt *AStmt, SourceLocation StartLoc, 7544 SourceLocation EndLoc); 7545 /// \brief Called on well-formed '\#pragma omp teams' after parsing of the 7546 /// associated statement. 7547 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 7548 Stmt *AStmt, SourceLocation StartLoc, 7549 SourceLocation EndLoc); 7550 7551 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, 7552 Expr *Expr, 7553 SourceLocation StartLoc, 7554 SourceLocation LParenLoc, 7555 SourceLocation EndLoc); 7556 /// \brief Called on well-formed 'if' clause. 7557 OMPClause *ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc, 7558 SourceLocation LParenLoc, 7559 SourceLocation EndLoc); 7560 /// \brief Called on well-formed 'final' clause. 7561 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc, 7562 SourceLocation LParenLoc, 7563 SourceLocation EndLoc); 7564 /// \brief Called on well-formed 'num_threads' clause. 7565 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads, 7566 SourceLocation StartLoc, 7567 SourceLocation LParenLoc, 7568 SourceLocation EndLoc); 7569 /// \brief Called on well-formed 'safelen' clause. 7570 OMPClause *ActOnOpenMPSafelenClause(Expr *Length, 7571 SourceLocation StartLoc, 7572 SourceLocation LParenLoc, 7573 SourceLocation EndLoc); 7574 /// \brief Called on well-formed 'collapse' clause. 7575 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops, 7576 SourceLocation StartLoc, 7577 SourceLocation LParenLoc, 7578 SourceLocation EndLoc); 7579 7580 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind, 7581 unsigned Argument, 7582 SourceLocation ArgumentLoc, 7583 SourceLocation StartLoc, 7584 SourceLocation LParenLoc, 7585 SourceLocation EndLoc); 7586 /// \brief Called on well-formed 'default' clause. 7587 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, 7588 SourceLocation KindLoc, 7589 SourceLocation StartLoc, 7590 SourceLocation LParenLoc, 7591 SourceLocation EndLoc); 7592 /// \brief Called on well-formed 'proc_bind' clause. 7593 OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, 7594 SourceLocation KindLoc, 7595 SourceLocation StartLoc, 7596 SourceLocation LParenLoc, 7597 SourceLocation EndLoc); 7598 7599 OMPClause *ActOnOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind, 7600 unsigned Argument, Expr *Expr, 7601 SourceLocation StartLoc, 7602 SourceLocation LParenLoc, 7603 SourceLocation ArgumentLoc, 7604 SourceLocation CommaLoc, 7605 SourceLocation EndLoc); 7606 /// \brief Called on well-formed 'schedule' clause. 7607 OMPClause *ActOnOpenMPScheduleClause(OpenMPScheduleClauseKind Kind, 7608 Expr *ChunkSize, SourceLocation StartLoc, 7609 SourceLocation LParenLoc, 7610 SourceLocation KindLoc, 7611 SourceLocation CommaLoc, 7612 SourceLocation EndLoc); 7613 7614 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc, 7615 SourceLocation EndLoc); 7616 /// \brief Called on well-formed 'ordered' clause. 7617 OMPClause *ActOnOpenMPOrderedClause(SourceLocation StartLoc, 7618 SourceLocation EndLoc); 7619 /// \brief Called on well-formed 'nowait' clause. 7620 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc, 7621 SourceLocation EndLoc); 7622 /// \brief Called on well-formed 'untied' clause. 7623 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc, 7624 SourceLocation EndLoc); 7625 /// \brief Called on well-formed 'mergeable' clause. 7626 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc, 7627 SourceLocation EndLoc); 7628 /// \brief Called on well-formed 'read' clause. 7629 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc, 7630 SourceLocation EndLoc); 7631 /// \brief Called on well-formed 'write' clause. 7632 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc, 7633 SourceLocation EndLoc); 7634 /// \brief Called on well-formed 'update' clause. 7635 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc, 7636 SourceLocation EndLoc); 7637 /// \brief Called on well-formed 'capture' clause. 7638 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc, 7639 SourceLocation EndLoc); 7640 /// \brief Called on well-formed 'seq_cst' clause. 7641 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 7642 SourceLocation EndLoc); 7643 7644 OMPClause * 7645 ActOnOpenMPVarListClause(OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, 7646 Expr *TailExpr, SourceLocation StartLoc, 7647 SourceLocation LParenLoc, SourceLocation ColonLoc, 7648 SourceLocation EndLoc, 7649 CXXScopeSpec &ReductionIdScopeSpec, 7650 const DeclarationNameInfo &ReductionId); 7651 /// \brief Called on well-formed 'private' clause. 7652 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 7653 SourceLocation StartLoc, 7654 SourceLocation LParenLoc, 7655 SourceLocation EndLoc); 7656 /// \brief Called on well-formed 'firstprivate' clause. 7657 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 7658 SourceLocation StartLoc, 7659 SourceLocation LParenLoc, 7660 SourceLocation EndLoc); 7661 /// \brief Called on well-formed 'lastprivate' clause. 7662 OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, 7663 SourceLocation StartLoc, 7664 SourceLocation LParenLoc, 7665 SourceLocation EndLoc); 7666 /// \brief Called on well-formed 'shared' clause. 7667 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 7668 SourceLocation StartLoc, 7669 SourceLocation LParenLoc, 7670 SourceLocation EndLoc); 7671 /// \brief Called on well-formed 'reduction' clause. 7672 OMPClause * 7673 ActOnOpenMPReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, 7674 SourceLocation LParenLoc, SourceLocation ColonLoc, 7675 SourceLocation EndLoc, 7676 CXXScopeSpec &ReductionIdScopeSpec, 7677 const DeclarationNameInfo &ReductionId); 7678 /// \brief Called on well-formed 'linear' clause. 7679 OMPClause *ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, 7680 Expr *Step, 7681 SourceLocation StartLoc, 7682 SourceLocation LParenLoc, 7683 SourceLocation ColonLoc, 7684 SourceLocation EndLoc); 7685 /// \brief Called on well-formed 'aligned' clause. 7686 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList, 7687 Expr *Alignment, 7688 SourceLocation StartLoc, 7689 SourceLocation LParenLoc, 7690 SourceLocation ColonLoc, 7691 SourceLocation EndLoc); 7692 /// \brief Called on well-formed 'copyin' clause. 7693 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 7694 SourceLocation StartLoc, 7695 SourceLocation LParenLoc, 7696 SourceLocation EndLoc); 7697 /// \brief Called on well-formed 'copyprivate' clause. 7698 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 7699 SourceLocation StartLoc, 7700 SourceLocation LParenLoc, 7701 SourceLocation EndLoc); 7702 /// \brief Called on well-formed 'flush' pseudo clause. 7703 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 7704 SourceLocation StartLoc, 7705 SourceLocation LParenLoc, 7706 SourceLocation EndLoc); 7707 7708 /// \brief The kind of conversion being performed. 7709 enum CheckedConversionKind { 7710 /// \brief An implicit conversion. 7711 CCK_ImplicitConversion, 7712 /// \brief A C-style cast. 7713 CCK_CStyleCast, 7714 /// \brief A functional-style cast. 7715 CCK_FunctionalCast, 7716 /// \brief A cast other than a C-style cast. 7717 CCK_OtherCast 7718 }; 7719 7720 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit 7721 /// cast. If there is already an implicit cast, merge into the existing one. 7722 /// If isLvalue, the result of the cast is an lvalue. 7723 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, 7724 ExprValueKind VK = VK_RValue, 7725 const CXXCastPath *BasePath = nullptr, 7726 CheckedConversionKind CCK 7727 = CCK_ImplicitConversion); 7728 7729 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding 7730 /// to the conversion from scalar type ScalarTy to the Boolean type. 7731 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); 7732 7733 /// IgnoredValueConversions - Given that an expression's result is 7734 /// syntactically ignored, perform any conversions that are 7735 /// required. 7736 ExprResult IgnoredValueConversions(Expr *E); 7737 7738 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts 7739 // functions and arrays to their respective pointers (C99 6.3.2.1). 7740 ExprResult UsualUnaryConversions(Expr *E); 7741 7742 /// CallExprUnaryConversions - a special case of an unary conversion 7743 /// performed on a function designator of a call expression. 7744 ExprResult CallExprUnaryConversions(Expr *E); 7745 7746 // DefaultFunctionArrayConversion - converts functions and arrays 7747 // to their respective pointers (C99 6.3.2.1). 7748 ExprResult DefaultFunctionArrayConversion(Expr *E); 7749 7750 // DefaultFunctionArrayLvalueConversion - converts functions and 7751 // arrays to their respective pointers and performs the 7752 // lvalue-to-rvalue conversion. 7753 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E); 7754 7755 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on 7756 // the operand. This is DefaultFunctionArrayLvalueConversion, 7757 // except that it assumes the operand isn't of function or array 7758 // type. 7759 ExprResult DefaultLvalueConversion(Expr *E); 7760 7761 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 7762 // do not have a prototype. Integer promotions are performed on each 7763 // argument, and arguments that have type float are promoted to double. 7764 ExprResult DefaultArgumentPromotion(Expr *E); 7765 7766 // Used for emitting the right warning by DefaultVariadicArgumentPromotion 7767 enum VariadicCallType { 7768 VariadicFunction, 7769 VariadicBlock, 7770 VariadicMethod, 7771 VariadicConstructor, 7772 VariadicDoesNotApply 7773 }; 7774 7775 VariadicCallType getVariadicCallType(FunctionDecl *FDecl, 7776 const FunctionProtoType *Proto, 7777 Expr *Fn); 7778 7779 // Used for determining in which context a type is allowed to be passed to a 7780 // vararg function. 7781 enum VarArgKind { 7782 VAK_Valid, 7783 VAK_ValidInCXX11, 7784 VAK_Undefined, 7785 VAK_MSVCUndefined, 7786 VAK_Invalid 7787 }; 7788 7789 // Determines which VarArgKind fits an expression. 7790 VarArgKind isValidVarArgType(const QualType &Ty); 7791 7792 /// Check to see if the given expression is a valid argument to a variadic 7793 /// function, issuing a diagnostic if not. 7794 void checkVariadicArgument(const Expr *E, VariadicCallType CT); 7795 7796 /// Check to see if a given expression could have '.c_str()' called on it. 7797 bool hasCStrMethod(const Expr *E); 7798 7799 /// GatherArgumentsForCall - Collector argument expressions for various 7800 /// form of call prototypes. 7801 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 7802 const FunctionProtoType *Proto, 7803 unsigned FirstParam, ArrayRef<Expr *> Args, 7804 SmallVectorImpl<Expr *> &AllArgs, 7805 VariadicCallType CallType = VariadicDoesNotApply, 7806 bool AllowExplicit = false, 7807 bool IsListInitialization = false); 7808 7809 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 7810 // will create a runtime trap if the resulting type is not a POD type. 7811 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 7812 FunctionDecl *FDecl); 7813 7814 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's 7815 // operands and then handles various conversions that are common to binary 7816 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this 7817 // routine returns the first non-arithmetic type found. The client is 7818 // responsible for emitting appropriate error diagnostics. 7819 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 7820 bool IsCompAssign = false); 7821 7822 /// AssignConvertType - All of the 'assignment' semantic checks return this 7823 /// enum to indicate whether the assignment was allowed. These checks are 7824 /// done for simple assignments, as well as initialization, return from 7825 /// function, argument passing, etc. The query is phrased in terms of a 7826 /// source and destination type. 7827 enum AssignConvertType { 7828 /// Compatible - the types are compatible according to the standard. 7829 Compatible, 7830 7831 /// PointerToInt - The assignment converts a pointer to an int, which we 7832 /// accept as an extension. 7833 PointerToInt, 7834 7835 /// IntToPointer - The assignment converts an int to a pointer, which we 7836 /// accept as an extension. 7837 IntToPointer, 7838 7839 /// FunctionVoidPointer - The assignment is between a function pointer and 7840 /// void*, which the standard doesn't allow, but we accept as an extension. 7841 FunctionVoidPointer, 7842 7843 /// IncompatiblePointer - The assignment is between two pointers types that 7844 /// are not compatible, but we accept them as an extension. 7845 IncompatiblePointer, 7846 7847 /// IncompatiblePointer - The assignment is between two pointers types which 7848 /// point to integers which have a different sign, but are otherwise 7849 /// identical. This is a subset of the above, but broken out because it's by 7850 /// far the most common case of incompatible pointers. 7851 IncompatiblePointerSign, 7852 7853 /// CompatiblePointerDiscardsQualifiers - The assignment discards 7854 /// c/v/r qualifiers, which we accept as an extension. 7855 CompatiblePointerDiscardsQualifiers, 7856 7857 /// IncompatiblePointerDiscardsQualifiers - The assignment 7858 /// discards qualifiers that we don't permit to be discarded, 7859 /// like address spaces. 7860 IncompatiblePointerDiscardsQualifiers, 7861 7862 /// IncompatibleNestedPointerQualifiers - The assignment is between two 7863 /// nested pointer types, and the qualifiers other than the first two 7864 /// levels differ e.g. char ** -> const char **, but we accept them as an 7865 /// extension. 7866 IncompatibleNestedPointerQualifiers, 7867 7868 /// IncompatibleVectors - The assignment is between two vector types that 7869 /// have the same size, which we accept as an extension. 7870 IncompatibleVectors, 7871 7872 /// IntToBlockPointer - The assignment converts an int to a block 7873 /// pointer. We disallow this. 7874 IntToBlockPointer, 7875 7876 /// IncompatibleBlockPointer - The assignment is between two block 7877 /// pointers types that are not compatible. 7878 IncompatibleBlockPointer, 7879 7880 /// IncompatibleObjCQualifiedId - The assignment is between a qualified 7881 /// id type and something else (that is incompatible with it). For example, 7882 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. 7883 IncompatibleObjCQualifiedId, 7884 7885 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an 7886 /// object with __weak qualifier. 7887 IncompatibleObjCWeakRef, 7888 7889 /// Incompatible - We reject this conversion outright, it is invalid to 7890 /// represent it in the AST. 7891 Incompatible 7892 }; 7893 7894 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the 7895 /// assignment conversion type specified by ConvTy. This returns true if the 7896 /// conversion was invalid or false if the conversion was accepted. 7897 bool DiagnoseAssignmentResult(AssignConvertType ConvTy, 7898 SourceLocation Loc, 7899 QualType DstType, QualType SrcType, 7900 Expr *SrcExpr, AssignmentAction Action, 7901 bool *Complained = nullptr); 7902 7903 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag 7904 /// enum. If AllowMask is true, then we also allow the complement of a valid 7905 /// value, to be used as a mask. 7906 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 7907 bool AllowMask) const; 7908 7909 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant 7910 /// integer not in the range of enum values. 7911 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, 7912 Expr *SrcExpr); 7913 7914 /// CheckAssignmentConstraints - Perform type checking for assignment, 7915 /// argument passing, variable initialization, and function return values. 7916 /// C99 6.5.16. 7917 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, 7918 QualType LHSType, 7919 QualType RHSType); 7920 7921 /// Check assignment constraints and prepare for a conversion of the 7922 /// RHS to the LHS type. 7923 AssignConvertType CheckAssignmentConstraints(QualType LHSType, 7924 ExprResult &RHS, 7925 CastKind &Kind); 7926 7927 // CheckSingleAssignmentConstraints - Currently used by 7928 // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking, 7929 // this routine performs the default function/array converions. 7930 AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, 7931 ExprResult &RHS, 7932 bool Diagnose = true, 7933 bool DiagnoseCFAudited = false); 7934 7935 // \brief If the lhs type is a transparent union, check whether we 7936 // can initialize the transparent union with the given expression. 7937 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, 7938 ExprResult &RHS); 7939 7940 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); 7941 7942 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); 7943 7944 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 7945 AssignmentAction Action, 7946 bool AllowExplicit = false); 7947 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 7948 AssignmentAction Action, 7949 bool AllowExplicit, 7950 ImplicitConversionSequence& ICS); 7951 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 7952 const ImplicitConversionSequence& ICS, 7953 AssignmentAction Action, 7954 CheckedConversionKind CCK 7955 = CCK_ImplicitConversion); 7956 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 7957 const StandardConversionSequence& SCS, 7958 AssignmentAction Action, 7959 CheckedConversionKind CCK); 7960 7961 /// the following "Check" methods will return a valid/converted QualType 7962 /// or a null QualType (indicating an error diagnostic was issued). 7963 7964 /// type checking binary operators (subroutines of CreateBuiltinBinOp). 7965 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7966 ExprResult &RHS); 7967 QualType CheckPointerToMemberOperands( // C++ 5.5 7968 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, 7969 SourceLocation OpLoc, bool isIndirect); 7970 QualType CheckMultiplyDivideOperands( // C99 6.5.5 7971 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, 7972 bool IsDivide); 7973 QualType CheckRemainderOperands( // C99 6.5.5 7974 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 7975 bool IsCompAssign = false); 7976 QualType CheckAdditionOperands( // C99 6.5.6 7977 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 7978 QualType* CompLHSTy = nullptr); 7979 QualType CheckSubtractionOperands( // C99 6.5.6 7980 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 7981 QualType* CompLHSTy = nullptr); 7982 QualType CheckShiftOperands( // C99 6.5.7 7983 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 7984 bool IsCompAssign = false); 7985 QualType CheckCompareOperands( // C99 6.5.8/9 7986 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc, 7987 bool isRelational); 7988 QualType CheckBitwiseOperands( // C99 6.5.[10...12] 7989 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 7990 bool IsCompAssign = false); 7991 QualType CheckLogicalOperands( // C99 6.5.[13,14] 7992 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc); 7993 // CheckAssignmentOperands is used for both simple and compound assignment. 7994 // For simple assignment, pass both expressions and a null converted type. 7995 // For compound assignment, pass both expressions and the converted type. 7996 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] 7997 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); 7998 7999 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, 8000 UnaryOperatorKind Opcode, Expr *Op); 8001 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, 8002 BinaryOperatorKind Opcode, 8003 Expr *LHS, Expr *RHS); 8004 ExprResult checkPseudoObjectRValue(Expr *E); 8005 Expr *recreateSyntacticForm(PseudoObjectExpr *E); 8006 8007 QualType CheckConditionalOperands( // C99 6.5.15 8008 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, 8009 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); 8010 QualType CXXCheckConditionalOperands( // C++ 5.16 8011 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, 8012 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); 8013 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, 8014 bool *NonStandardCompositeType = nullptr); 8015 QualType FindCompositePointerType(SourceLocation Loc, 8016 ExprResult &E1, ExprResult &E2, 8017 bool *NonStandardCompositeType = nullptr) { 8018 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get(); 8019 QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, 8020 NonStandardCompositeType); 8021 E1 = E1Tmp; 8022 E2 = E2Tmp; 8023 return Composite; 8024 } 8025 8026 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8027 SourceLocation QuestionLoc); 8028 8029 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 8030 SourceLocation QuestionLoc); 8031 8032 void DiagnoseAlwaysNonNullPointer(Expr *E, 8033 Expr::NullPointerConstantKind NullType, 8034 bool IsEqual, SourceRange Range); 8035 8036 /// type checking for vector binary operators. 8037 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8038 SourceLocation Loc, bool IsCompAssign); 8039 QualType GetSignedVectorType(QualType V); 8040 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 8041 SourceLocation Loc, bool isRelational); 8042 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 8043 SourceLocation Loc); 8044 8045 bool isLaxVectorConversion(QualType srcType, QualType destType); 8046 8047 /// type checking declaration initializers (C99 6.7.8) 8048 bool CheckForConstantInitializer(Expr *e, QualType t); 8049 8050 // type checking C++ declaration initializers (C++ [dcl.init]). 8051 8052 /// ReferenceCompareResult - Expresses the result of comparing two 8053 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the 8054 /// purposes of initialization by reference (C++ [dcl.init.ref]p4). 8055 enum ReferenceCompareResult { 8056 /// Ref_Incompatible - The two types are incompatible, so direct 8057 /// reference binding is not possible. 8058 Ref_Incompatible = 0, 8059 /// Ref_Related - The two types are reference-related, which means 8060 /// that their unqualified forms (T1 and T2) are either the same 8061 /// or T1 is a base class of T2. 8062 Ref_Related, 8063 /// Ref_Compatible_With_Added_Qualification - The two types are 8064 /// reference-compatible with added qualification, meaning that 8065 /// they are reference-compatible and the qualifiers on T1 (cv1) 8066 /// are greater than the qualifiers on T2 (cv2). 8067 Ref_Compatible_With_Added_Qualification, 8068 /// Ref_Compatible - The two types are reference-compatible and 8069 /// have equivalent qualifiers (cv1 == cv2). 8070 Ref_Compatible 8071 }; 8072 8073 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, 8074 QualType T1, QualType T2, 8075 bool &DerivedToBase, 8076 bool &ObjCConversion, 8077 bool &ObjCLifetimeConversion); 8078 8079 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 8080 Expr *CastExpr, CastKind &CastKind, 8081 ExprValueKind &VK, CXXCastPath &Path); 8082 8083 /// \brief Force an expression with unknown-type to an expression of the 8084 /// given type. 8085 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); 8086 8087 /// \brief Type-check an expression that's being passed to an 8088 /// __unknown_anytype parameter. 8089 ExprResult checkUnknownAnyArg(SourceLocation callLoc, 8090 Expr *result, QualType ¶mType); 8091 8092 // CheckVectorCast - check type constraints for vectors. 8093 // Since vectors are an extension, there are no C standard reference for this. 8094 // We allow casting between vectors and integer datatypes of the same size. 8095 // returns true if the cast is invalid 8096 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 8097 CastKind &Kind); 8098 8099 // CheckExtVectorCast - check type constraints for extended vectors. 8100 // Since vectors are an extension, there are no C standard reference for this. 8101 // We allow casting between vectors and integer datatypes of the same size, 8102 // or vectors and the element type of that vector. 8103 // returns the cast expr 8104 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, 8105 CastKind &Kind); 8106 8107 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, 8108 SourceLocation LParenLoc, 8109 Expr *CastExpr, 8110 SourceLocation RParenLoc); 8111 8112 enum ARCConversionResult { ACR_okay, ACR_unbridged }; 8113 8114 /// \brief Checks for invalid conversions and casts between 8115 /// retainable pointers and other pointer kinds. 8116 ARCConversionResult CheckObjCARCConversion(SourceRange castRange, 8117 QualType castType, Expr *&op, 8118 CheckedConversionKind CCK, 8119 bool DiagnoseCFAudited = false, 8120 BinaryOperatorKind Opc = BO_PtrMemD 8121 ); 8122 8123 Expr *stripARCUnbridgedCast(Expr *e); 8124 void diagnoseARCUnbridgedCast(Expr *e); 8125 8126 bool CheckObjCARCUnavailableWeakConversion(QualType castType, 8127 QualType ExprType); 8128 8129 /// checkRetainCycles - Check whether an Objective-C message send 8130 /// might create an obvious retain cycle. 8131 void checkRetainCycles(ObjCMessageExpr *msg); 8132 void checkRetainCycles(Expr *receiver, Expr *argument); 8133 void checkRetainCycles(VarDecl *Var, Expr *Init); 8134 8135 /// checkUnsafeAssigns - Check whether +1 expr is being assigned 8136 /// to weak/__unsafe_unretained type. 8137 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); 8138 8139 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned 8140 /// to weak/__unsafe_unretained expression. 8141 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); 8142 8143 /// CheckMessageArgumentTypes - Check types in an Obj-C message send. 8144 /// \param Method - May be null. 8145 /// \param [out] ReturnType - The return type of the send. 8146 /// \return true iff there were any incompatible types. 8147 bool CheckMessageArgumentTypes(QualType ReceiverType, 8148 MultiExprArg Args, Selector Sel, 8149 ArrayRef<SourceLocation> SelectorLocs, 8150 ObjCMethodDecl *Method, bool isClassMessage, 8151 bool isSuperMessage, 8152 SourceLocation lbrac, SourceLocation rbrac, 8153 SourceRange RecRange, 8154 QualType &ReturnType, ExprValueKind &VK); 8155 8156 /// \brief Determine the result of a message send expression based on 8157 /// the type of the receiver, the method expected to receive the message, 8158 /// and the form of the message send. 8159 QualType getMessageSendResultType(QualType ReceiverType, 8160 ObjCMethodDecl *Method, 8161 bool isClassMessage, bool isSuperMessage); 8162 8163 /// \brief If the given expression involves a message send to a method 8164 /// with a related result type, emit a note describing what happened. 8165 void EmitRelatedResultTypeNote(const Expr *E); 8166 8167 /// \brief Given that we had incompatible pointer types in a return 8168 /// statement, check whether we're in a method with a related result 8169 /// type, and if so, emit a note describing what happened. 8170 void EmitRelatedResultTypeNoteForReturn(QualType destType); 8171 8172 /// CheckBooleanCondition - Diagnose problems involving the use of 8173 /// the given expression as a boolean condition (e.g. in an if 8174 /// statement). Also performs the standard function and array 8175 /// decays, possibly changing the input variable. 8176 /// 8177 /// \param Loc - A location associated with the condition, e.g. the 8178 /// 'if' keyword. 8179 /// \return true iff there were any errors 8180 ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc); 8181 8182 ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc, 8183 Expr *SubExpr); 8184 8185 /// DiagnoseAssignmentAsCondition - Given that an expression is 8186 /// being used as a boolean condition, warn if it's an assignment. 8187 void DiagnoseAssignmentAsCondition(Expr *E); 8188 8189 /// \brief Redundant parentheses over an equality comparison can indicate 8190 /// that the user intended an assignment used as condition. 8191 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); 8192 8193 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. 8194 ExprResult CheckCXXBooleanCondition(Expr *CondExpr); 8195 8196 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 8197 /// the specified width and sign. If an overflow occurs, detect it and emit 8198 /// the specified diagnostic. 8199 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, 8200 unsigned NewWidth, bool NewSign, 8201 SourceLocation Loc, unsigned DiagID); 8202 8203 /// Checks that the Objective-C declaration is declared in the global scope. 8204 /// Emits an error and marks the declaration as invalid if it's not declared 8205 /// in the global scope. 8206 bool CheckObjCDeclScope(Decl *D); 8207 8208 /// \brief Abstract base class used for diagnosing integer constant 8209 /// expression violations. 8210 class VerifyICEDiagnoser { 8211 public: 8212 bool Suppress; 8213 Suppress(Suppress)8214 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } 8215 8216 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0; 8217 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR); ~VerifyICEDiagnoser()8218 virtual ~VerifyICEDiagnoser() { } 8219 }; 8220 8221 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, 8222 /// and reports the appropriate diagnostics. Returns false on success. 8223 /// Can optionally return the value of the expression. 8224 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 8225 VerifyICEDiagnoser &Diagnoser, 8226 bool AllowFold = true); 8227 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 8228 unsigned DiagID, 8229 bool AllowFold = true); 8230 ExprResult VerifyIntegerConstantExpression(Expr *E, 8231 llvm::APSInt *Result = nullptr); 8232 8233 /// VerifyBitField - verifies that a bit field expression is an ICE and has 8234 /// the correct width, and that the field type is valid. 8235 /// Returns false on success. 8236 /// Can optionally return whether the bit-field is of width 0 8237 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 8238 QualType FieldTy, bool IsMsStruct, 8239 Expr *BitWidth, bool *ZeroWidth = nullptr); 8240 8241 enum CUDAFunctionTarget { 8242 CFT_Device, 8243 CFT_Global, 8244 CFT_Host, 8245 CFT_HostDevice, 8246 CFT_InvalidTarget 8247 }; 8248 8249 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D); 8250 8251 bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee); 8252 8253 /// Given a implicit special member, infer its CUDA target from the 8254 /// calls it needs to make to underlying base/field special members. 8255 /// \param ClassDecl the class for which the member is being created. 8256 /// \param CSM the kind of special member. 8257 /// \param MemberDecl the special member itself. 8258 /// \param ConstRHS true if this is a copy operation with a const object on 8259 /// its RHS. 8260 /// \param Diagnose true if this call should emit diagnostics. 8261 /// \return true if there was an error inferring. 8262 /// The result of this call is implicit CUDA target attribute(s) attached to 8263 /// the member declaration. 8264 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, 8265 CXXSpecialMember CSM, 8266 CXXMethodDecl *MemberDecl, 8267 bool ConstRHS, 8268 bool Diagnose); 8269 8270 /// \name Code completion 8271 //@{ 8272 /// \brief Describes the context in which code completion occurs. 8273 enum ParserCompletionContext { 8274 /// \brief Code completion occurs at top-level or namespace context. 8275 PCC_Namespace, 8276 /// \brief Code completion occurs within a class, struct, or union. 8277 PCC_Class, 8278 /// \brief Code completion occurs within an Objective-C interface, protocol, 8279 /// or category. 8280 PCC_ObjCInterface, 8281 /// \brief Code completion occurs within an Objective-C implementation or 8282 /// category implementation 8283 PCC_ObjCImplementation, 8284 /// \brief Code completion occurs within the list of instance variables 8285 /// in an Objective-C interface, protocol, category, or implementation. 8286 PCC_ObjCInstanceVariableList, 8287 /// \brief Code completion occurs following one or more template 8288 /// headers. 8289 PCC_Template, 8290 /// \brief Code completion occurs following one or more template 8291 /// headers within a class. 8292 PCC_MemberTemplate, 8293 /// \brief Code completion occurs within an expression. 8294 PCC_Expression, 8295 /// \brief Code completion occurs within a statement, which may 8296 /// also be an expression or a declaration. 8297 PCC_Statement, 8298 /// \brief Code completion occurs at the beginning of the 8299 /// initialization statement (or expression) in a for loop. 8300 PCC_ForInit, 8301 /// \brief Code completion occurs within the condition of an if, 8302 /// while, switch, or for statement. 8303 PCC_Condition, 8304 /// \brief Code completion occurs within the body of a function on a 8305 /// recovery path, where we do not have a specific handle on our position 8306 /// in the grammar. 8307 PCC_RecoveryInFunction, 8308 /// \brief Code completion occurs where only a type is permitted. 8309 PCC_Type, 8310 /// \brief Code completion occurs in a parenthesized expression, which 8311 /// might also be a type cast. 8312 PCC_ParenthesizedExpression, 8313 /// \brief Code completion occurs within a sequence of declaration 8314 /// specifiers within a function, method, or block. 8315 PCC_LocalDeclarationSpecifiers 8316 }; 8317 8318 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); 8319 void CodeCompleteOrdinaryName(Scope *S, 8320 ParserCompletionContext CompletionContext); 8321 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, 8322 bool AllowNonIdentifiers, 8323 bool AllowNestedNameSpecifiers); 8324 8325 struct CodeCompleteExpressionData; 8326 void CodeCompleteExpression(Scope *S, 8327 const CodeCompleteExpressionData &Data); 8328 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, 8329 SourceLocation OpLoc, 8330 bool IsArrow); 8331 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS); 8332 void CodeCompleteTag(Scope *S, unsigned TagSpec); 8333 void CodeCompleteTypeQualifiers(DeclSpec &DS); 8334 void CodeCompleteCase(Scope *S); 8335 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args); 8336 void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc, 8337 ArrayRef<Expr *> Args); 8338 void CodeCompleteInitializer(Scope *S, Decl *D); 8339 void CodeCompleteReturn(Scope *S); 8340 void CodeCompleteAfterIf(Scope *S); 8341 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS); 8342 8343 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, 8344 bool EnteringContext); 8345 void CodeCompleteUsing(Scope *S); 8346 void CodeCompleteUsingDirective(Scope *S); 8347 void CodeCompleteNamespaceDecl(Scope *S); 8348 void CodeCompleteNamespaceAliasDecl(Scope *S); 8349 void CodeCompleteOperatorName(Scope *S); 8350 void CodeCompleteConstructorInitializer( 8351 Decl *Constructor, 8352 ArrayRef<CXXCtorInitializer *> Initializers); 8353 8354 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, 8355 bool AfterAmpersand); 8356 8357 void CodeCompleteObjCAtDirective(Scope *S); 8358 void CodeCompleteObjCAtVisibility(Scope *S); 8359 void CodeCompleteObjCAtStatement(Scope *S); 8360 void CodeCompleteObjCAtExpression(Scope *S); 8361 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); 8362 void CodeCompleteObjCPropertyGetter(Scope *S); 8363 void CodeCompleteObjCPropertySetter(Scope *S); 8364 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, 8365 bool IsParameter); 8366 void CodeCompleteObjCMessageReceiver(Scope *S); 8367 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, 8368 ArrayRef<IdentifierInfo *> SelIdents, 8369 bool AtArgumentExpression); 8370 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, 8371 ArrayRef<IdentifierInfo *> SelIdents, 8372 bool AtArgumentExpression, 8373 bool IsSuper = false); 8374 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, 8375 ArrayRef<IdentifierInfo *> SelIdents, 8376 bool AtArgumentExpression, 8377 ObjCInterfaceDecl *Super = nullptr); 8378 void CodeCompleteObjCForCollection(Scope *S, 8379 DeclGroupPtrTy IterationVar); 8380 void CodeCompleteObjCSelector(Scope *S, 8381 ArrayRef<IdentifierInfo *> SelIdents); 8382 void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols, 8383 unsigned NumProtocols); 8384 void CodeCompleteObjCProtocolDecl(Scope *S); 8385 void CodeCompleteObjCInterfaceDecl(Scope *S); 8386 void CodeCompleteObjCSuperclass(Scope *S, 8387 IdentifierInfo *ClassName, 8388 SourceLocation ClassNameLoc); 8389 void CodeCompleteObjCImplementationDecl(Scope *S); 8390 void CodeCompleteObjCInterfaceCategory(Scope *S, 8391 IdentifierInfo *ClassName, 8392 SourceLocation ClassNameLoc); 8393 void CodeCompleteObjCImplementationCategory(Scope *S, 8394 IdentifierInfo *ClassName, 8395 SourceLocation ClassNameLoc); 8396 void CodeCompleteObjCPropertyDefinition(Scope *S); 8397 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, 8398 IdentifierInfo *PropertyName); 8399 void CodeCompleteObjCMethodDecl(Scope *S, 8400 bool IsInstanceMethod, 8401 ParsedType ReturnType); 8402 void CodeCompleteObjCMethodDeclSelector(Scope *S, 8403 bool IsInstanceMethod, 8404 bool AtParameterName, 8405 ParsedType ReturnType, 8406 ArrayRef<IdentifierInfo *> SelIdents); 8407 void CodeCompletePreprocessorDirective(bool InConditional); 8408 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); 8409 void CodeCompletePreprocessorMacroName(bool IsDefinition); 8410 void CodeCompletePreprocessorExpression(); 8411 void CodeCompletePreprocessorMacroArgument(Scope *S, 8412 IdentifierInfo *Macro, 8413 MacroInfo *MacroInfo, 8414 unsigned Argument); 8415 void CodeCompleteNaturalLanguage(); 8416 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, 8417 CodeCompletionTUInfo &CCTUInfo, 8418 SmallVectorImpl<CodeCompletionResult> &Results); 8419 //@} 8420 8421 //===--------------------------------------------------------------------===// 8422 // Extra semantic analysis beyond the C type system 8423 8424 public: 8425 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, 8426 unsigned ByteNo) const; 8427 8428 private: 8429 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 8430 const ArraySubscriptExpr *ASE=nullptr, 8431 bool AllowOnePastEnd=true, bool IndexNegated=false); 8432 void CheckArrayAccess(const Expr *E); 8433 // Used to grab the relevant information from a FormatAttr and a 8434 // FunctionDeclaration. 8435 struct FormatStringInfo { 8436 unsigned FormatIdx; 8437 unsigned FirstDataArg; 8438 bool HasVAListArg; 8439 }; 8440 8441 bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 8442 FormatStringInfo *FSI); 8443 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 8444 const FunctionProtoType *Proto); 8445 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, 8446 ArrayRef<const Expr *> Args); 8447 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 8448 const FunctionProtoType *Proto); 8449 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto); 8450 void CheckConstructorCall(FunctionDecl *FDecl, 8451 ArrayRef<const Expr *> Args, 8452 const FunctionProtoType *Proto, 8453 SourceLocation Loc); 8454 8455 void checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args, 8456 unsigned NumParams, bool IsMemberFunction, SourceLocation Loc, 8457 SourceRange Range, VariadicCallType CallType); 8458 8459 bool CheckObjCString(Expr *Arg); 8460 8461 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, 8462 unsigned BuiltinID, CallExpr *TheCall); 8463 8464 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 8465 unsigned MaxWidth); 8466 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 8467 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 8468 8469 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 8470 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 8471 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 8472 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 8473 bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 8474 8475 bool SemaBuiltinVAStart(CallExpr *TheCall); 8476 bool SemaBuiltinVAStartARM(CallExpr *Call); 8477 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); 8478 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); 8479 8480 public: 8481 // Used by C++ template instantiation. 8482 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); 8483 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 8484 SourceLocation BuiltinLoc, 8485 SourceLocation RParenLoc); 8486 8487 private: 8488 bool SemaBuiltinPrefetch(CallExpr *TheCall); 8489 bool SemaBuiltinAssume(CallExpr *TheCall); 8490 bool SemaBuiltinAssumeAligned(CallExpr *TheCall); 8491 bool SemaBuiltinLongjmp(CallExpr *TheCall); 8492 bool SemaBuiltinSetjmp(CallExpr *TheCall); 8493 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); 8494 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, 8495 AtomicExpr::AtomicOp Op); 8496 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 8497 llvm::APSInt &Result); 8498 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 8499 int Low, int High); 8500 8501 public: 8502 enum FormatStringType { 8503 FST_Scanf, 8504 FST_Printf, 8505 FST_NSString, 8506 FST_Strftime, 8507 FST_Strfmon, 8508 FST_Kprintf, 8509 FST_FreeBSDKPrintf, 8510 FST_OSTrace, 8511 FST_Unknown 8512 }; 8513 static FormatStringType GetFormatStringType(const FormatAttr *Format); 8514 8515 void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr, 8516 ArrayRef<const Expr *> Args, bool HasVAListArg, 8517 unsigned format_idx, unsigned firstDataArg, 8518 FormatStringType Type, bool inFunctionCall, 8519 VariadicCallType CallType, 8520 llvm::SmallBitVector &CheckedVarArgs); 8521 8522 bool FormatStringHasSArg(const StringLiteral *FExpr); 8523 8524 bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx); 8525 8526 private: 8527 bool CheckFormatArguments(const FormatAttr *Format, 8528 ArrayRef<const Expr *> Args, 8529 bool IsCXXMember, 8530 VariadicCallType CallType, 8531 SourceLocation Loc, SourceRange Range, 8532 llvm::SmallBitVector &CheckedVarArgs); 8533 bool CheckFormatArguments(ArrayRef<const Expr *> Args, 8534 bool HasVAListArg, unsigned format_idx, 8535 unsigned firstDataArg, FormatStringType Type, 8536 VariadicCallType CallType, 8537 SourceLocation Loc, SourceRange range, 8538 llvm::SmallBitVector &CheckedVarArgs); 8539 8540 void CheckAbsoluteValueFunction(const CallExpr *Call, 8541 const FunctionDecl *FDecl, 8542 IdentifierInfo *FnInfo); 8543 8544 void CheckMemaccessArguments(const CallExpr *Call, 8545 unsigned BId, 8546 IdentifierInfo *FnName); 8547 8548 void CheckStrlcpycatArguments(const CallExpr *Call, 8549 IdentifierInfo *FnName); 8550 8551 void CheckStrncatArguments(const CallExpr *Call, 8552 IdentifierInfo *FnName); 8553 8554 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 8555 SourceLocation ReturnLoc, 8556 bool isObjCMethod = false, 8557 const AttrVec *Attrs = nullptr, 8558 const FunctionDecl *FD = nullptr); 8559 8560 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS); 8561 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); 8562 void CheckBoolLikeConversion(Expr *E, SourceLocation CC); 8563 void CheckForIntOverflow(Expr *E); 8564 void CheckUnsequencedOperations(Expr *E); 8565 8566 /// \brief Perform semantic checks on a completed expression. This will either 8567 /// be a full-expression or a default argument expression. 8568 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(), 8569 bool IsConstexpr = false); 8570 8571 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, 8572 Expr *Init); 8573 8574 /// \brief Check if the given expression contains 'break' or 'continue' 8575 /// statement that produces control flow different from GCC. 8576 void CheckBreakContinueBinding(Expr *E); 8577 8578 /// \brief Check whether receiver is mutable ObjC container which 8579 /// attempts to add itself into the container 8580 void CheckObjCCircularContainer(ObjCMessageExpr *Message); 8581 8582 public: 8583 /// \brief Register a magic integral constant to be used as a type tag. 8584 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 8585 uint64_t MagicValue, QualType Type, 8586 bool LayoutCompatible, bool MustBeNull); 8587 8588 struct TypeTagData { TypeTagDataTypeTagData8589 TypeTagData() {} 8590 TypeTagDataTypeTagData8591 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) : 8592 Type(Type), LayoutCompatible(LayoutCompatible), 8593 MustBeNull(MustBeNull) 8594 {} 8595 8596 QualType Type; 8597 8598 /// If true, \c Type should be compared with other expression's types for 8599 /// layout-compatibility. 8600 unsigned LayoutCompatible : 1; 8601 unsigned MustBeNull : 1; 8602 }; 8603 8604 /// A pair of ArgumentKind identifier and magic value. This uniquely 8605 /// identifies the magic value. 8606 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; 8607 8608 private: 8609 /// \brief A map from magic value to type information. 8610 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>> 8611 TypeTagForDatatypeMagicValues; 8612 8613 /// \brief Peform checks on a call of a function with argument_with_type_tag 8614 /// or pointer_with_type_tag attributes. 8615 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 8616 const Expr * const *ExprArgs); 8617 8618 /// \brief The parser's current scope. 8619 /// 8620 /// The parser maintains this state here. 8621 Scope *CurScope; 8622 8623 mutable IdentifierInfo *Ident_super; 8624 mutable IdentifierInfo *Ident___float128; 8625 8626 protected: 8627 friend class Parser; 8628 friend class InitializationSequence; 8629 friend class ASTReader; 8630 friend class ASTWriter; 8631 8632 public: 8633 /// \brief Retrieve the parser's current scope. 8634 /// 8635 /// This routine must only be used when it is certain that semantic analysis 8636 /// and the parser are in precisely the same context, which is not the case 8637 /// when, e.g., we are performing any kind of template instantiation. 8638 /// Therefore, the only safe places to use this scope are in the parser 8639 /// itself and in routines directly invoked from the parser and *never* from 8640 /// template substitution or instantiation. getCurScope()8641 Scope *getCurScope() const { return CurScope; } 8642 incrementMSManglingNumber()8643 void incrementMSManglingNumber() const { 8644 return CurScope->incrementMSManglingNumber(); 8645 } 8646 8647 IdentifierInfo *getSuperIdentifier() const; 8648 IdentifierInfo *getFloat128Identifier() const; 8649 8650 Decl *getObjCDeclContext() const; 8651 getCurLexicalContext()8652 DeclContext *getCurLexicalContext() const { 8653 return OriginalLexicalContext ? OriginalLexicalContext : CurContext; 8654 } 8655 8656 AvailabilityResult getCurContextAvailability() const; 8657 getCurObjCLexicalContext()8658 const DeclContext *getCurObjCLexicalContext() const { 8659 const DeclContext *DC = getCurLexicalContext(); 8660 // A category implicitly has the attribute of the interface. 8661 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC)) 8662 DC = CatD->getClassInterface(); 8663 return DC; 8664 } 8665 8666 /// \brief To be used for checking whether the arguments being passed to 8667 /// function exceeds the number of parameters expected for it. 8668 static bool TooManyArguments(size_t NumParams, size_t NumArgs, 8669 bool PartialOverloading = false) { 8670 // We check whether we're just after a comma in code-completion. 8671 if (NumArgs > 0 && PartialOverloading) 8672 return NumArgs + 1 > NumParams; // If so, we view as an extra argument. 8673 return NumArgs > NumParams; 8674 } 8675 }; 8676 8677 /// \brief RAII object that enters a new expression evaluation context. 8678 class EnterExpressionEvaluationContext { 8679 Sema &Actions; 8680 8681 public: 8682 EnterExpressionEvaluationContext(Sema &Actions, 8683 Sema::ExpressionEvaluationContext NewContext, 8684 Decl *LambdaContextDecl = nullptr, 8685 bool IsDecltype = false) Actions(Actions)8686 : Actions(Actions) { 8687 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, 8688 IsDecltype); 8689 } 8690 EnterExpressionEvaluationContext(Sema &Actions, 8691 Sema::ExpressionEvaluationContext NewContext, 8692 Sema::ReuseLambdaContextDecl_t, 8693 bool IsDecltype = false) Actions(Actions)8694 : Actions(Actions) { 8695 Actions.PushExpressionEvaluationContext(NewContext, 8696 Sema::ReuseLambdaContextDecl, 8697 IsDecltype); 8698 } 8699 ~EnterExpressionEvaluationContext()8700 ~EnterExpressionEvaluationContext() { 8701 Actions.PopExpressionEvaluationContext(); 8702 } 8703 }; 8704 8705 DeductionFailureInfo 8706 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, 8707 sema::TemplateDeductionInfo &Info); 8708 8709 /// \brief Contains a late templated function. 8710 /// Will be parsed at the end of the translation unit, used by Sema & Parser. 8711 struct LateParsedTemplate { 8712 CachedTokens Toks; 8713 /// \brief The template function declaration to be late parsed. 8714 Decl *D; 8715 }; 8716 8717 } // end namespace clang 8718 8719 #endif 8720