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