Sema.h revision c32d684d6c787b332a64c9013598d5ef668c4b45
15821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===// 25821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// 35821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// The LLVM Compiler Infrastructure 45821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// 5b2df76ea8fec9e32f6f3718986dba0d95315b29cTorne (Richard Coles)// This file is distributed under the University of Illinois Open Source 6b2df76ea8fec9e32f6f3718986dba0d95315b29cTorne (Richard Coles)// License. See LICENSE.TXT for details. 75821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// 85821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===----------------------------------------------------------------------===// 95821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// 105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// This file defines the Sema class, which performs semantic analysis and 11b2df76ea8fec9e32f6f3718986dba0d95315b29cTorne (Richard Coles)// builds ASTs. 125821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// 135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===----------------------------------------------------------------------===// 145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#ifndef LLVM_CLANG_SEMA_SEMA_H 165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#define LLVM_CLANG_SEMA_SEMA_H 175821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Sema/Ownership.h" 195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Sema/AnalysisBasedWarnings.h" 205821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Sema/IdentifierResolver.h" 215821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Sema/ObjCMethodList.h" 225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Sema/DeclSpec.h" 235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Sema/ExternalSemaSource.h" 245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Sema/LocInfoType.h" 255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Sema/MultiInitializer.h" 265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Sema/TypoCorrection.h" 275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Sema/Weak.h" 285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/AST/Expr.h" 295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/AST/DeclarationName.h" 305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/AST/ExternalASTSource.h" 315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/AST/TypeLoc.h" 321e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)#include "clang/Basic/Specifiers.h" 331e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)#include "clang/Basic/TemplateKinds.h" 341e9bf3e0803691d0a228da41fc608347b6db4340Torne (Richard Coles)#include "clang/Basic/TypeTraits.h" 355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Basic/ExpressionTraits.h" 365821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/ADT/ArrayRef.h" 375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/ADT/OwningPtr.h" 385821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/ADT/SmallPtrSet.h" 395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/ADT/SmallVector.h" 405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <deque> 415821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <string> 425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)namespace llvm { 445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) class APSInt; 455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) template <typename ValueT> struct DenseMapInfo; 465821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) template <typename ValueT, typename ValueInfoT> class DenseSet; 475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)} 485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) 495821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)namespace clang { 505821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) class ADLResult; 515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) class ASTConsumer; 525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) class ASTContext; 535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) class ASTMutationListener; 54b2df76ea8fec9e32f6f3718986dba0d95315b29cTorne (Richard Coles) class ASTReader; 55 class ASTWriter; 56 class ArrayType; 57 class AttributeList; 58 class BlockDecl; 59 class CXXBasePath; 60 class CXXBasePaths; 61 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; 62 class CXXConstructorDecl; 63 class CXXConversionDecl; 64 class CXXDestructorDecl; 65 class CXXFieldCollector; 66 class CXXMemberCallExpr; 67 class CXXMethodDecl; 68 class CXXScopeSpec; 69 class CXXTemporary; 70 class CXXTryStmt; 71 class CallExpr; 72 class ClassTemplateDecl; 73 class ClassTemplatePartialSpecializationDecl; 74 class ClassTemplateSpecializationDecl; 75 class CodeCompleteConsumer; 76 class CodeCompletionAllocator; 77 class CodeCompletionResult; 78 class Decl; 79 class DeclAccessPair; 80 class DeclContext; 81 class DeclRefExpr; 82 class DeclaratorDecl; 83 class DeducedTemplateArgument; 84 class DependentDiagnostic; 85 class DesignatedInitExpr; 86 class Designation; 87 class EnumConstantDecl; 88 class Expr; 89 class ExtVectorType; 90 class ExternalSemaSource; 91 class FormatAttr; 92 class FriendDecl; 93 class FunctionDecl; 94 class FunctionProtoType; 95 class FunctionTemplateDecl; 96 class ImplicitConversionSequence; 97 class InitListExpr; 98 class InitializationKind; 99 class InitializationSequence; 100 class InitializedEntity; 101 class IntegerLiteral; 102 class LabelStmt; 103 class LangOptions; 104 class LocalInstantiationScope; 105 class LookupResult; 106 class MacroInfo; 107 class MultiLevelTemplateArgumentList; 108 class NamedDecl; 109 class NonNullAttr; 110 class ObjCCategoryDecl; 111 class ObjCCategoryImplDecl; 112 class ObjCCompatibleAliasDecl; 113 class ObjCContainerDecl; 114 class ObjCImplDecl; 115 class ObjCImplementationDecl; 116 class ObjCInterfaceDecl; 117 class ObjCIvarDecl; 118 template <class T> class ObjCList; 119 class ObjCMessageExpr; 120 class ObjCMethodDecl; 121 class ObjCPropertyDecl; 122 class ObjCProtocolDecl; 123 class OverloadCandidateSet; 124 class OverloadExpr; 125 class ParenListExpr; 126 class ParmVarDecl; 127 class Preprocessor; 128 class PseudoDestructorTypeStorage; 129 class QualType; 130 class StandardConversionSequence; 131 class Stmt; 132 class StringLiteral; 133 class SwitchStmt; 134 class TargetAttributesSema; 135 class TemplateArgument; 136 class TemplateArgumentList; 137 class TemplateArgumentLoc; 138 class TemplateDecl; 139 class TemplateParameterList; 140 class TemplatePartialOrderingContext; 141 class TemplateTemplateParmDecl; 142 class Token; 143 class TypeAliasDecl; 144 class TypedefDecl; 145 class TypedefNameDecl; 146 class TypeLoc; 147 class UnqualifiedId; 148 class UnresolvedLookupExpr; 149 class UnresolvedMemberExpr; 150 class UnresolvedSetImpl; 151 class UnresolvedSetIterator; 152 class UsingDecl; 153 class UsingShadowDecl; 154 class ValueDecl; 155 class VarDecl; 156 class VisibilityAttr; 157 class VisibleDeclConsumer; 158 class IndirectFieldDecl; 159 160namespace sema { 161 class AccessedEntity; 162 class BlockScopeInfo; 163 class DelayedDiagnostic; 164 class FunctionScopeInfo; 165 class TemplateDeductionInfo; 166} 167 168// FIXME: No way to easily map from TemplateTypeParmTypes to 169// TemplateTypeParmDecls, so we have this horrible PointerUnion. 170typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, 171 SourceLocation> UnexpandedParameterPack; 172 173/// Sema - This implements semantic analysis and AST building for C. 174class Sema { 175 Sema(const Sema&); // DO NOT IMPLEMENT 176 void operator=(const Sema&); // DO NOT IMPLEMENT 177 mutable const TargetAttributesSema* TheTargetAttributesSema; 178public: 179 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; 180 typedef OpaquePtr<TemplateName> TemplateTy; 181 typedef OpaquePtr<QualType> TypeTy; 182 183 OpenCLOptions OpenCLFeatures; 184 FPOptions FPFeatures; 185 186 const LangOptions &LangOpts; 187 Preprocessor &PP; 188 ASTContext &Context; 189 ASTConsumer &Consumer; 190 DiagnosticsEngine &Diags; 191 SourceManager &SourceMgr; 192 193 /// \brief Flag indicating whether or not to collect detailed statistics. 194 bool CollectStats; 195 196 /// \brief Source of additional semantic information. 197 ExternalSemaSource *ExternalSource; 198 199 /// \brief Code-completion consumer. 200 CodeCompleteConsumer *CodeCompleter; 201 202 /// CurContext - This is the current declaration context of parsing. 203 DeclContext *CurContext; 204 205 /// \brief Generally null except when we temporarily switch decl contexts, 206 /// like in \see ActOnObjCTemporaryExitContainerContext. 207 DeclContext *OriginalLexicalContext; 208 209 /// VAListTagName - The declaration name corresponding to __va_list_tag. 210 /// This is used as part of a hack to omit that class from ADL results. 211 DeclarationName VAListTagName; 212 213 /// PackContext - Manages the stack for #pragma pack. An alignment 214 /// of 0 indicates default alignment. 215 void *PackContext; // Really a "PragmaPackStack*" 216 217 bool MSStructPragmaOn; // True when #pragma ms_struct on 218 219 /// VisContext - Manages the stack for #pragma GCC visibility. 220 void *VisContext; // Really a "PragmaVisStack*" 221 222 /// ExprNeedsCleanups - True if the current evaluation context 223 /// requires cleanups to be run at its conclusion. 224 bool ExprNeedsCleanups; 225 226 /// \brief Stack containing information about each of the nested 227 /// function, block, and method scopes that are currently active. 228 /// 229 /// This array is never empty. Clients should ignore the first 230 /// element, which is used to cache a single FunctionScopeInfo 231 /// that's used to parse every top-level function. 232 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; 233 234 /// ExprTemporaries - This is the stack of temporaries that are created by 235 /// the current full expression. 236 SmallVector<CXXTemporary*, 8> ExprTemporaries; 237 238 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, 239 &ExternalSemaSource::ReadExtVectorDecls, 2, 2> 240 ExtVectorDeclsType; 241 242 /// ExtVectorDecls - This is a list all the extended vector types. This allows 243 /// us to associate a raw vector type with one of the ext_vector type names. 244 /// This is only necessary for issuing pretty diagnostics. 245 ExtVectorDeclsType ExtVectorDecls; 246 247 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. 248 llvm::OwningPtr<CXXFieldCollector> FieldCollector; 249 250 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; 251 252 /// PureVirtualClassDiagSet - a set of class declarations which we have 253 /// emitted a list of pure virtual functions. Used to prevent emitting the 254 /// same list more than once. 255 llvm::OwningPtr<RecordDeclSetTy> PureVirtualClassDiagSet; 256 257 /// ParsingInitForAutoVars - a set of declarations with auto types for which 258 /// we are currently parsing the initializer. 259 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; 260 261 /// \brief A mapping from external names to the most recent 262 /// locally-scoped external declaration with that name. 263 /// 264 /// This map contains external declarations introduced in local 265 /// scoped, e.g., 266 /// 267 /// \code 268 /// void f() { 269 /// void foo(int, int); 270 /// } 271 /// \endcode 272 /// 273 /// Here, the name "foo" will be associated with the declaration on 274 /// "foo" within f. This name is not visible outside of 275 /// "f". However, we still find it in two cases: 276 /// 277 /// - If we are declaring another external with the name "foo", we 278 /// can find "foo" as a previous declaration, so that the types 279 /// of this external declaration can be checked for 280 /// compatibility. 281 /// 282 /// - If we would implicitly declare "foo" (e.g., due to a call to 283 /// "foo" in C when no prototype or definition is visible), then 284 /// we find this declaration of "foo" and complain that it is 285 /// not visible. 286 llvm::DenseMap<DeclarationName, NamedDecl *> LocallyScopedExternalDecls; 287 288 /// \brief Look for a locally scoped external declaration by the given name. 289 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator 290 findLocallyScopedExternalDecl(DeclarationName Name); 291 292 typedef LazyVector<VarDecl *, ExternalSemaSource, 293 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> 294 TentativeDefinitionsType; 295 296 /// \brief All the tentative definitions encountered in the TU. 297 TentativeDefinitionsType TentativeDefinitions; 298 299 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, 300 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> 301 UnusedFileScopedDeclsType; 302 303 /// \brief The set of file scoped decls seen so far that have not been used 304 /// and must warn if not used. Only contains the first declaration. 305 UnusedFileScopedDeclsType UnusedFileScopedDecls; 306 307 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, 308 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> 309 DelegatingCtorDeclsType; 310 311 /// \brief All the delegating constructors seen so far in the file, used for 312 /// cycle detection at the end of the TU. 313 DelegatingCtorDeclsType DelegatingCtorDecls; 314 315 /// \brief All the overriding destructors seen during a class definition 316 /// (there could be multiple due to nested classes) that had their exception 317 /// spec checks delayed, plus the overridden destructor. 318 SmallVector<std::pair<const CXXDestructorDecl*, 319 const CXXDestructorDecl*>, 2> 320 DelayedDestructorExceptionSpecChecks; 321 322 /// \brief Callback to the parser to parse templated functions when needed. 323 typedef void LateTemplateParserCB(void *P, const FunctionDecl *FD); 324 LateTemplateParserCB *LateTemplateParser; 325 void *OpaqueParser; 326 327 void SetLateTemplateParser(LateTemplateParserCB *LTP, void *P) { 328 LateTemplateParser = LTP; 329 OpaqueParser = P; 330 } 331 332 class DelayedDiagnostics; 333 334 class ParsingDeclState { 335 unsigned SavedStackSize; 336 friend class Sema::DelayedDiagnostics; 337 }; 338 339 class ProcessingContextState { 340 unsigned SavedParsingDepth; 341 unsigned SavedActiveStackBase; 342 friend class Sema::DelayedDiagnostics; 343 }; 344 345 /// A class which encapsulates the logic for delaying diagnostics 346 /// during parsing and other processing. 347 class DelayedDiagnostics { 348 /// \brief The stack of diagnostics that were delayed due to being 349 /// produced during the parsing of a declaration. 350 sema::DelayedDiagnostic *Stack; 351 352 /// \brief The number of objects on the delayed-diagnostics stack. 353 unsigned StackSize; 354 355 /// \brief The current capacity of the delayed-diagnostics stack. 356 unsigned StackCapacity; 357 358 /// \brief The index of the first "active" delayed diagnostic in 359 /// the stack. When parsing class definitions, we ignore active 360 /// delayed diagnostics from the surrounding context. 361 unsigned ActiveStackBase; 362 363 /// \brief The depth of the declarations we're currently parsing. 364 /// This gets saved and reset whenever we enter a class definition. 365 unsigned ParsingDepth; 366 367 public: 368 DelayedDiagnostics() : Stack(0), StackSize(0), StackCapacity(0), 369 ActiveStackBase(0), ParsingDepth(0) {} 370 371 ~DelayedDiagnostics() { 372 delete[] reinterpret_cast<char*>(Stack); 373 } 374 375 /// Adds a delayed diagnostic. 376 void add(const sema::DelayedDiagnostic &diag); 377 378 /// Determines whether diagnostics should be delayed. 379 bool shouldDelayDiagnostics() { return ParsingDepth > 0; } 380 381 /// Observe that we've started parsing a declaration. Access and 382 /// deprecation diagnostics will be delayed; when the declaration 383 /// is completed, all active delayed diagnostics will be evaluated 384 /// in its context, and then active diagnostics stack will be 385 /// popped down to the saved depth. 386 ParsingDeclState pushParsingDecl() { 387 ParsingDepth++; 388 389 ParsingDeclState state; 390 state.SavedStackSize = StackSize; 391 return state; 392 } 393 394 /// Observe that we're completed parsing a declaration. 395 static void popParsingDecl(Sema &S, ParsingDeclState state, Decl *decl); 396 397 /// Observe that we've started processing a different context, the 398 /// contents of which are semantically separate from the 399 /// declarations it may lexically appear in. This sets aside the 400 /// current stack of active diagnostics and starts afresh. 401 ProcessingContextState pushContext() { 402 assert(StackSize >= ActiveStackBase); 403 404 ProcessingContextState state; 405 state.SavedParsingDepth = ParsingDepth; 406 state.SavedActiveStackBase = ActiveStackBase; 407 408 ActiveStackBase = StackSize; 409 ParsingDepth = 0; 410 411 return state; 412 } 413 414 /// Observe that we've stopped processing a context. This 415 /// restores the previous stack of active diagnostics. 416 void popContext(ProcessingContextState state) { 417 assert(ActiveStackBase == StackSize); 418 assert(ParsingDepth == 0); 419 ActiveStackBase = state.SavedActiveStackBase; 420 ParsingDepth = state.SavedParsingDepth; 421 } 422 } DelayedDiagnostics; 423 424 /// A RAII object to temporarily push a declaration context. 425 class ContextRAII { 426 private: 427 Sema &S; 428 DeclContext *SavedContext; 429 ProcessingContextState SavedContextState; 430 431 public: 432 ContextRAII(Sema &S, DeclContext *ContextToPush) 433 : S(S), SavedContext(S.CurContext), 434 SavedContextState(S.DelayedDiagnostics.pushContext()) 435 { 436 assert(ContextToPush && "pushing null context"); 437 S.CurContext = ContextToPush; 438 } 439 440 void pop() { 441 if (!SavedContext) return; 442 S.CurContext = SavedContext; 443 S.DelayedDiagnostics.popContext(SavedContextState); 444 SavedContext = 0; 445 } 446 447 ~ContextRAII() { 448 pop(); 449 } 450 }; 451 452 /// WeakUndeclaredIdentifiers - Identifiers contained in 453 /// #pragma weak before declared. rare. may alias another 454 /// identifier, declared or undeclared 455 llvm::DenseMap<IdentifierInfo*,WeakInfo> WeakUndeclaredIdentifiers; 456 457 /// \brief Load weak undeclared identifiers from the external source. 458 void LoadExternalWeakUndeclaredIdentifiers(); 459 460 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by 461 /// #pragma weak during processing of other Decls. 462 /// I couldn't figure out a clean way to generate these in-line, so 463 /// we store them here and handle separately -- which is a hack. 464 /// It would be best to refactor this. 465 SmallVector<Decl*,2> WeakTopLevelDecl; 466 467 IdentifierResolver IdResolver; 468 469 /// Translation Unit Scope - useful to Objective-C actions that need 470 /// to lookup file scope declarations in the "ordinary" C decl namespace. 471 /// For example, user-defined classes, built-in "id" type, etc. 472 Scope *TUScope; 473 474 /// \brief The C++ "std" namespace, where the standard library resides. 475 LazyDeclPtr StdNamespace; 476 477 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++ 478 /// standard library. 479 LazyDeclPtr StdBadAlloc; 480 481 /// \brief The C++ "type_info" declaration, which is defined in <typeinfo>. 482 RecordDecl *CXXTypeInfoDecl; 483 484 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files. 485 RecordDecl *MSVCGuidDecl; 486 487 /// A flag to remember whether the implicit forms of operator new and delete 488 /// have been declared. 489 bool GlobalNewDeleteDeclared; 490 491 492 /// A flag that is set when parsing a -dealloc method and no [super dealloc] 493 /// call was found yet. 494 bool ObjCShouldCallSuperDealloc; 495 /// A flag that is set when parsing a -finalize method and no [super finalize] 496 /// call was found yet. 497 bool ObjCShouldCallSuperFinalize; 498 499 /// \brief The set of declarations that have been referenced within 500 /// a potentially evaluated expression. 501 typedef SmallVector<std::pair<SourceLocation, Decl *>, 10> 502 PotentiallyReferencedDecls; 503 504 /// \brief A set of diagnostics that may be emitted. 505 typedef SmallVector<std::pair<SourceLocation, PartialDiagnostic>, 10> 506 PotentiallyEmittedDiagnostics; 507 508 /// \brief Describes how the expressions currently being parsed are 509 /// evaluated at run-time, if at all. 510 enum ExpressionEvaluationContext { 511 /// \brief The current expression and its subexpressions occur within an 512 /// unevaluated operand (C++0x [expr]p8), such as a constant expression 513 /// or the subexpression of \c sizeof, where the type or the value of the 514 /// expression may be significant but no code will be generated to evaluate 515 /// the value of the expression at run time. 516 Unevaluated, 517 518 /// \brief The current expression is potentially evaluated at run time, 519 /// which means that code may be generated to evaluate the value of the 520 /// expression at run time. 521 PotentiallyEvaluated, 522 523 /// \brief The current expression may be potentially evaluated or it may 524 /// be unevaluated, but it is impossible to tell from the lexical context. 525 /// This evaluation context is used primary for the operand of the C++ 526 /// \c typeid expression, whose argument is potentially evaluated only when 527 /// it is an lvalue of polymorphic class type (C++ [basic.def.odr]p2). 528 PotentiallyPotentiallyEvaluated, 529 530 /// \brief The current expression is potentially evaluated, but any 531 /// declarations referenced inside that expression are only used if 532 /// in fact the current expression is used. 533 /// 534 /// This value is used when parsing default function arguments, for which 535 /// we would like to provide diagnostics (e.g., passing non-POD arguments 536 /// through varargs) but do not want to mark declarations as "referenced" 537 /// until the default argument is used. 538 PotentiallyEvaluatedIfUsed 539 }; 540 541 /// \brief Data structure used to record current or nested 542 /// expression evaluation contexts. 543 struct ExpressionEvaluationContextRecord { 544 /// \brief The expression evaluation context. 545 ExpressionEvaluationContext Context; 546 547 /// \brief Whether the enclosing context needed a cleanup. 548 bool ParentNeedsCleanups; 549 550 /// \brief The number of temporaries that were active when we 551 /// entered this expression evaluation context. 552 unsigned NumTemporaries; 553 554 /// \brief The set of declarations referenced within a 555 /// potentially potentially-evaluated context. 556 /// 557 /// When leaving a potentially potentially-evaluated context, each 558 /// of these elements will be as referenced if the corresponding 559 /// potentially potentially evaluated expression is potentially 560 /// evaluated. 561 PotentiallyReferencedDecls *PotentiallyReferenced; 562 563 /// \brief The set of diagnostics to emit should this potentially 564 /// potentially-evaluated context become evaluated. 565 PotentiallyEmittedDiagnostics *PotentiallyDiagnosed; 566 567 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, 568 unsigned NumTemporaries, 569 bool ParentNeedsCleanups) 570 : Context(Context), ParentNeedsCleanups(ParentNeedsCleanups), 571 NumTemporaries(NumTemporaries), 572 PotentiallyReferenced(0), PotentiallyDiagnosed(0) { } 573 574 void addReferencedDecl(SourceLocation Loc, Decl *Decl) { 575 if (!PotentiallyReferenced) 576 PotentiallyReferenced = new PotentiallyReferencedDecls; 577 PotentiallyReferenced->push_back(std::make_pair(Loc, Decl)); 578 } 579 580 void addDiagnostic(SourceLocation Loc, const PartialDiagnostic &PD) { 581 if (!PotentiallyDiagnosed) 582 PotentiallyDiagnosed = new PotentiallyEmittedDiagnostics; 583 PotentiallyDiagnosed->push_back(std::make_pair(Loc, PD)); 584 } 585 586 void Destroy() { 587 delete PotentiallyReferenced; 588 delete PotentiallyDiagnosed; 589 PotentiallyReferenced = 0; 590 PotentiallyDiagnosed = 0; 591 } 592 }; 593 594 /// A stack of expression evaluation contexts. 595 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; 596 597 /// SpecialMemberOverloadResult - The overloading result for a special member 598 /// function. 599 /// 600 /// This is basically a wrapper around PointerIntPair. The lowest bit of the 601 /// integer is used to determine whether we have a parameter qualification 602 /// match, the second-lowest is whether we had success in resolving the 603 /// overload to a unique non-deleted function. 604 /// 605 /// The ConstParamMatch bit represents whether, when looking up a copy 606 /// constructor or assignment operator, we found a potential copy 607 /// constructor/assignment operator whose first parameter is const-qualified. 608 /// This is used for determining parameter types of other objects and is 609 /// utterly meaningless on other types of special members. 610 class SpecialMemberOverloadResult : public llvm::FastFoldingSetNode { 611 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; 612 public: 613 SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID) 614 : FastFoldingSetNode(ID) 615 {} 616 617 CXXMethodDecl *getMethod() const { return Pair.getPointer(); } 618 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } 619 620 bool hasSuccess() const { return Pair.getInt() & 0x1; } 621 void setSuccess(bool B) { 622 Pair.setInt(unsigned(B) | hasConstParamMatch() << 1); 623 } 624 625 bool hasConstParamMatch() const { return Pair.getInt() & 0x2; } 626 void setConstParamMatch(bool B) { 627 Pair.setInt(B << 1 | unsigned(hasSuccess())); 628 } 629 }; 630 631 /// \brief A cache of special member function overload resolution results 632 /// for C++ records. 633 llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache; 634 635 /// \brief The kind of translation unit we are processing. 636 /// 637 /// When we're processing a complete translation unit, Sema will perform 638 /// end-of-translation-unit semantic tasks (such as creating 639 /// initializers for tentative definitions in C) once parsing has 640 /// completed. Modules and precompiled headers perform different kinds of 641 /// checks. 642 TranslationUnitKind TUKind; 643 644 llvm::BumpPtrAllocator BumpAlloc; 645 646 /// \brief The number of SFINAE diagnostics that have been trapped. 647 unsigned NumSFINAEErrors; 648 649 typedef llvm::DenseMap<ParmVarDecl *, SmallVector<ParmVarDecl *, 1> > 650 UnparsedDefaultArgInstantiationsMap; 651 652 /// \brief A mapping from parameters with unparsed default arguments to the 653 /// set of instantiations of each parameter. 654 /// 655 /// This mapping is a temporary data structure used when parsing 656 /// nested class templates or nested classes of class templates, 657 /// where we might end up instantiating an inner class before the 658 /// default arguments of its methods have been parsed. 659 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; 660 661 // Contains the locations of the beginning of unparsed default 662 // argument locations. 663 llvm::DenseMap<ParmVarDecl *,SourceLocation> UnparsedDefaultArgLocs; 664 665 /// UndefinedInternals - all the used, undefined objects with 666 /// internal linkage in this translation unit. 667 llvm::DenseMap<NamedDecl*, SourceLocation> UndefinedInternals; 668 669 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods; 670 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool; 671 672 /// Method Pool - allows efficient lookup when typechecking messages to "id". 673 /// We need to maintain a list, since selectors can have differing signatures 674 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% 675 /// of selectors are "overloaded"). 676 GlobalMethodPool MethodPool; 677 678 /// Method selectors used in a @selector expression. Used for implementation 679 /// of -Wselector. 680 llvm::DenseMap<Selector, SourceLocation> ReferencedSelectors; 681 682 GlobalMethodPool::iterator ReadMethodPool(Selector Sel); 683 684 /// Private Helper predicate to check for 'self'. 685 bool isSelfExpr(Expr *RExpr); 686public: 687 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 688 TranslationUnitKind TUKind = TU_Complete, 689 CodeCompleteConsumer *CompletionConsumer = 0); 690 ~Sema(); 691 692 /// \brief Perform initialization that occurs after the parser has been 693 /// initialized but before it parses anything. 694 void Initialize(); 695 696 const LangOptions &getLangOptions() const { return LangOpts; } 697 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } 698 FPOptions &getFPOptions() { return FPFeatures; } 699 700 DiagnosticsEngine &getDiagnostics() const { return Diags; } 701 SourceManager &getSourceManager() const { return SourceMgr; } 702 const TargetAttributesSema &getTargetAttributesSema() const; 703 Preprocessor &getPreprocessor() const { return PP; } 704 ASTContext &getASTContext() const { return Context; } 705 ASTConsumer &getASTConsumer() const { return Consumer; } 706 ASTMutationListener *getASTMutationListener() const; 707 708 void PrintStats() const; 709 710 /// \brief Helper class that creates diagnostics with optional 711 /// template instantiation stacks. 712 /// 713 /// This class provides a wrapper around the basic DiagnosticBuilder 714 /// class that emits diagnostics. SemaDiagnosticBuilder is 715 /// responsible for emitting the diagnostic (as DiagnosticBuilder 716 /// does) and, if the diagnostic comes from inside a template 717 /// instantiation, printing the template instantiation stack as 718 /// well. 719 class SemaDiagnosticBuilder : public DiagnosticBuilder { 720 Sema &SemaRef; 721 unsigned DiagID; 722 723 public: 724 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) 725 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { } 726 727 explicit SemaDiagnosticBuilder(Sema &SemaRef) 728 : DiagnosticBuilder(DiagnosticBuilder::Suppress), SemaRef(SemaRef) { } 729 730 ~SemaDiagnosticBuilder(); 731 }; 732 733 /// \brief Emit a diagnostic. 734 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); 735 736 /// \brief Emit a partial diagnostic. 737 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD); 738 739 /// \brief Build a partial diagnostic. 740 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h 741 742 bool findMacroSpelling(SourceLocation &loc, StringRef name); 743 744 ExprResult Owned(Expr* E) { return E; } 745 ExprResult Owned(ExprResult R) { return R; } 746 StmtResult Owned(Stmt* S) { return S; } 747 748 void ActOnEndOfTranslationUnit(); 749 750 void CheckDelegatingCtorCycles(); 751 752 Scope *getScopeForContext(DeclContext *Ctx); 753 754 void PushFunctionScope(); 755 void PushBlockScope(Scope *BlockScope, BlockDecl *Block); 756 void PopFunctionOrBlockScope(const sema::AnalysisBasedWarnings::Policy *WP =0, 757 const Decl *D = 0, const BlockExpr *blkExpr = 0); 758 759 sema::FunctionScopeInfo *getCurFunction() const { 760 return FunctionScopes.back(); 761 } 762 763 bool hasAnyUnrecoverableErrorsInThisFunction() const; 764 765 /// \brief Retrieve the current block, if any. 766 sema::BlockScopeInfo *getCurBlock(); 767 768 /// WeakTopLevelDeclDecls - access to #pragma weak-generated Decls 769 SmallVector<Decl*,2> &WeakTopLevelDecls() { return WeakTopLevelDecl; } 770 771 //===--------------------------------------------------------------------===// 772 // Type Analysis / Processing: SemaType.cpp. 773 // 774 775 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs); 776 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVR) { 777 return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR)); 778 } 779 QualType BuildPointerType(QualType T, 780 SourceLocation Loc, DeclarationName Entity); 781 QualType BuildReferenceType(QualType T, bool LValueRef, 782 SourceLocation Loc, DeclarationName Entity); 783 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, 784 Expr *ArraySize, unsigned Quals, 785 SourceRange Brackets, DeclarationName Entity); 786 QualType BuildExtVectorType(QualType T, Expr *ArraySize, 787 SourceLocation AttrLoc); 788 QualType BuildFunctionType(QualType T, 789 QualType *ParamTypes, unsigned NumParamTypes, 790 bool Variadic, unsigned Quals, 791 RefQualifierKind RefQualifier, 792 SourceLocation Loc, DeclarationName Entity, 793 FunctionType::ExtInfo Info); 794 QualType BuildMemberPointerType(QualType T, QualType Class, 795 SourceLocation Loc, 796 DeclarationName Entity); 797 QualType BuildBlockPointerType(QualType T, 798 SourceLocation Loc, DeclarationName Entity); 799 QualType BuildParenType(QualType T); 800 QualType BuildAtomicType(QualType T, SourceLocation Loc); 801 802 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); 803 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); 804 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, 805 TypeSourceInfo *ReturnTypeInfo); 806 /// \brief Package the given type and TSI into a ParsedType. 807 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); 808 DeclarationNameInfo GetNameForDeclarator(Declarator &D); 809 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); 810 static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo = 0); 811 bool CheckSpecifiedExceptionType(QualType T, const SourceRange &Range); 812 bool CheckDistantExceptionSpec(QualType T); 813 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); 814 bool CheckEquivalentExceptionSpec( 815 const FunctionProtoType *Old, SourceLocation OldLoc, 816 const FunctionProtoType *New, SourceLocation NewLoc); 817 bool CheckEquivalentExceptionSpec( 818 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, 819 const FunctionProtoType *Old, SourceLocation OldLoc, 820 const FunctionProtoType *New, SourceLocation NewLoc, 821 bool *MissingExceptionSpecification = 0, 822 bool *MissingEmptyExceptionSpecification = 0, 823 bool AllowNoexceptAllMatchWithNoSpec = false, 824 bool IsOperatorNew = false); 825 bool CheckExceptionSpecSubset( 826 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, 827 const FunctionProtoType *Superset, SourceLocation SuperLoc, 828 const FunctionProtoType *Subset, SourceLocation SubLoc); 829 bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID, 830 const FunctionProtoType *Target, SourceLocation TargetLoc, 831 const FunctionProtoType *Source, SourceLocation SourceLoc); 832 833 TypeResult ActOnTypeName(Scope *S, Declarator &D); 834 835 /// \brief The parser has parsed the context-sensitive type 'instancetype' 836 /// in an Objective-C message declaration. Return the appropriate type. 837 ParsedType ActOnObjCInstanceType(SourceLocation Loc); 838 839 bool RequireCompleteType(SourceLocation Loc, QualType T, 840 const PartialDiagnostic &PD, 841 std::pair<SourceLocation, PartialDiagnostic> Note); 842 bool RequireCompleteType(SourceLocation Loc, QualType T, 843 const PartialDiagnostic &PD); 844 bool RequireCompleteType(SourceLocation Loc, QualType T, 845 unsigned DiagID); 846 bool RequireCompleteExprType(Expr *E, const PartialDiagnostic &PD, 847 std::pair<SourceLocation, 848 PartialDiagnostic> Note); 849 850 bool RequireLiteralType(SourceLocation Loc, QualType T, 851 const PartialDiagnostic &PD, 852 bool AllowIncompleteType = false); 853 854 QualType getElaboratedType(ElaboratedTypeKeyword Keyword, 855 const CXXScopeSpec &SS, QualType T); 856 857 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc); 858 QualType BuildDecltypeType(Expr *E, SourceLocation Loc); 859 QualType BuildUnaryTransformType(QualType BaseType, 860 UnaryTransformType::UTTKind UKind, 861 SourceLocation Loc); 862 863 //===--------------------------------------------------------------------===// 864 // Symbol table / Decl tracking callbacks: SemaDecl.cpp. 865 // 866 867 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = 0); 868 869 void DiagnoseUseOfUnimplementedSelectors(); 870 871 ParsedType getTypeName(IdentifierInfo &II, SourceLocation NameLoc, 872 Scope *S, CXXScopeSpec *SS = 0, 873 bool isClassName = false, 874 bool HasTrailingDot = false, 875 ParsedType ObjectType = ParsedType(), 876 bool WantNontrivialTypeSourceInfo = false, 877 IdentifierInfo **CorrectedII = 0); 878 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); 879 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); 880 bool DiagnoseUnknownTypeName(const IdentifierInfo &II, 881 SourceLocation IILoc, 882 Scope *S, 883 CXXScopeSpec *SS, 884 ParsedType &SuggestedType); 885 886 /// \brief Describes the result of the name lookup and resolution performed 887 /// by \c ClassifyName(). 888 enum NameClassificationKind { 889 NC_Unknown, 890 NC_Error, 891 NC_Keyword, 892 NC_Type, 893 NC_Expression, 894 NC_NestedNameSpecifier, 895 NC_TypeTemplate, 896 NC_FunctionTemplate 897 }; 898 899 class NameClassification { 900 NameClassificationKind Kind; 901 ExprResult Expr; 902 TemplateName Template; 903 ParsedType Type; 904 const IdentifierInfo *Keyword; 905 906 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} 907 908 public: 909 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {} 910 911 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} 912 913 NameClassification(const IdentifierInfo *Keyword) 914 : Kind(NC_Keyword), Keyword(Keyword) { } 915 916 static NameClassification Error() { 917 return NameClassification(NC_Error); 918 } 919 920 static NameClassification Unknown() { 921 return NameClassification(NC_Unknown); 922 } 923 924 static NameClassification NestedNameSpecifier() { 925 return NameClassification(NC_NestedNameSpecifier); 926 } 927 928 static NameClassification TypeTemplate(TemplateName Name) { 929 NameClassification Result(NC_TypeTemplate); 930 Result.Template = Name; 931 return Result; 932 } 933 934 static NameClassification FunctionTemplate(TemplateName Name) { 935 NameClassification Result(NC_FunctionTemplate); 936 Result.Template = Name; 937 return Result; 938 } 939 940 NameClassificationKind getKind() const { return Kind; } 941 942 ParsedType getType() const { 943 assert(Kind == NC_Type); 944 return Type; 945 } 946 947 ExprResult getExpression() const { 948 assert(Kind == NC_Expression); 949 return Expr; 950 } 951 952 TemplateName getTemplateName() const { 953 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate); 954 return Template; 955 } 956 957 TemplateNameKind getTemplateNameKind() const { 958 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate); 959 return Kind == NC_TypeTemplate? TNK_Type_template : TNK_Function_template; 960 } 961}; 962 963 /// \brief Perform name lookup on the given name, classifying it based on 964 /// the results of name lookup and the following token. 965 /// 966 /// This routine is used by the parser to resolve identifiers and help direct 967 /// parsing. When the identifier cannot be found, this routine will attempt 968 /// to correct the typo and classify based on the resulting name. 969 /// 970 /// \param S The scope in which we're performing name lookup. 971 /// 972 /// \param SS The nested-name-specifier that precedes the name. 973 /// 974 /// \param Name The identifier. If typo correction finds an alternative name, 975 /// this pointer parameter will be updated accordingly. 976 /// 977 /// \param NameLoc The location of the identifier. 978 /// 979 /// \param NextToken The token following the identifier. Used to help 980 /// disambiguate the name. 981 NameClassification ClassifyName(Scope *S, 982 CXXScopeSpec &SS, 983 IdentifierInfo *&Name, 984 SourceLocation NameLoc, 985 const Token &NextToken); 986 987 Decl *ActOnDeclarator(Scope *S, Declarator &D); 988 989 Decl *HandleDeclarator(Scope *S, Declarator &D, 990 MultiTemplateParamsArg TemplateParameterLists); 991 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, 992 const LookupResult &Previous, 993 Scope *S); 994 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); 995 void DiagnoseFunctionSpecifiers(Declarator& D); 996 void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R); 997 void CheckShadow(Scope *S, VarDecl *D); 998 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); 999 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); 1000 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 1001 TypeSourceInfo *TInfo, 1002 LookupResult &Previous); 1003 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, 1004 LookupResult &Previous, bool &Redeclaration); 1005 NamedDecl* ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC, 1006 TypeSourceInfo *TInfo, 1007 LookupResult &Previous, 1008 MultiTemplateParamsArg TemplateParamLists); 1009 // Returns true if the variable declaration is a redeclaration 1010 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); 1011 void CheckCompleteVariableDeclaration(VarDecl *var); 1012 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, 1013 TypeSourceInfo *TInfo, 1014 LookupResult &Previous, 1015 MultiTemplateParamsArg TemplateParamLists, 1016 bool &AddToScope); 1017 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); 1018 1019 /// \brief The kind of constexpr declaration checking we are performing. 1020 /// 1021 /// The kind affects which diagnostics (if any) are emitted if the function 1022 /// does not satisfy the requirements of a constexpr function declaration. 1023 enum CheckConstexprKind { 1024 /// \brief Check a constexpr function declaration, and produce errors if it 1025 /// does not satisfy the requirements. 1026 CCK_Declaration, 1027 /// \brief Check a constexpr function template instantiation. 1028 CCK_Instantiation, 1029 /// \brief Produce notes explaining why an instantiation was not constexpr. 1030 CCK_NoteNonConstexprInstantiation 1031 }; 1032 bool CheckConstexprFunctionDecl(const FunctionDecl *FD, CheckConstexprKind CCK); 1033 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body); 1034 1035 void DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); 1036 // Returns true if the function declaration is a redeclaration 1037 bool CheckFunctionDeclaration(Scope *S, 1038 FunctionDecl *NewFD, LookupResult &Previous, 1039 bool IsExplicitSpecialization); 1040 void CheckMain(FunctionDecl *FD, const DeclSpec &D); 1041 Decl *ActOnParamDeclarator(Scope *S, Declarator &D); 1042 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, 1043 SourceLocation Loc, 1044 QualType T); 1045 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, 1046 SourceLocation NameLoc, IdentifierInfo *Name, 1047 QualType T, TypeSourceInfo *TSInfo, 1048 StorageClass SC, StorageClass SCAsWritten); 1049 void ActOnParamDefaultArgument(Decl *param, 1050 SourceLocation EqualLoc, 1051 Expr *defarg); 1052 void ActOnParamUnparsedDefaultArgument(Decl *param, 1053 SourceLocation EqualLoc, 1054 SourceLocation ArgLoc); 1055 void ActOnParamDefaultArgumentError(Decl *param); 1056 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, 1057 SourceLocation EqualLoc); 1058 1059 void CheckSelfReference(Decl *OrigDecl, Expr *E); 1060 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit, 1061 bool TypeMayContainAuto); 1062 void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto); 1063 void ActOnInitializerError(Decl *Dcl); 1064 void ActOnCXXForRangeDecl(Decl *D); 1065 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); 1066 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); 1067 void FinalizeDeclaration(Decl *D); 1068 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 1069 Decl **Group, 1070 unsigned NumDecls); 1071 DeclGroupPtrTy BuildDeclaratorGroup(Decl **Group, unsigned NumDecls, 1072 bool TypeMayContainAuto = true); 1073 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 1074 SourceLocation LocAfterDecls); 1075 void CheckForFunctionRedefinition(FunctionDecl *FD); 1076 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D); 1077 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D); 1078 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); 1079 1080 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); 1081 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); 1082 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); 1083 1084 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an 1085 /// attribute for which parsing is delayed. 1086 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); 1087 1088 /// \brief Diagnose any unused parameters in the given sequence of 1089 /// ParmVarDecl pointers. 1090 void DiagnoseUnusedParameters(ParmVarDecl * const *Begin, 1091 ParmVarDecl * const *End); 1092 1093 /// \brief Diagnose whether the size of parameters or return value of a 1094 /// function or obj-c method definition is pass-by-value and larger than a 1095 /// specified threshold. 1096 void DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Begin, 1097 ParmVarDecl * const *End, 1098 QualType ReturnTy, 1099 NamedDecl *D); 1100 1101 void DiagnoseInvalidJumps(Stmt *Body); 1102 Decl *ActOnFileScopeAsmDecl(Expr *expr, 1103 SourceLocation AsmLoc, 1104 SourceLocation RParenLoc); 1105 1106 /// \brief The parser has processed a module import declaration. 1107 /// 1108 /// \param ImportLoc The location of the '__import_module__' keyword. 1109 /// 1110 /// \param ModuleName The name of the module. 1111 /// 1112 /// \param ModuleNameLoc The location of the module name. 1113 DeclResult ActOnModuleImport(SourceLocation ImportLoc, 1114 IdentifierInfo &ModuleName, 1115 SourceLocation ModuleNameLoc); 1116 1117 /// \brief Diagnose that \p New is a module-private redeclaration of 1118 /// \p Old. 1119 void diagnoseModulePrivateRedeclaration(NamedDecl *New, NamedDecl *Old, 1120 SourceLocation ModulePrivateKeyword 1121 = SourceLocation()); 1122 1123 /// \brief Retrieve a suitable printing policy. 1124 PrintingPolicy getPrintingPolicy() const; 1125 1126 /// Scope actions. 1127 void ActOnPopScope(SourceLocation Loc, Scope *S); 1128 void ActOnTranslationUnitScope(Scope *S); 1129 1130 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 1131 DeclSpec &DS); 1132 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 1133 DeclSpec &DS, 1134 MultiTemplateParamsArg TemplateParams); 1135 1136 StmtResult ActOnVlaStmt(const DeclSpec &DS); 1137 1138 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 1139 AccessSpecifier AS, 1140 RecordDecl *Record); 1141 1142 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 1143 RecordDecl *Record); 1144 1145 bool isAcceptableTagRedeclaration(const TagDecl *Previous, 1146 TagTypeKind NewTag, bool isDefinition, 1147 SourceLocation NewTagLoc, 1148 const IdentifierInfo &Name); 1149 1150 enum TagUseKind { 1151 TUK_Reference, // Reference to a tag: 'struct foo *X;' 1152 TUK_Declaration, // Fwd decl of a tag: 'struct foo;' 1153 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' 1154 TUK_Friend // Friend declaration: 'friend struct foo;' 1155 }; 1156 1157 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 1158 SourceLocation KWLoc, CXXScopeSpec &SS, 1159 IdentifierInfo *Name, SourceLocation NameLoc, 1160 AttributeList *Attr, AccessSpecifier AS, 1161 SourceLocation ModulePrivateLoc, 1162 MultiTemplateParamsArg TemplateParameterLists, 1163 bool &OwnedDecl, bool &IsDependent, bool ScopedEnum, 1164 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType); 1165 1166 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 1167 unsigned TagSpec, SourceLocation TagLoc, 1168 CXXScopeSpec &SS, 1169 IdentifierInfo *Name, SourceLocation NameLoc, 1170 AttributeList *Attr, 1171 MultiTemplateParamsArg TempParamLists); 1172 1173 TypeResult ActOnDependentTag(Scope *S, 1174 unsigned TagSpec, 1175 TagUseKind TUK, 1176 const CXXScopeSpec &SS, 1177 IdentifierInfo *Name, 1178 SourceLocation TagLoc, 1179 SourceLocation NameLoc); 1180 1181 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, 1182 IdentifierInfo *ClassName, 1183 SmallVectorImpl<Decl *> &Decls); 1184 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 1185 Declarator &D, Expr *BitfieldWidth); 1186 1187 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, 1188 Declarator &D, Expr *BitfieldWidth, bool HasInit, 1189 AccessSpecifier AS); 1190 1191 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, 1192 TypeSourceInfo *TInfo, 1193 RecordDecl *Record, SourceLocation Loc, 1194 bool Mutable, Expr *BitfieldWidth, bool HasInit, 1195 SourceLocation TSSL, 1196 AccessSpecifier AS, NamedDecl *PrevDecl, 1197 Declarator *D = 0); 1198 1199 enum CXXSpecialMember { 1200 CXXDefaultConstructor, 1201 CXXCopyConstructor, 1202 CXXMoveConstructor, 1203 CXXCopyAssignment, 1204 CXXMoveAssignment, 1205 CXXDestructor, 1206 CXXInvalid 1207 }; 1208 bool CheckNontrivialField(FieldDecl *FD); 1209 void DiagnoseNontrivial(const RecordType* Record, CXXSpecialMember mem); 1210 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD); 1211 void ActOnLastBitfield(SourceLocation DeclStart, 1212 SmallVectorImpl<Decl *> &AllIvarDecls); 1213 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, 1214 Declarator &D, Expr *BitfieldWidth, 1215 tok::ObjCKeywordKind visibility); 1216 1217 // This is used for both record definitions and ObjC interface declarations. 1218 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl, 1219 llvm::ArrayRef<Decl *> Fields, 1220 SourceLocation LBrac, SourceLocation RBrac, 1221 AttributeList *AttrList); 1222 1223 /// ActOnTagStartDefinition - Invoked when we have entered the 1224 /// scope of a tag's definition (e.g., for an enumeration, class, 1225 /// struct, or union). 1226 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); 1227 1228 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl); 1229 1230 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a 1231 /// C++ record definition's base-specifiers clause and are starting its 1232 /// member declarations. 1233 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, 1234 SourceLocation FinalLoc, 1235 SourceLocation LBraceLoc); 1236 1237 /// ActOnTagFinishDefinition - Invoked once we have finished parsing 1238 /// the definition of a tag (enumeration, class, struct, or union). 1239 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, 1240 SourceLocation RBraceLoc); 1241 1242 void ActOnObjCContainerFinishDefinition(); 1243 1244 /// \brief Invoked when we must temporarily exit the objective-c container 1245 /// scope for parsing/looking-up C constructs. 1246 /// 1247 /// Must be followed by a call to \see ActOnObjCReenterContainerContext 1248 void ActOnObjCTemporaryExitContainerContext(); 1249 void ActOnObjCReenterContainerContext(); 1250 1251 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable 1252 /// error parsing the definition of a tag. 1253 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); 1254 1255 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, 1256 EnumConstantDecl *LastEnumConst, 1257 SourceLocation IdLoc, 1258 IdentifierInfo *Id, 1259 Expr *val); 1260 1261 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, 1262 SourceLocation IdLoc, IdentifierInfo *Id, 1263 AttributeList *Attrs, 1264 SourceLocation EqualLoc, Expr *Val); 1265 void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 1266 SourceLocation RBraceLoc, Decl *EnumDecl, 1267 Decl **Elements, unsigned NumElements, 1268 Scope *S, AttributeList *Attr); 1269 1270 DeclContext *getContainingDC(DeclContext *DC); 1271 1272 /// Set the current declaration context until it gets popped. 1273 void PushDeclContext(Scope *S, DeclContext *DC); 1274 void PopDeclContext(); 1275 1276 /// EnterDeclaratorContext - Used when we must lookup names in the context 1277 /// of a declarator's nested name specifier. 1278 void EnterDeclaratorContext(Scope *S, DeclContext *DC); 1279 void ExitDeclaratorContext(Scope *S); 1280 1281 /// Push the parameters of D, which must be a function, into scope. 1282 void ActOnReenterFunctionContext(Scope* S, Decl* D); 1283 void ActOnExitFunctionContext() { PopDeclContext(); } 1284 1285 DeclContext *getFunctionLevelDeclContext(); 1286 1287 /// getCurFunctionDecl - If inside of a function body, this returns a pointer 1288 /// to the function decl for the function being parsed. If we're currently 1289 /// in a 'block', this returns the containing context. 1290 FunctionDecl *getCurFunctionDecl(); 1291 1292 /// getCurMethodDecl - If inside of a method body, this returns a pointer to 1293 /// the method decl for the method being parsed. If we're currently 1294 /// in a 'block', this returns the containing context. 1295 ObjCMethodDecl *getCurMethodDecl(); 1296 1297 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method 1298 /// or C function we're in, otherwise return null. If we're currently 1299 /// in a 'block', this returns the containing context. 1300 NamedDecl *getCurFunctionOrMethodDecl(); 1301 1302 /// Add this decl to the scope shadowed decl chains. 1303 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); 1304 1305 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true 1306 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns 1307 /// true if 'D' belongs to the given declaration context. 1308 /// 1309 /// \param ExplicitInstantiationOrSpecialization When true, we are checking 1310 /// whether the declaration is in scope for the purposes of explicit template 1311 /// instantiation or specialization. The default is false. 1312 bool isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S = 0, 1313 bool ExplicitInstantiationOrSpecialization = false); 1314 1315 /// Finds the scope corresponding to the given decl context, if it 1316 /// happens to be an enclosing scope. Otherwise return NULL. 1317 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); 1318 1319 /// Subroutines of ActOnDeclarator(). 1320 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 1321 TypeSourceInfo *TInfo); 1322 void MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls); 1323 bool MergeFunctionDecl(FunctionDecl *New, Decl *Old); 1324 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old); 1325 void mergeObjCMethodDecls(ObjCMethodDecl *New, const ObjCMethodDecl *Old); 1326 void MergeVarDecl(VarDecl *New, LookupResult &OldDecls); 1327 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old); 1328 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); 1329 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old); 1330 1331 // AssignmentAction - This is used by all the assignment diagnostic functions 1332 // to represent what is actually causing the operation 1333 enum AssignmentAction { 1334 AA_Assigning, 1335 AA_Passing, 1336 AA_Returning, 1337 AA_Converting, 1338 AA_Initializing, 1339 AA_Sending, 1340 AA_Casting 1341 }; 1342 1343 /// C++ Overloading. 1344 enum OverloadKind { 1345 /// This is a legitimate overload: the existing declarations are 1346 /// functions or function templates with different signatures. 1347 Ovl_Overload, 1348 1349 /// This is not an overload because the signature exactly matches 1350 /// an existing declaration. 1351 Ovl_Match, 1352 1353 /// This is not an overload because the lookup results contain a 1354 /// non-function. 1355 Ovl_NonFunction 1356 }; 1357 OverloadKind CheckOverload(Scope *S, 1358 FunctionDecl *New, 1359 const LookupResult &OldDecls, 1360 NamedDecl *&OldDecl, 1361 bool IsForUsingDecl); 1362 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl); 1363 1364 /// \brief Checks availability of the function depending on the current 1365 /// function context.Inside an unavailable function,unavailability is ignored. 1366 /// 1367 /// \returns true if \arg FD is unavailable and current context is inside 1368 /// an available function, false otherwise. 1369 bool isFunctionConsideredUnavailable(FunctionDecl *FD); 1370 1371 ImplicitConversionSequence 1372 TryImplicitConversion(Expr *From, QualType ToType, 1373 bool SuppressUserConversions, 1374 bool AllowExplicit, 1375 bool InOverloadResolution, 1376 bool CStyle, 1377 bool AllowObjCWritebackConversion); 1378 1379 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); 1380 bool IsFloatingPointPromotion(QualType FromType, QualType ToType); 1381 bool IsComplexPromotion(QualType FromType, QualType ToType); 1382 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1383 bool InOverloadResolution, 1384 QualType& ConvertedType, bool &IncompatibleObjC); 1385 bool isObjCPointerConversion(QualType FromType, QualType ToType, 1386 QualType& ConvertedType, bool &IncompatibleObjC); 1387 bool isObjCWritebackConversion(QualType FromType, QualType ToType, 1388 QualType &ConvertedType); 1389 bool IsBlockPointerConversion(QualType FromType, QualType ToType, 1390 QualType& ConvertedType); 1391 bool FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 1392 const FunctionProtoType *NewType); 1393 1394 CastKind PrepareCastToObjCObjectPointer(ExprResult &E); 1395 bool CheckPointerConversion(Expr *From, QualType ToType, 1396 CastKind &Kind, 1397 CXXCastPath& BasePath, 1398 bool IgnoreBaseAccess); 1399 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, 1400 bool InOverloadResolution, 1401 QualType &ConvertedType); 1402 bool CheckMemberPointerConversion(Expr *From, QualType ToType, 1403 CastKind &Kind, 1404 CXXCastPath &BasePath, 1405 bool IgnoreBaseAccess); 1406 bool IsQualificationConversion(QualType FromType, QualType ToType, 1407 bool CStyle, bool &ObjCLifetimeConversion); 1408 bool IsNoReturnConversion(QualType FromType, QualType ToType, 1409 QualType &ResultTy); 1410 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); 1411 1412 1413 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, 1414 const VarDecl *NRVOCandidate, 1415 QualType ResultType, 1416 Expr *Value, 1417 bool AllowNRVO = true); 1418 1419 bool CanPerformCopyInitialization(const InitializedEntity &Entity, 1420 ExprResult Init); 1421 ExprResult PerformCopyInitialization(const InitializedEntity &Entity, 1422 SourceLocation EqualLoc, 1423 ExprResult Init, 1424 bool TopLevelOfInitList = false); 1425 ExprResult PerformObjectArgumentInitialization(Expr *From, 1426 NestedNameSpecifier *Qualifier, 1427 NamedDecl *FoundDecl, 1428 CXXMethodDecl *Method); 1429 1430 ExprResult PerformContextuallyConvertToBool(Expr *From); 1431 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); 1432 1433 ExprResult 1434 ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *FromE, 1435 const PartialDiagnostic &NotIntDiag, 1436 const PartialDiagnostic &IncompleteDiag, 1437 const PartialDiagnostic &ExplicitConvDiag, 1438 const PartialDiagnostic &ExplicitConvNote, 1439 const PartialDiagnostic &AmbigDiag, 1440 const PartialDiagnostic &AmbigNote, 1441 const PartialDiagnostic &ConvDiag); 1442 1443 ExprResult PerformObjectMemberConversion(Expr *From, 1444 NestedNameSpecifier *Qualifier, 1445 NamedDecl *FoundDecl, 1446 NamedDecl *Member); 1447 1448 // Members have to be NamespaceDecl* or TranslationUnitDecl*. 1449 // TODO: make this is a typesafe union. 1450 typedef llvm::SmallPtrSet<DeclContext *, 16> AssociatedNamespaceSet; 1451 typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet; 1452 1453 void AddOverloadCandidate(NamedDecl *Function, 1454 DeclAccessPair FoundDecl, 1455 Expr **Args, unsigned NumArgs, 1456 OverloadCandidateSet &CandidateSet); 1457 1458 void AddOverloadCandidate(FunctionDecl *Function, 1459 DeclAccessPair FoundDecl, 1460 Expr **Args, unsigned NumArgs, 1461 OverloadCandidateSet& CandidateSet, 1462 bool SuppressUserConversions = false, 1463 bool PartialOverloading = false); 1464 void AddFunctionCandidates(const UnresolvedSetImpl &Functions, 1465 Expr **Args, unsigned NumArgs, 1466 OverloadCandidateSet& CandidateSet, 1467 bool SuppressUserConversions = false); 1468 void AddMethodCandidate(DeclAccessPair FoundDecl, 1469 QualType ObjectType, 1470 Expr::Classification ObjectClassification, 1471 Expr **Args, unsigned NumArgs, 1472 OverloadCandidateSet& CandidateSet, 1473 bool SuppressUserConversion = false); 1474 void AddMethodCandidate(CXXMethodDecl *Method, 1475 DeclAccessPair FoundDecl, 1476 CXXRecordDecl *ActingContext, QualType ObjectType, 1477 Expr::Classification ObjectClassification, 1478 Expr **Args, unsigned NumArgs, 1479 OverloadCandidateSet& CandidateSet, 1480 bool SuppressUserConversions = false); 1481 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 1482 DeclAccessPair FoundDecl, 1483 CXXRecordDecl *ActingContext, 1484 TemplateArgumentListInfo *ExplicitTemplateArgs, 1485 QualType ObjectType, 1486 Expr::Classification ObjectClassification, 1487 Expr **Args, unsigned NumArgs, 1488 OverloadCandidateSet& CandidateSet, 1489 bool SuppressUserConversions = false); 1490 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 1491 DeclAccessPair FoundDecl, 1492 TemplateArgumentListInfo *ExplicitTemplateArgs, 1493 Expr **Args, unsigned NumArgs, 1494 OverloadCandidateSet& CandidateSet, 1495 bool SuppressUserConversions = false); 1496 void AddConversionCandidate(CXXConversionDecl *Conversion, 1497 DeclAccessPair FoundDecl, 1498 CXXRecordDecl *ActingContext, 1499 Expr *From, QualType ToType, 1500 OverloadCandidateSet& CandidateSet); 1501 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 1502 DeclAccessPair FoundDecl, 1503 CXXRecordDecl *ActingContext, 1504 Expr *From, QualType ToType, 1505 OverloadCandidateSet &CandidateSet); 1506 void AddSurrogateCandidate(CXXConversionDecl *Conversion, 1507 DeclAccessPair FoundDecl, 1508 CXXRecordDecl *ActingContext, 1509 const FunctionProtoType *Proto, 1510 Expr *Object, Expr **Args, unsigned NumArgs, 1511 OverloadCandidateSet& CandidateSet); 1512 void AddMemberOperatorCandidates(OverloadedOperatorKind Op, 1513 SourceLocation OpLoc, 1514 Expr **Args, unsigned NumArgs, 1515 OverloadCandidateSet& CandidateSet, 1516 SourceRange OpRange = SourceRange()); 1517 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 1518 Expr **Args, unsigned NumArgs, 1519 OverloadCandidateSet& CandidateSet, 1520 bool IsAssignmentOperator = false, 1521 unsigned NumContextualBoolArguments = 0); 1522 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 1523 SourceLocation OpLoc, 1524 Expr **Args, unsigned NumArgs, 1525 OverloadCandidateSet& CandidateSet); 1526 void AddArgumentDependentLookupCandidates(DeclarationName Name, 1527 bool Operator, 1528 Expr **Args, unsigned NumArgs, 1529 TemplateArgumentListInfo *ExplicitTemplateArgs, 1530 OverloadCandidateSet& CandidateSet, 1531 bool PartialOverloading = false, 1532 bool StdNamespaceIsAssociated = false); 1533 1534 // Emit as a 'note' the specific overload candidate 1535 void NoteOverloadCandidate(FunctionDecl *Fn); 1536 1537 // Emit as a series of 'note's all template and non-templates 1538 // identified by the expression Expr 1539 void NoteAllOverloadCandidates(Expr* E); 1540 1541 // [PossiblyAFunctionType] --> [Return] 1542 // NonFunctionType --> NonFunctionType 1543 // R (A) --> R(A) 1544 // R (*)(A) --> R (A) 1545 // R (&)(A) --> R (A) 1546 // R (S::*)(A) --> R (A) 1547 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); 1548 1549 FunctionDecl *ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, 1550 bool Complain, 1551 DeclAccessPair &Found); 1552 1553 FunctionDecl *ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 1554 bool Complain = false, 1555 DeclAccessPair* Found = 0); 1556 1557 ExprResult ResolveAndFixSingleFunctionTemplateSpecialization( 1558 Expr *SrcExpr, bool DoFunctionPointerConverion = false, 1559 bool Complain = false, 1560 const SourceRange& OpRangeForComplaining = SourceRange(), 1561 QualType DestTypeForComplaining = QualType(), 1562 unsigned DiagIDForComplaining = 0); 1563 1564 1565 Expr *FixOverloadedFunctionReference(Expr *E, 1566 DeclAccessPair FoundDecl, 1567 FunctionDecl *Fn); 1568 ExprResult FixOverloadedFunctionReference(ExprResult, 1569 DeclAccessPair FoundDecl, 1570 FunctionDecl *Fn); 1571 1572 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 1573 Expr **Args, unsigned NumArgs, 1574 OverloadCandidateSet &CandidateSet, 1575 bool PartialOverloading = false); 1576 1577 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, 1578 UnresolvedLookupExpr *ULE, 1579 SourceLocation LParenLoc, 1580 Expr **Args, unsigned NumArgs, 1581 SourceLocation RParenLoc, 1582 Expr *ExecConfig); 1583 1584 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, 1585 unsigned Opc, 1586 const UnresolvedSetImpl &Fns, 1587 Expr *input); 1588 1589 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, 1590 unsigned Opc, 1591 const UnresolvedSetImpl &Fns, 1592 Expr *LHS, Expr *RHS); 1593 1594 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 1595 SourceLocation RLoc, 1596 Expr *Base,Expr *Idx); 1597 1598 ExprResult 1599 BuildCallToMemberFunction(Scope *S, Expr *MemExpr, 1600 SourceLocation LParenLoc, Expr **Args, 1601 unsigned NumArgs, SourceLocation RParenLoc); 1602 ExprResult 1603 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, 1604 Expr **Args, unsigned NumArgs, 1605 SourceLocation RParenLoc); 1606 1607 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, 1608 SourceLocation OpLoc); 1609 1610 /// CheckCallReturnType - Checks that a call expression's return type is 1611 /// complete. Returns true on failure. The location passed in is the location 1612 /// that best represents the call. 1613 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 1614 CallExpr *CE, FunctionDecl *FD); 1615 1616 /// Helpers for dealing with blocks and functions. 1617 bool CheckParmsForFunctionDef(ParmVarDecl **Param, ParmVarDecl **ParamEnd, 1618 bool CheckParameterNames); 1619 void CheckCXXDefaultArguments(FunctionDecl *FD); 1620 void CheckExtraCXXDefaultArguments(Declarator &D); 1621 Scope *getNonFieldDeclScope(Scope *S); 1622 1623 /// \name Name lookup 1624 /// 1625 /// These routines provide name lookup that is used during semantic 1626 /// analysis to resolve the various kinds of names (identifiers, 1627 /// overloaded operator names, constructor names, etc.) into zero or 1628 /// more declarations within a particular scope. The major entry 1629 /// points are LookupName, which performs unqualified name lookup, 1630 /// and LookupQualifiedName, which performs qualified name lookup. 1631 /// 1632 /// All name lookup is performed based on some specific criteria, 1633 /// which specify what names will be visible to name lookup and how 1634 /// far name lookup should work. These criteria are important both 1635 /// for capturing language semantics (certain lookups will ignore 1636 /// certain names, for example) and for performance, since name 1637 /// lookup is often a bottleneck in the compilation of C++. Name 1638 /// lookup criteria is specified via the LookupCriteria enumeration. 1639 /// 1640 /// The results of name lookup can vary based on the kind of name 1641 /// lookup performed, the current language, and the translation 1642 /// unit. In C, for example, name lookup will either return nothing 1643 /// (no entity found) or a single declaration. In C++, name lookup 1644 /// can additionally refer to a set of overloaded functions or 1645 /// result in an ambiguity. All of the possible results of name 1646 /// lookup are captured by the LookupResult class, which provides 1647 /// the ability to distinguish among them. 1648 //@{ 1649 1650 /// @brief Describes the kind of name lookup to perform. 1651 enum LookupNameKind { 1652 /// Ordinary name lookup, which finds ordinary names (functions, 1653 /// variables, typedefs, etc.) in C and most kinds of names 1654 /// (functions, variables, members, types, etc.) in C++. 1655 LookupOrdinaryName = 0, 1656 /// Tag name lookup, which finds the names of enums, classes, 1657 /// structs, and unions. 1658 LookupTagName, 1659 /// Label name lookup. 1660 LookupLabel, 1661 /// Member name lookup, which finds the names of 1662 /// class/struct/union members. 1663 LookupMemberName, 1664 /// Look up of an operator name (e.g., operator+) for use with 1665 /// operator overloading. This lookup is similar to ordinary name 1666 /// lookup, but will ignore any declarations that are class members. 1667 LookupOperatorName, 1668 /// Look up of a name that precedes the '::' scope resolution 1669 /// operator in C++. This lookup completely ignores operator, object, 1670 /// function, and enumerator names (C++ [basic.lookup.qual]p1). 1671 LookupNestedNameSpecifierName, 1672 /// Look up a namespace name within a C++ using directive or 1673 /// namespace alias definition, ignoring non-namespace names (C++ 1674 /// [basic.lookup.udir]p1). 1675 LookupNamespaceName, 1676 /// Look up all declarations in a scope with the given name, 1677 /// including resolved using declarations. This is appropriate 1678 /// for checking redeclarations for a using declaration. 1679 LookupUsingDeclName, 1680 /// Look up an ordinary name that is going to be redeclared as a 1681 /// name with linkage. This lookup ignores any declarations that 1682 /// are outside of the current scope unless they have linkage. See 1683 /// C99 6.2.2p4-5 and C++ [basic.link]p6. 1684 LookupRedeclarationWithLinkage, 1685 /// Look up the name of an Objective-C protocol. 1686 LookupObjCProtocolName, 1687 /// Look up implicit 'self' parameter of an objective-c method. 1688 LookupObjCImplicitSelfParam, 1689 /// \brief Look up any declaration with any name. 1690 LookupAnyName 1691 }; 1692 1693 /// \brief Specifies whether (or how) name lookup is being performed for a 1694 /// redeclaration (vs. a reference). 1695 enum RedeclarationKind { 1696 /// \brief The lookup is a reference to this name that is not for the 1697 /// purpose of redeclaring the name. 1698 NotForRedeclaration = 0, 1699 /// \brief The lookup results will be used for redeclaration of a name, 1700 /// if an entity by that name already exists. 1701 ForRedeclaration 1702 }; 1703 1704private: 1705 bool CppLookupName(LookupResult &R, Scope *S); 1706 1707 SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D, 1708 CXXSpecialMember SM, 1709 bool ConstArg, 1710 bool VolatileArg, 1711 bool RValueThis, 1712 bool ConstThis, 1713 bool VolatileThis); 1714 1715 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls. 1716 // 1717 // The boolean value will be true to indicate that the namespace was loaded 1718 // from an AST/PCH file, or false otherwise. 1719 llvm::DenseMap<NamespaceDecl*, bool> KnownNamespaces; 1720 1721 /// \brief Whether we have already loaded known namespaces from an extenal 1722 /// source. 1723 bool LoadedExternalKnownNamespaces; 1724 1725public: 1726 /// \brief Look up a name, looking for a single declaration. Return 1727 /// null if the results were absent, ambiguous, or overloaded. 1728 /// 1729 /// It is preferable to use the elaborated form and explicitly handle 1730 /// ambiguity and overloaded. 1731 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, 1732 SourceLocation Loc, 1733 LookupNameKind NameKind, 1734 RedeclarationKind Redecl 1735 = NotForRedeclaration); 1736 bool LookupName(LookupResult &R, Scope *S, 1737 bool AllowBuiltinCreation = false); 1738 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 1739 bool InUnqualifiedLookup = false); 1740 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 1741 bool AllowBuiltinCreation = false, 1742 bool EnteringContext = false); 1743 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc); 1744 1745 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, 1746 QualType T1, QualType T2, 1747 UnresolvedSetImpl &Functions); 1748 1749 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, 1750 SourceLocation GnuLabelLoc = SourceLocation()); 1751 1752 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); 1753 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); 1754 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, 1755 unsigned Quals, 1756 bool *ConstParam = 0); 1757 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, 1758 bool RValueThis, unsigned ThisQuals, 1759 bool *ConstParam = 0); 1760 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class); 1761 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, bool RValueThis, 1762 unsigned ThisQuals); 1763 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); 1764 1765 void ArgumentDependentLookup(DeclarationName Name, bool Operator, 1766 Expr **Args, unsigned NumArgs, 1767 ADLResult &Functions, 1768 bool StdNamespaceIsAssociated = false); 1769 1770 void LookupVisibleDecls(Scope *S, LookupNameKind Kind, 1771 VisibleDeclConsumer &Consumer, 1772 bool IncludeGlobalScope = true); 1773 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, 1774 VisibleDeclConsumer &Consumer, 1775 bool IncludeGlobalScope = true); 1776 1777 /// \brief The context in which typo-correction occurs. 1778 /// 1779 /// The typo-correction context affects which keywords (if any) are 1780 /// considered when trying to correct for typos. 1781 enum CorrectTypoContext { 1782 /// \brief An unknown context, where any keyword might be valid. 1783 CTC_Unknown, 1784 /// \brief A context where no keywords are used (e.g. we expect an actual 1785 /// name). 1786 CTC_NoKeywords, 1787 /// \brief A context where we're correcting a type name. 1788 CTC_Type, 1789 /// \brief An expression context. 1790 CTC_Expression, 1791 /// \brief A type cast, or anything else that can be followed by a '<'. 1792 CTC_CXXCasts, 1793 /// \brief A member lookup context. 1794 CTC_MemberLookup, 1795 /// \brief An Objective-C ivar lookup context (e.g., self->ivar). 1796 CTC_ObjCIvarLookup, 1797 /// \brief An Objective-C property lookup context (e.g., self.prop). 1798 CTC_ObjCPropertyLookup, 1799 /// \brief The receiver of an Objective-C message send within an 1800 /// Objective-C method where 'super' is a valid keyword. 1801 CTC_ObjCMessageReceiver 1802 }; 1803 1804 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, 1805 Sema::LookupNameKind LookupKind, 1806 Scope *S, CXXScopeSpec *SS, 1807 DeclContext *MemberContext = NULL, 1808 bool EnteringContext = false, 1809 CorrectTypoContext CTC = CTC_Unknown, 1810 const ObjCObjectPointerType *OPT = NULL); 1811 1812 void FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs, 1813 AssociatedNamespaceSet &AssociatedNamespaces, 1814 AssociatedClassSet &AssociatedClasses); 1815 1816 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1817 bool ConsiderLinkage, 1818 bool ExplicitInstantiationOrSpecialization); 1819 1820 bool DiagnoseAmbiguousLookup(LookupResult &Result); 1821 //@} 1822 1823 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, 1824 SourceLocation IdLoc, 1825 bool TypoCorrection = false); 1826 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1827 Scope *S, bool ForRedeclaration, 1828 SourceLocation Loc); 1829 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, 1830 Scope *S); 1831 void AddKnownFunctionAttributes(FunctionDecl *FD); 1832 1833 // More parsing and symbol table subroutines. 1834 1835 // Decl attributes - this routine is the top level dispatcher. 1836 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD, 1837 bool NonInheritable = true, bool Inheritable = true); 1838 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL, 1839 bool NonInheritable = true, bool Inheritable = true); 1840 1841 void checkUnusedDeclAttributes(Declarator &D); 1842 1843 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value); 1844 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC); 1845 bool CheckNoReturnAttr(const AttributeList &attr); 1846 1847 void WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method, 1848 bool &IncompleteImpl, unsigned DiagID); 1849 void WarnConflictingTypedMethods(ObjCMethodDecl *Method, 1850 ObjCMethodDecl *MethodDecl, 1851 bool IsProtocolMethodDecl); 1852 1853 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, 1854 ObjCMethodDecl *Overridden, 1855 bool IsProtocolMethodDecl); 1856 1857 /// WarnExactTypedMethods - This routine issues a warning if method 1858 /// implementation declaration matches exactly that of its declaration. 1859 void WarnExactTypedMethods(ObjCMethodDecl *Method, 1860 ObjCMethodDecl *MethodDecl, 1861 bool IsProtocolMethodDecl); 1862 1863 bool isPropertyReadonly(ObjCPropertyDecl *PropertyDecl, 1864 ObjCInterfaceDecl *IDecl); 1865 1866 typedef llvm::DenseSet<Selector, llvm::DenseMapInfo<Selector> > SelectorSet; 1867 typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap; 1868 1869 /// CheckProtocolMethodDefs - This routine checks unimplemented 1870 /// methods declared in protocol, and those referenced by it. 1871 /// \param IDecl - Used for checking for methods which may have been 1872 /// inherited. 1873 void CheckProtocolMethodDefs(SourceLocation ImpLoc, 1874 ObjCProtocolDecl *PDecl, 1875 bool& IncompleteImpl, 1876 const SelectorSet &InsMap, 1877 const SelectorSet &ClsMap, 1878 ObjCContainerDecl *CDecl); 1879 1880 /// CheckImplementationIvars - This routine checks if the instance variables 1881 /// listed in the implelementation match those listed in the interface. 1882 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, 1883 ObjCIvarDecl **Fields, unsigned nIvars, 1884 SourceLocation Loc); 1885 1886 /// ImplMethodsVsClassMethods - This is main routine to warn if any method 1887 /// remains unimplemented in the class or category @implementation. 1888 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, 1889 ObjCContainerDecl* IDecl, 1890 bool IncompleteImpl = false); 1891 1892 /// DiagnoseUnimplementedProperties - This routine warns on those properties 1893 /// which must be implemented by this implementation. 1894 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, 1895 ObjCContainerDecl *CDecl, 1896 const SelectorSet &InsMap); 1897 1898 /// DefaultSynthesizeProperties - This routine default synthesizes all 1899 /// properties which must be synthesized in class's @implementation. 1900 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl, 1901 ObjCInterfaceDecl *IDecl); 1902 void DefaultSynthesizeProperties(Scope *S, Decl *D); 1903 1904 /// CollectImmediateProperties - This routine collects all properties in 1905 /// the class and its conforming protocols; but not those it its super class. 1906 void CollectImmediateProperties(ObjCContainerDecl *CDecl, 1907 llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& PropMap, 1908 llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& SuperPropMap); 1909 1910 1911 /// LookupPropertyDecl - Looks up a property in the current class and all 1912 /// its protocols. 1913 ObjCPropertyDecl *LookupPropertyDecl(const ObjCContainerDecl *CDecl, 1914 IdentifierInfo *II); 1915 1916 /// Called by ActOnProperty to handle @property declarations in 1917 //// class extensions. 1918 Decl *HandlePropertyInClassExtension(Scope *S, 1919 SourceLocation AtLoc, 1920 FieldDeclarator &FD, 1921 Selector GetterSel, 1922 Selector SetterSel, 1923 const bool isAssign, 1924 const bool isReadWrite, 1925 const unsigned Attributes, 1926 bool *isOverridingProperty, 1927 TypeSourceInfo *T, 1928 tok::ObjCKeywordKind MethodImplKind); 1929 1930 /// Called by ActOnProperty and HandlePropertyInClassExtension to 1931 /// handle creating the ObjcPropertyDecl for a category or @interface. 1932 ObjCPropertyDecl *CreatePropertyDecl(Scope *S, 1933 ObjCContainerDecl *CDecl, 1934 SourceLocation AtLoc, 1935 FieldDeclarator &FD, 1936 Selector GetterSel, 1937 Selector SetterSel, 1938 const bool isAssign, 1939 const bool isReadWrite, 1940 const unsigned Attributes, 1941 TypeSourceInfo *T, 1942 tok::ObjCKeywordKind MethodImplKind, 1943 DeclContext *lexicalDC = 0); 1944 1945 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via 1946 /// warning) when atomic property has one but not the other user-declared 1947 /// setter or getter. 1948 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, 1949 ObjCContainerDecl* IDecl); 1950 1951 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); 1952 1953 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); 1954 1955 enum MethodMatchStrategy { 1956 MMS_loose, 1957 MMS_strict 1958 }; 1959 1960 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns 1961 /// true, or false, accordingly. 1962 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, 1963 const ObjCMethodDecl *PrevMethod, 1964 MethodMatchStrategy strategy = MMS_strict); 1965 1966 /// MatchAllMethodDeclarations - Check methods declaraed in interface or 1967 /// or protocol against those declared in their implementations. 1968 void MatchAllMethodDeclarations(const SelectorSet &InsMap, 1969 const SelectorSet &ClsMap, 1970 SelectorSet &InsMapSeen, 1971 SelectorSet &ClsMapSeen, 1972 ObjCImplDecl* IMPDecl, 1973 ObjCContainerDecl* IDecl, 1974 bool &IncompleteImpl, 1975 bool ImmediateClass, 1976 bool WarnExactMatch=false); 1977 1978 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in 1979 /// category matches with those implemented in its primary class and 1980 /// warns each time an exact match is found. 1981 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); 1982 1983private: 1984 /// AddMethodToGlobalPool - Add an instance or factory method to the global 1985 /// pool. See descriptoin of AddInstanceMethodToGlobalPool. 1986 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); 1987 1988 /// LookupMethodInGlobalPool - Returns the instance or factory method and 1989 /// optionally warns if there are multiple signatures. 1990 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, 1991 bool receiverIdOrClass, 1992 bool warn, bool instance); 1993 1994public: 1995 /// AddInstanceMethodToGlobalPool - All instance methods in a translation 1996 /// unit are added to a global pool. This allows us to efficiently associate 1997 /// a selector with a method declaraation for purposes of typechecking 1998 /// messages sent to "id" (where the class of the object is unknown). 1999 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 2000 AddMethodToGlobalPool(Method, impl, /*instance*/true); 2001 } 2002 2003 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. 2004 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 2005 AddMethodToGlobalPool(Method, impl, /*instance*/false); 2006 } 2007 2008 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global 2009 /// pool. 2010 void AddAnyMethodToGlobalPool(Decl *D); 2011 2012 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if 2013 /// there are multiple signatures. 2014 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, 2015 bool receiverIdOrClass=false, 2016 bool warn=true) { 2017 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 2018 warn, /*instance*/true); 2019 } 2020 2021 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if 2022 /// there are multiple signatures. 2023 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, 2024 bool receiverIdOrClass=false, 2025 bool warn=true) { 2026 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 2027 warn, /*instance*/false); 2028 } 2029 2030 /// LookupImplementedMethodInGlobalPool - Returns the method which has an 2031 /// implementation. 2032 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); 2033 2034 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require 2035 /// initialization. 2036 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, 2037 SmallVectorImpl<ObjCIvarDecl*> &Ivars); 2038 2039 //===--------------------------------------------------------------------===// 2040 // Statement Parsing Callbacks: SemaStmt.cpp. 2041public: 2042 class FullExprArg { 2043 public: 2044 FullExprArg(Sema &actions) : E(0) { } 2045 2046 // FIXME: The const_cast here is ugly. RValue references would make this 2047 // much nicer (or we could duplicate a bunch of the move semantics 2048 // emulation code from Ownership.h). 2049 FullExprArg(const FullExprArg& Other) : E(Other.E) {} 2050 2051 ExprResult release() { 2052 return move(E); 2053 } 2054 2055 Expr *get() const { return E; } 2056 2057 Expr *operator->() { 2058 return E; 2059 } 2060 2061 private: 2062 // FIXME: No need to make the entire Sema class a friend when it's just 2063 // Sema::MakeFullExpr that needs access to the constructor below. 2064 friend class Sema; 2065 2066 explicit FullExprArg(Expr *expr) : E(expr) {} 2067 2068 Expr *E; 2069 }; 2070 2071 FullExprArg MakeFullExpr(Expr *Arg) { 2072 return FullExprArg(ActOnFinishFullExpr(Arg).release()); 2073 } 2074 2075 StmtResult ActOnExprStmt(FullExprArg Expr); 2076 2077 StmtResult ActOnNullStmt(SourceLocation SemiLoc, 2078 bool HasLeadingEmptyMacro = false); 2079 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, 2080 MultiStmtArg Elts, 2081 bool isStmtExpr); 2082 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, 2083 SourceLocation StartLoc, 2084 SourceLocation EndLoc); 2085 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); 2086 StmtResult ActOnForEachLValueExpr(Expr *E); 2087 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal, 2088 SourceLocation DotDotDotLoc, Expr *RHSVal, 2089 SourceLocation ColonLoc); 2090 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); 2091 2092 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, 2093 SourceLocation ColonLoc, 2094 Stmt *SubStmt, Scope *CurScope); 2095 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, 2096 SourceLocation ColonLoc, Stmt *SubStmt); 2097 2098 StmtResult ActOnIfStmt(SourceLocation IfLoc, 2099 FullExprArg CondVal, Decl *CondVar, 2100 Stmt *ThenVal, 2101 SourceLocation ElseLoc, Stmt *ElseVal); 2102 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, 2103 Expr *Cond, 2104 Decl *CondVar); 2105 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, 2106 Stmt *Switch, Stmt *Body); 2107 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, 2108 FullExprArg Cond, 2109 Decl *CondVar, Stmt *Body); 2110 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 2111 SourceLocation WhileLoc, 2112 SourceLocation CondLParen, Expr *Cond, 2113 SourceLocation CondRParen); 2114 2115 StmtResult ActOnForStmt(SourceLocation ForLoc, 2116 SourceLocation LParenLoc, 2117 Stmt *First, FullExprArg Second, 2118 Decl *SecondVar, 2119 FullExprArg Third, 2120 SourceLocation RParenLoc, 2121 Stmt *Body); 2122 ExprResult ActOnObjCForCollectionOperand(SourceLocation forLoc, 2123 Expr *collection); 2124 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, 2125 SourceLocation LParenLoc, 2126 Stmt *First, Expr *Second, 2127 SourceLocation RParenLoc, Stmt *Body); 2128 StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc, 2129 SourceLocation LParenLoc, Stmt *LoopVar, 2130 SourceLocation ColonLoc, Expr *Collection, 2131 SourceLocation RParenLoc); 2132 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, 2133 SourceLocation ColonLoc, 2134 Stmt *RangeDecl, Stmt *BeginEndDecl, 2135 Expr *Cond, Expr *Inc, 2136 Stmt *LoopVarDecl, 2137 SourceLocation RParenLoc); 2138 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); 2139 2140 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, 2141 SourceLocation LabelLoc, 2142 LabelDecl *TheDecl); 2143 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, 2144 SourceLocation StarLoc, 2145 Expr *DestExp); 2146 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); 2147 StmtResult ActOnBreakStmt(SourceLocation GotoLoc, Scope *CurScope); 2148 2149 const VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E, 2150 bool AllowFunctionParameters); 2151 2152 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); 2153 StmtResult ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); 2154 2155 StmtResult ActOnAsmStmt(SourceLocation AsmLoc, 2156 bool IsSimple, bool IsVolatile, 2157 unsigned NumOutputs, unsigned NumInputs, 2158 IdentifierInfo **Names, 2159 MultiExprArg Constraints, 2160 MultiExprArg Exprs, 2161 Expr *AsmString, 2162 MultiExprArg Clobbers, 2163 SourceLocation RParenLoc, 2164 bool MSAsm = false); 2165 2166 2167 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, 2168 SourceLocation StartLoc, 2169 SourceLocation IdLoc, IdentifierInfo *Id, 2170 bool Invalid = false); 2171 2172 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); 2173 2174 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, 2175 Decl *Parm, Stmt *Body); 2176 2177 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); 2178 2179 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 2180 MultiStmtArg Catch, Stmt *Finally); 2181 2182 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); 2183 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 2184 Scope *CurScope); 2185 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, 2186 Expr *operand); 2187 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, 2188 Expr *SynchExpr, 2189 Stmt *SynchBody); 2190 2191 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); 2192 2193 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, 2194 SourceLocation StartLoc, 2195 SourceLocation IdLoc, 2196 IdentifierInfo *Id); 2197 2198 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); 2199 2200 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, 2201 Decl *ExDecl, Stmt *HandlerBlock); 2202 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 2203 MultiStmtArg Handlers); 2204 2205 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? 2206 SourceLocation TryLoc, 2207 Stmt *TryBlock, 2208 Stmt *Handler); 2209 2210 StmtResult ActOnSEHExceptBlock(SourceLocation Loc, 2211 Expr *FilterExpr, 2212 Stmt *Block); 2213 2214 StmtResult ActOnSEHFinallyBlock(SourceLocation Loc, 2215 Stmt *Block); 2216 2217 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); 2218 2219 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; 2220 2221 /// \brief If it's a file scoped decl that must warn if not used, keep track 2222 /// of it. 2223 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); 2224 2225 /// DiagnoseUnusedExprResult - If the statement passed in is an expression 2226 /// whose result is unused, warn. 2227 void DiagnoseUnusedExprResult(const Stmt *S); 2228 void DiagnoseUnusedDecl(const NamedDecl *ND); 2229 2230 ParsingDeclState PushParsingDeclaration() { 2231 return DelayedDiagnostics.pushParsingDecl(); 2232 } 2233 void PopParsingDeclaration(ParsingDeclState state, Decl *decl) { 2234 DelayedDiagnostics::popParsingDecl(*this, state, decl); 2235 } 2236 2237 typedef ProcessingContextState ParsingClassState; 2238 ParsingClassState PushParsingClass() { 2239 return DelayedDiagnostics.pushContext(); 2240 } 2241 void PopParsingClass(ParsingClassState state) { 2242 DelayedDiagnostics.popContext(state); 2243 } 2244 2245 void EmitDeprecationWarning(NamedDecl *D, StringRef Message, 2246 SourceLocation Loc, 2247 const ObjCInterfaceDecl *UnknownObjCClass=0); 2248 2249 void HandleDelayedDeprecationCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 2250 2251 bool makeUnavailableInSystemHeader(SourceLocation loc, 2252 StringRef message); 2253 2254 //===--------------------------------------------------------------------===// 2255 // Expression Parsing Callbacks: SemaExpr.cpp. 2256 2257 bool CanUseDecl(NamedDecl *D); 2258 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 2259 const ObjCInterfaceDecl *UnknownObjCClass=0); 2260 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD); 2261 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, 2262 ObjCMethodDecl *Getter, 2263 SourceLocation Loc); 2264 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 2265 Expr **Args, unsigned NumArgs); 2266 2267 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext); 2268 2269 void PopExpressionEvaluationContext(); 2270 2271 void DiscardCleanupsInEvaluationContext(); 2272 2273 void MarkDeclarationReferenced(SourceLocation Loc, Decl *D); 2274 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); 2275 void MarkDeclarationsReferencedInExpr(Expr *E); 2276 2277 /// \brief Figure out if an expression could be turned into a call. 2278 bool isExprCallable(const Expr &E, QualType &ZeroArgCallReturnTy, 2279 UnresolvedSetImpl &NonTemplateOverloads); 2280 /// \brief Give notes for a set of overloads. 2281 void NoteOverloads(const UnresolvedSetImpl &Overloads, 2282 const SourceLocation FinalNoteLoc); 2283 2284 /// \brief Conditionally issue a diagnostic based on the current 2285 /// evaluation context. 2286 /// 2287 /// \param stmt - If stmt is non-null, delay reporting the diagnostic until 2288 /// the function body is parsed, and then do a basic reachability analysis to 2289 /// determine if the statement is reachable. If it is unreachable, the 2290 /// diagnostic will not be emitted. 2291 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 2292 const PartialDiagnostic &PD); 2293 2294 // Primary Expressions. 2295 SourceRange getExprRange(Expr *E) const; 2296 2297 ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, UnqualifiedId &Id, 2298 bool HasTrailingLParen, bool IsAddressOfOperand); 2299 2300 void DecomposeUnqualifiedId(const UnqualifiedId &Id, 2301 TemplateArgumentListInfo &Buffer, 2302 DeclarationNameInfo &NameInfo, 2303 const TemplateArgumentListInfo *&TemplateArgs); 2304 2305 bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2306 CorrectTypoContext CTC = CTC_Unknown, 2307 TemplateArgumentListInfo *ExplicitTemplateArgs = 0, 2308 Expr **Args = 0, unsigned NumArgs = 0); 2309 2310 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, 2311 IdentifierInfo *II, 2312 bool AllowBuiltinCreation=false); 2313 2314 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, 2315 const DeclarationNameInfo &NameInfo, 2316 bool isAddressOfOperand, 2317 const TemplateArgumentListInfo *TemplateArgs); 2318 2319 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, 2320 ExprValueKind VK, 2321 SourceLocation Loc, 2322 const CXXScopeSpec *SS = 0); 2323 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, 2324 ExprValueKind VK, 2325 const DeclarationNameInfo &NameInfo, 2326 const CXXScopeSpec *SS = 0); 2327 ExprResult 2328 BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, 2329 SourceLocation nameLoc, 2330 IndirectFieldDecl *indirectField, 2331 Expr *baseObjectExpr = 0, 2332 SourceLocation opLoc = SourceLocation()); 2333 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, 2334 LookupResult &R, 2335 const TemplateArgumentListInfo *TemplateArgs); 2336 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, 2337 LookupResult &R, 2338 const TemplateArgumentListInfo *TemplateArgs, 2339 bool IsDefiniteInstance); 2340 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, 2341 const LookupResult &R, 2342 bool HasTrailingLParen); 2343 2344 ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 2345 const DeclarationNameInfo &NameInfo); 2346 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, 2347 const DeclarationNameInfo &NameInfo, 2348 const TemplateArgumentListInfo *TemplateArgs); 2349 2350 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2351 LookupResult &R, 2352 bool NeedsADL); 2353 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2354 const DeclarationNameInfo &NameInfo, 2355 NamedDecl *D); 2356 2357 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); 2358 ExprResult ActOnNumericConstant(const Token &Tok); 2359 ExprResult ActOnCharacterConstant(const Token &Tok); 2360 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); 2361 ExprResult ActOnParenOrParenListExpr(SourceLocation L, 2362 SourceLocation R, 2363 MultiExprArg Val); 2364 2365 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 2366 /// fragments (e.g. "foo" "bar" L"baz"). 2367 ExprResult ActOnStringLiteral(const Token *StringToks, 2368 unsigned NumStringToks); 2369 2370 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, 2371 SourceLocation DefaultLoc, 2372 SourceLocation RParenLoc, 2373 Expr *ControllingExpr, 2374 MultiTypeArg ArgTypes, 2375 MultiExprArg ArgExprs); 2376 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, 2377 SourceLocation DefaultLoc, 2378 SourceLocation RParenLoc, 2379 Expr *ControllingExpr, 2380 TypeSourceInfo **Types, 2381 Expr **Exprs, 2382 unsigned NumAssocs); 2383 2384 // Binary/Unary Operators. 'Tok' is the token for the operator. 2385 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 2386 Expr *InputExpr); 2387 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, 2388 UnaryOperatorKind Opc, Expr *Input); 2389 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 2390 tok::TokenKind Op, Expr *Input); 2391 2392 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 2393 SourceLocation OpLoc, 2394 UnaryExprOrTypeTrait ExprKind, 2395 SourceRange R); 2396 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 2397 UnaryExprOrTypeTrait ExprKind); 2398 ExprResult 2399 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 2400 UnaryExprOrTypeTrait ExprKind, 2401 bool IsType, void *TyOrEx, 2402 const SourceRange &ArgRange); 2403 2404 ExprResult CheckPlaceholderExpr(Expr *E); 2405 bool CheckVecStepExpr(Expr *E); 2406 2407 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); 2408 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, 2409 SourceRange ExprRange, 2410 UnaryExprOrTypeTrait ExprKind); 2411 ExprResult ActOnSizeofParameterPackExpr(Scope *S, 2412 SourceLocation OpLoc, 2413 IdentifierInfo &Name, 2414 SourceLocation NameLoc, 2415 SourceLocation RParenLoc); 2416 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 2417 tok::TokenKind Kind, Expr *Input); 2418 2419 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, 2420 Expr *Idx, SourceLocation RLoc); 2421 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 2422 Expr *Idx, SourceLocation RLoc); 2423 2424 ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, 2425 SourceLocation OpLoc, bool IsArrow, 2426 CXXScopeSpec &SS, 2427 NamedDecl *FirstQualifierInScope, 2428 const DeclarationNameInfo &NameInfo, 2429 const TemplateArgumentListInfo *TemplateArgs); 2430 2431 ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, 2432 SourceLocation OpLoc, bool IsArrow, 2433 const CXXScopeSpec &SS, 2434 NamedDecl *FirstQualifierInScope, 2435 LookupResult &R, 2436 const TemplateArgumentListInfo *TemplateArgs, 2437 bool SuppressQualifierCheck = false); 2438 2439 ExprResult LookupMemberExpr(LookupResult &R, ExprResult &Base, 2440 bool &IsArrow, SourceLocation OpLoc, 2441 CXXScopeSpec &SS, 2442 Decl *ObjCImpDecl, 2443 bool HasTemplateArgs); 2444 2445 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, 2446 const CXXScopeSpec &SS, 2447 const LookupResult &R); 2448 2449 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, 2450 bool IsArrow, SourceLocation OpLoc, 2451 const CXXScopeSpec &SS, 2452 NamedDecl *FirstQualifierInScope, 2453 const DeclarationNameInfo &NameInfo, 2454 const TemplateArgumentListInfo *TemplateArgs); 2455 2456 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, 2457 SourceLocation OpLoc, 2458 tok::TokenKind OpKind, 2459 CXXScopeSpec &SS, 2460 UnqualifiedId &Member, 2461 Decl *ObjCImpDecl, 2462 bool HasTrailingLParen); 2463 2464 void ActOnDefaultCtorInitializers(Decl *CDtorDecl); 2465 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 2466 FunctionDecl *FDecl, 2467 const FunctionProtoType *Proto, 2468 Expr **Args, unsigned NumArgs, 2469 SourceLocation RParenLoc, 2470 bool ExecConfig = false); 2471 2472 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 2473 /// This provides the location of the left/right parens and a list of comma 2474 /// locations. 2475 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 2476 MultiExprArg ArgExprs, SourceLocation RParenLoc, 2477 Expr *ExecConfig = 0, bool IsExecConfig = false); 2478 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 2479 SourceLocation LParenLoc, 2480 Expr **Args, unsigned NumArgs, 2481 SourceLocation RParenLoc, 2482 Expr *Config = 0, 2483 bool IsExecConfig = false); 2484 2485 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 2486 MultiExprArg ExecConfig, 2487 SourceLocation GGGLoc); 2488 2489 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 2490 Declarator &D, ParsedType &Ty, 2491 SourceLocation RParenLoc, Expr *CastExpr); 2492 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, 2493 TypeSourceInfo *Ty, 2494 SourceLocation RParenLoc, 2495 Expr *Op); 2496 CastKind PrepareScalarCast(ExprResult &src, QualType destType); 2497 2498 /// \brief Build an altivec or OpenCL literal. 2499 ExprResult BuildVectorLiteral(SourceLocation LParenLoc, 2500 SourceLocation RParenLoc, Expr *E, 2501 TypeSourceInfo *TInfo); 2502 2503 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); 2504 2505 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, 2506 ParsedType Ty, 2507 SourceLocation RParenLoc, 2508 Expr *InitExpr); 2509 2510 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, 2511 TypeSourceInfo *TInfo, 2512 SourceLocation RParenLoc, 2513 Expr *LiteralExpr); 2514 2515 ExprResult ActOnInitList(SourceLocation LBraceLoc, 2516 MultiExprArg InitArgList, 2517 SourceLocation RBraceLoc); 2518 2519 ExprResult ActOnDesignatedInitializer(Designation &Desig, 2520 SourceLocation Loc, 2521 bool GNUSyntax, 2522 ExprResult Init); 2523 2524 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, 2525 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); 2526 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, 2527 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); 2528 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, 2529 Expr *LHSExpr, Expr *RHSExpr); 2530 2531 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 2532 /// in the case of a the GNU conditional expr extension. 2533 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, 2534 SourceLocation ColonLoc, 2535 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); 2536 2537 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 2538 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 2539 LabelDecl *TheDecl); 2540 2541 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 2542 SourceLocation RPLoc); // "({..})" 2543 2544 // __builtin_offsetof(type, identifier(.identifier|[expr])*) 2545 struct OffsetOfComponent { 2546 SourceLocation LocStart, LocEnd; 2547 bool isBrackets; // true if [expr], false if .ident 2548 union { 2549 IdentifierInfo *IdentInfo; 2550 Expr *E; 2551 } U; 2552 }; 2553 2554 /// __builtin_offsetof(type, a.b[123][456].c) 2555 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 2556 TypeSourceInfo *TInfo, 2557 OffsetOfComponent *CompPtr, 2558 unsigned NumComponents, 2559 SourceLocation RParenLoc); 2560 ExprResult ActOnBuiltinOffsetOf(Scope *S, 2561 SourceLocation BuiltinLoc, 2562 SourceLocation TypeLoc, 2563 ParsedType ParsedArgTy, 2564 OffsetOfComponent *CompPtr, 2565 unsigned NumComponents, 2566 SourceLocation RParenLoc); 2567 2568 // __builtin_choose_expr(constExpr, expr1, expr2) 2569 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, 2570 Expr *CondExpr, Expr *LHSExpr, 2571 Expr *RHSExpr, SourceLocation RPLoc); 2572 2573 // __builtin_va_arg(expr, type) 2574 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 2575 SourceLocation RPLoc); 2576 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, 2577 TypeSourceInfo *TInfo, SourceLocation RPLoc); 2578 2579 // __null 2580 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); 2581 2582 bool CheckCaseExpression(Expr *E); 2583 2584 bool CheckMicrosoftIfExistsSymbol(CXXScopeSpec &SS, UnqualifiedId &Name); 2585 2586 //===------------------------- "Block" Extension ------------------------===// 2587 2588 /// ActOnBlockStart - This callback is invoked when a block literal is 2589 /// started. 2590 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); 2591 2592 /// ActOnBlockArguments - This callback allows processing of block arguments. 2593 /// If there are no arguments, this is still invoked. 2594 void ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope); 2595 2596 /// ActOnBlockError - If there is an error parsing a block, this callback 2597 /// is invoked to pop the information about the block from the action impl. 2598 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); 2599 2600 /// ActOnBlockStmtExpr - This is called when the body of a block statement 2601 /// literal was successfully completed. ^(int x){...} 2602 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, 2603 Scope *CurScope); 2604 2605 //===---------------------------- OpenCL Features -----------------------===// 2606 2607 /// __builtin_astype(...) 2608 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 2609 SourceLocation BuiltinLoc, 2610 SourceLocation RParenLoc); 2611 2612 //===---------------------------- C++ Features --------------------------===// 2613 2614 // Act on C++ namespaces 2615 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, 2616 SourceLocation NamespaceLoc, 2617 SourceLocation IdentLoc, 2618 IdentifierInfo *Ident, 2619 SourceLocation LBrace, 2620 AttributeList *AttrList); 2621 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); 2622 2623 NamespaceDecl *getStdNamespace() const; 2624 NamespaceDecl *getOrCreateStdNamespace(); 2625 2626 CXXRecordDecl *getStdBadAlloc() const; 2627 2628 Decl *ActOnUsingDirective(Scope *CurScope, 2629 SourceLocation UsingLoc, 2630 SourceLocation NamespcLoc, 2631 CXXScopeSpec &SS, 2632 SourceLocation IdentLoc, 2633 IdentifierInfo *NamespcName, 2634 AttributeList *AttrList); 2635 2636 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); 2637 2638 Decl *ActOnNamespaceAliasDef(Scope *CurScope, 2639 SourceLocation NamespaceLoc, 2640 SourceLocation AliasLoc, 2641 IdentifierInfo *Alias, 2642 CXXScopeSpec &SS, 2643 SourceLocation IdentLoc, 2644 IdentifierInfo *Ident); 2645 2646 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); 2647 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, 2648 const LookupResult &PreviousDecls); 2649 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD, 2650 NamedDecl *Target); 2651 2652 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 2653 bool isTypeName, 2654 const CXXScopeSpec &SS, 2655 SourceLocation NameLoc, 2656 const LookupResult &Previous); 2657 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, 2658 const CXXScopeSpec &SS, 2659 SourceLocation NameLoc); 2660 2661 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 2662 SourceLocation UsingLoc, 2663 CXXScopeSpec &SS, 2664 const DeclarationNameInfo &NameInfo, 2665 AttributeList *AttrList, 2666 bool IsInstantiation, 2667 bool IsTypeName, 2668 SourceLocation TypenameLoc); 2669 2670 bool CheckInheritedConstructorUsingDecl(UsingDecl *UD); 2671 2672 Decl *ActOnUsingDeclaration(Scope *CurScope, 2673 AccessSpecifier AS, 2674 bool HasUsingKeyword, 2675 SourceLocation UsingLoc, 2676 CXXScopeSpec &SS, 2677 UnqualifiedId &Name, 2678 AttributeList *AttrList, 2679 bool IsTypeName, 2680 SourceLocation TypenameLoc); 2681 Decl *ActOnAliasDeclaration(Scope *CurScope, 2682 AccessSpecifier AS, 2683 MultiTemplateParamsArg TemplateParams, 2684 SourceLocation UsingLoc, 2685 UnqualifiedId &Name, 2686 TypeResult Type); 2687 2688 /// AddCXXDirectInitializerToDecl - This action is called immediately after 2689 /// ActOnDeclarator, when a C++ direct initializer is present. 2690 /// e.g: "int x(1);" 2691 void AddCXXDirectInitializerToDecl(Decl *Dcl, 2692 SourceLocation LParenLoc, 2693 MultiExprArg Exprs, 2694 SourceLocation RParenLoc, 2695 bool TypeMayContainAuto); 2696 2697 /// InitializeVarWithConstructor - Creates an CXXConstructExpr 2698 /// and sets it as the initializer for the the passed in VarDecl. 2699 bool InitializeVarWithConstructor(VarDecl *VD, 2700 CXXConstructorDecl *Constructor, 2701 MultiExprArg Exprs, 2702 bool HadMultipleCandidates); 2703 2704 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 2705 /// including handling of its default argument expressions. 2706 /// 2707 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind 2708 ExprResult 2709 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 2710 CXXConstructorDecl *Constructor, MultiExprArg Exprs, 2711 bool HadMultipleCandidates, bool RequiresZeroInit, 2712 unsigned ConstructKind, SourceRange ParenRange); 2713 2714 // FIXME: Can re remove this and have the above BuildCXXConstructExpr check if 2715 // the constructor can be elidable? 2716 ExprResult 2717 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 2718 CXXConstructorDecl *Constructor, bool Elidable, 2719 MultiExprArg Exprs, bool HadMultipleCandidates, 2720 bool RequiresZeroInit, unsigned ConstructKind, 2721 SourceRange ParenRange); 2722 2723 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating 2724 /// the default expr if needed. 2725 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, 2726 FunctionDecl *FD, 2727 ParmVarDecl *Param); 2728 2729 /// FinalizeVarWithDestructor - Prepare for calling destructor on the 2730 /// constructed variable. 2731 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); 2732 2733 /// \brief Helper class that collects exception specifications for 2734 /// implicitly-declared special member functions. 2735 class ImplicitExceptionSpecification { 2736 // Pointer to allow copying 2737 ASTContext *Context; 2738 // We order exception specifications thus: 2739 // noexcept is the most restrictive, but is only used in C++0x. 2740 // throw() comes next. 2741 // Then a throw(collected exceptions) 2742 // Finally no specification. 2743 // throw(...) is used instead if any called function uses it. 2744 // 2745 // If this exception specification cannot be known yet (for instance, 2746 // because this is the exception specification for a defaulted default 2747 // constructor and we haven't finished parsing the deferred parts of the 2748 // class yet), the C++0x standard does not specify how to behave. We 2749 // record this as an 'unknown' exception specification, which overrules 2750 // any other specification (even 'none', to keep this rule simple). 2751 ExceptionSpecificationType ComputedEST; 2752 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; 2753 SmallVector<QualType, 4> Exceptions; 2754 2755 void ClearExceptions() { 2756 ExceptionsSeen.clear(); 2757 Exceptions.clear(); 2758 } 2759 2760 public: 2761 explicit ImplicitExceptionSpecification(ASTContext &Context) 2762 : Context(&Context), ComputedEST(EST_BasicNoexcept) { 2763 if (!Context.getLangOptions().CPlusPlus0x) 2764 ComputedEST = EST_DynamicNone; 2765 } 2766 2767 /// \brief Get the computed exception specification type. 2768 ExceptionSpecificationType getExceptionSpecType() const { 2769 assert(ComputedEST != EST_ComputedNoexcept && 2770 "noexcept(expr) should not be a possible result"); 2771 return ComputedEST; 2772 } 2773 2774 /// \brief The number of exceptions in the exception specification. 2775 unsigned size() const { return Exceptions.size(); } 2776 2777 /// \brief The set of exceptions in the exception specification. 2778 const QualType *data() const { return Exceptions.data(); } 2779 2780 /// \brief Integrate another called method into the collected data. 2781 void CalledDecl(CXXMethodDecl *Method); 2782 2783 /// \brief Integrate an invoked expression into the collected data. 2784 void CalledExpr(Expr *E); 2785 2786 /// \brief Specify that the exception specification can't be detemined yet. 2787 void SetDelayed() { 2788 ClearExceptions(); 2789 ComputedEST = EST_Delayed; 2790 } 2791 2792 FunctionProtoType::ExtProtoInfo getEPI() const { 2793 FunctionProtoType::ExtProtoInfo EPI; 2794 EPI.ExceptionSpecType = getExceptionSpecType(); 2795 EPI.NumExceptions = size(); 2796 EPI.Exceptions = data(); 2797 return EPI; 2798 } 2799 }; 2800 2801 /// \brief Determine what sort of exception specification a defaulted 2802 /// copy constructor of a class will have. 2803 ImplicitExceptionSpecification 2804 ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl); 2805 2806 /// \brief Determine what sort of exception specification a defaulted 2807 /// default constructor of a class will have, and whether the parameter 2808 /// will be const. 2809 std::pair<ImplicitExceptionSpecification, bool> 2810 ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl); 2811 2812 /// \brief Determine what sort of exception specification a defautled 2813 /// copy assignment operator of a class will have, and whether the 2814 /// parameter will be const. 2815 std::pair<ImplicitExceptionSpecification, bool> 2816 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(CXXRecordDecl *ClassDecl); 2817 2818 /// \brief Determine what sort of exception specification a defaulted move 2819 /// constructor of a class will have. 2820 ImplicitExceptionSpecification 2821 ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl); 2822 2823 /// \brief Determine what sort of exception specification a defaulted move 2824 /// assignment operator of a class will have. 2825 ImplicitExceptionSpecification 2826 ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl); 2827 2828 /// \brief Determine what sort of exception specification a defaulted 2829 /// destructor of a class will have. 2830 ImplicitExceptionSpecification 2831 ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl); 2832 2833 /// \brief Determine if a special member function should have a deleted 2834 /// definition when it is defaulted. 2835 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM); 2836 2837 /// \brief Determine if a defaulted copy assignment operator ought to be 2838 /// deleted. 2839 bool ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD); 2840 2841 /// \brief Determine if a defaulted move constructor ought to be deleted. 2842 bool ShouldDeleteMoveConstructor(CXXConstructorDecl *CD); 2843 2844 /// \brief Determine if a defaulted move assignment operator ought to be 2845 /// deleted. 2846 bool ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD); 2847 2848 /// \brief Determine if a defaulted destructor ought to be deleted. 2849 bool ShouldDeleteDestructor(CXXDestructorDecl *DD); 2850 2851 /// \brief Declare the implicit default constructor for the given class. 2852 /// 2853 /// \param ClassDecl The class declaration into which the implicit 2854 /// default constructor will be added. 2855 /// 2856 /// \returns The implicitly-declared default constructor. 2857 CXXConstructorDecl *DeclareImplicitDefaultConstructor( 2858 CXXRecordDecl *ClassDecl); 2859 2860 /// DefineImplicitDefaultConstructor - Checks for feasibility of 2861 /// defining this constructor as the default constructor. 2862 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 2863 CXXConstructorDecl *Constructor); 2864 2865 /// \brief Declare the implicit destructor for the given class. 2866 /// 2867 /// \param ClassDecl The class declaration into which the implicit 2868 /// destructor will be added. 2869 /// 2870 /// \returns The implicitly-declared destructor. 2871 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); 2872 2873 /// DefineImplicitDestructor - Checks for feasibility of 2874 /// defining this destructor as the default destructor. 2875 void DefineImplicitDestructor(SourceLocation CurrentLocation, 2876 CXXDestructorDecl *Destructor); 2877 2878 /// \brief Build an exception spec for destructors that don't have one. 2879 /// 2880 /// C++11 says that user-defined destructors with no exception spec get one 2881 /// that looks as if the destructor was implicitly declared. 2882 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 2883 CXXDestructorDecl *Destructor); 2884 2885 /// \brief Declare all inherited constructors for the given class. 2886 /// 2887 /// \param ClassDecl The class declaration into which the inherited 2888 /// constructors will be added. 2889 void DeclareInheritedConstructors(CXXRecordDecl *ClassDecl); 2890 2891 /// \brief Declare the implicit copy constructor for the given class. 2892 /// 2893 /// \param ClassDecl The class declaration into which the implicit 2894 /// copy constructor will be added. 2895 /// 2896 /// \returns The implicitly-declared copy constructor. 2897 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); 2898 2899 /// DefineImplicitCopyConstructor - Checks for feasibility of 2900 /// defining this constructor as the copy constructor. 2901 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 2902 CXXConstructorDecl *Constructor); 2903 2904 /// \brief Declare the implicit move constructor for the given class. 2905 /// 2906 /// \param ClassDecl The Class declaration into which the implicit 2907 /// move constructor will be added. 2908 /// 2909 /// \returns The implicitly-declared move constructor, or NULL if it wasn't 2910 /// declared. 2911 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); 2912 2913 /// DefineImplicitMoveConstructor - Checks for feasibility of 2914 /// defining this constructor as the move constructor. 2915 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 2916 CXXConstructorDecl *Constructor); 2917 2918 /// \brief Declare the implicit copy assignment operator for the given class. 2919 /// 2920 /// \param ClassDecl The class declaration into which the implicit 2921 /// copy assignment operator will be added. 2922 /// 2923 /// \returns The implicitly-declared copy assignment operator. 2924 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); 2925 2926 /// \brief Defines an implicitly-declared copy assignment operator. 2927 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 2928 CXXMethodDecl *MethodDecl); 2929 2930 /// \brief Declare the implicit move assignment operator for the given class. 2931 /// 2932 /// \param ClassDecl The Class declaration into which the implicit 2933 /// move assignment operator will be added. 2934 /// 2935 /// \returns The implicitly-declared move assignment operator, or NULL if it 2936 /// wasn't declared. 2937 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); 2938 2939 /// \brief Defines an implicitly-declared move assignment operator. 2940 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 2941 CXXMethodDecl *MethodDecl); 2942 2943 /// \brief Force the declaration of any implicitly-declared members of this 2944 /// class. 2945 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); 2946 2947 /// MaybeBindToTemporary - If the passed in expression has a record type with 2948 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise 2949 /// it simply returns the passed in expression. 2950 ExprResult MaybeBindToTemporary(Expr *E); 2951 2952 bool CompleteConstructorCall(CXXConstructorDecl *Constructor, 2953 MultiExprArg ArgsPtr, 2954 SourceLocation Loc, 2955 ASTOwningVector<Expr*> &ConvertedArgs); 2956 2957 ParsedType getDestructorName(SourceLocation TildeLoc, 2958 IdentifierInfo &II, SourceLocation NameLoc, 2959 Scope *S, CXXScopeSpec &SS, 2960 ParsedType ObjectType, 2961 bool EnteringContext); 2962 2963 // Checks that reinterpret casts don't have undefined behavior. 2964 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, 2965 bool IsDereference, SourceRange Range); 2966 2967 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. 2968 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, 2969 tok::TokenKind Kind, 2970 SourceLocation LAngleBracketLoc, 2971 Declarator &D, 2972 SourceLocation RAngleBracketLoc, 2973 SourceLocation LParenLoc, 2974 Expr *E, 2975 SourceLocation RParenLoc); 2976 2977 ExprResult BuildCXXNamedCast(SourceLocation OpLoc, 2978 tok::TokenKind Kind, 2979 TypeSourceInfo *Ty, 2980 Expr *E, 2981 SourceRange AngleBrackets, 2982 SourceRange Parens); 2983 2984 ExprResult BuildCXXTypeId(QualType TypeInfoType, 2985 SourceLocation TypeidLoc, 2986 TypeSourceInfo *Operand, 2987 SourceLocation RParenLoc); 2988 ExprResult BuildCXXTypeId(QualType TypeInfoType, 2989 SourceLocation TypeidLoc, 2990 Expr *Operand, 2991 SourceLocation RParenLoc); 2992 2993 /// ActOnCXXTypeid - Parse typeid( something ). 2994 ExprResult ActOnCXXTypeid(SourceLocation OpLoc, 2995 SourceLocation LParenLoc, bool isType, 2996 void *TyOrExpr, 2997 SourceLocation RParenLoc); 2998 2999 ExprResult BuildCXXUuidof(QualType TypeInfoType, 3000 SourceLocation TypeidLoc, 3001 TypeSourceInfo *Operand, 3002 SourceLocation RParenLoc); 3003 ExprResult BuildCXXUuidof(QualType TypeInfoType, 3004 SourceLocation TypeidLoc, 3005 Expr *Operand, 3006 SourceLocation RParenLoc); 3007 3008 /// ActOnCXXUuidof - Parse __uuidof( something ). 3009 ExprResult ActOnCXXUuidof(SourceLocation OpLoc, 3010 SourceLocation LParenLoc, bool isType, 3011 void *TyOrExpr, 3012 SourceLocation RParenLoc); 3013 3014 3015 //// ActOnCXXThis - Parse 'this' pointer. 3016 ExprResult ActOnCXXThis(SourceLocation loc); 3017 3018 /// getAndCaptureCurrentThisType - Try to capture a 'this' pointer. Returns 3019 /// the type of the 'this' pointer, or a null type if this is not possible. 3020 QualType getAndCaptureCurrentThisType(); 3021 3022 /// ActOnCXXBoolLiteral - Parse {true,false} literals. 3023 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 3024 3025 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 3026 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); 3027 3028 //// ActOnCXXThrow - Parse throw expressions. 3029 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); 3030 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, 3031 bool IsThrownVarInScope); 3032 ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E, 3033 bool IsThrownVarInScope); 3034 3035 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 3036 /// Can be interpreted either as function-style casting ("int(x)") 3037 /// or class type construction ("ClassType(x,y,z)") 3038 /// or creation of a value-initialized type ("int()"). 3039 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, 3040 SourceLocation LParenLoc, 3041 MultiExprArg Exprs, 3042 SourceLocation RParenLoc); 3043 3044 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, 3045 SourceLocation LParenLoc, 3046 MultiExprArg Exprs, 3047 SourceLocation RParenLoc); 3048 3049 /// ActOnCXXNew - Parsed a C++ 'new' expression. 3050 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 3051 SourceLocation PlacementLParen, 3052 MultiExprArg PlacementArgs, 3053 SourceLocation PlacementRParen, 3054 SourceRange TypeIdParens, Declarator &D, 3055 SourceLocation ConstructorLParen, 3056 MultiExprArg ConstructorArgs, 3057 SourceLocation ConstructorRParen); 3058 ExprResult BuildCXXNew(SourceLocation StartLoc, bool UseGlobal, 3059 SourceLocation PlacementLParen, 3060 MultiExprArg PlacementArgs, 3061 SourceLocation PlacementRParen, 3062 SourceRange TypeIdParens, 3063 QualType AllocType, 3064 TypeSourceInfo *AllocTypeInfo, 3065 Expr *ArraySize, 3066 SourceLocation ConstructorLParen, 3067 MultiExprArg ConstructorArgs, 3068 SourceLocation ConstructorRParen, 3069 bool TypeMayContainAuto = true); 3070 3071 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, 3072 SourceRange R); 3073 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 3074 bool UseGlobal, QualType AllocType, bool IsArray, 3075 Expr **PlaceArgs, unsigned NumPlaceArgs, 3076 FunctionDecl *&OperatorNew, 3077 FunctionDecl *&OperatorDelete); 3078 bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, 3079 DeclarationName Name, Expr** Args, 3080 unsigned NumArgs, DeclContext *Ctx, 3081 bool AllowMissing, FunctionDecl *&Operator, 3082 bool Diagnose = true); 3083 void DeclareGlobalNewDelete(); 3084 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, 3085 QualType Argument, 3086 bool addMallocAttr = false); 3087 3088 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 3089 DeclarationName Name, FunctionDecl* &Operator, 3090 bool Diagnose = true); 3091 3092 /// ActOnCXXDelete - Parsed a C++ 'delete' expression 3093 ExprResult ActOnCXXDelete(SourceLocation StartLoc, 3094 bool UseGlobal, bool ArrayForm, 3095 Expr *Operand); 3096 3097 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); 3098 ExprResult CheckConditionVariable(VarDecl *ConditionVar, 3099 SourceLocation StmtLoc, 3100 bool ConvertToBoolean); 3101 3102 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, 3103 Expr *Operand, SourceLocation RParen); 3104 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 3105 SourceLocation RParen); 3106 3107 /// ActOnUnaryTypeTrait - Parsed one of the unary type trait support 3108 /// pseudo-functions. 3109 ExprResult ActOnUnaryTypeTrait(UnaryTypeTrait OTT, 3110 SourceLocation KWLoc, 3111 ParsedType Ty, 3112 SourceLocation RParen); 3113 3114 ExprResult BuildUnaryTypeTrait(UnaryTypeTrait OTT, 3115 SourceLocation KWLoc, 3116 TypeSourceInfo *T, 3117 SourceLocation RParen); 3118 3119 /// ActOnBinaryTypeTrait - Parsed one of the bianry type trait support 3120 /// pseudo-functions. 3121 ExprResult ActOnBinaryTypeTrait(BinaryTypeTrait OTT, 3122 SourceLocation KWLoc, 3123 ParsedType LhsTy, 3124 ParsedType RhsTy, 3125 SourceLocation RParen); 3126 3127 ExprResult BuildBinaryTypeTrait(BinaryTypeTrait BTT, 3128 SourceLocation KWLoc, 3129 TypeSourceInfo *LhsT, 3130 TypeSourceInfo *RhsT, 3131 SourceLocation RParen); 3132 3133 /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support 3134 /// pseudo-functions. 3135 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, 3136 SourceLocation KWLoc, 3137 ParsedType LhsTy, 3138 Expr *DimExpr, 3139 SourceLocation RParen); 3140 3141 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, 3142 SourceLocation KWLoc, 3143 TypeSourceInfo *TSInfo, 3144 Expr *DimExpr, 3145 SourceLocation RParen); 3146 3147 /// ActOnExpressionTrait - Parsed one of the unary type trait support 3148 /// pseudo-functions. 3149 ExprResult ActOnExpressionTrait(ExpressionTrait OET, 3150 SourceLocation KWLoc, 3151 Expr *Queried, 3152 SourceLocation RParen); 3153 3154 ExprResult BuildExpressionTrait(ExpressionTrait OET, 3155 SourceLocation KWLoc, 3156 Expr *Queried, 3157 SourceLocation RParen); 3158 3159 ExprResult ActOnStartCXXMemberReference(Scope *S, 3160 Expr *Base, 3161 SourceLocation OpLoc, 3162 tok::TokenKind OpKind, 3163 ParsedType &ObjectType, 3164 bool &MayBePseudoDestructor); 3165 3166 ExprResult DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr); 3167 3168 ExprResult BuildPseudoDestructorExpr(Expr *Base, 3169 SourceLocation OpLoc, 3170 tok::TokenKind OpKind, 3171 const CXXScopeSpec &SS, 3172 TypeSourceInfo *ScopeType, 3173 SourceLocation CCLoc, 3174 SourceLocation TildeLoc, 3175 PseudoDestructorTypeStorage DestroyedType, 3176 bool HasTrailingLParen); 3177 3178 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 3179 SourceLocation OpLoc, 3180 tok::TokenKind OpKind, 3181 CXXScopeSpec &SS, 3182 UnqualifiedId &FirstTypeName, 3183 SourceLocation CCLoc, 3184 SourceLocation TildeLoc, 3185 UnqualifiedId &SecondTypeName, 3186 bool HasTrailingLParen); 3187 3188 /// MaybeCreateExprWithCleanups - If the current full-expression 3189 /// requires any cleanups, surround it with a ExprWithCleanups node. 3190 /// Otherwise, just returns the passed-in expression. 3191 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); 3192 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); 3193 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); 3194 3195 ExprResult ActOnFinishFullExpr(Expr *Expr); 3196 StmtResult ActOnFinishFullStmt(Stmt *Stmt); 3197 3198 // Marks SS invalid if it represents an incomplete type. 3199 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); 3200 3201 DeclContext *computeDeclContext(QualType T); 3202 DeclContext *computeDeclContext(const CXXScopeSpec &SS, 3203 bool EnteringContext = false); 3204 bool isDependentScopeSpecifier(const CXXScopeSpec &SS); 3205 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); 3206 bool isUnknownSpecialization(const CXXScopeSpec &SS); 3207 3208 /// \brief The parser has parsed a global nested-name-specifier '::'. 3209 /// 3210 /// \param S The scope in which this nested-name-specifier occurs. 3211 /// 3212 /// \param CCLoc The location of the '::'. 3213 /// 3214 /// \param SS The nested-name-specifier, which will be updated in-place 3215 /// to reflect the parsed nested-name-specifier. 3216 /// 3217 /// \returns true if an error occurred, false otherwise. 3218 bool ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc, 3219 CXXScopeSpec &SS); 3220 3221 bool isAcceptableNestedNameSpecifier(NamedDecl *SD); 3222 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); 3223 3224 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, 3225 SourceLocation IdLoc, 3226 IdentifierInfo &II, 3227 ParsedType ObjectType); 3228 3229 bool BuildCXXNestedNameSpecifier(Scope *S, 3230 IdentifierInfo &Identifier, 3231 SourceLocation IdentifierLoc, 3232 SourceLocation CCLoc, 3233 QualType ObjectType, 3234 bool EnteringContext, 3235 CXXScopeSpec &SS, 3236 NamedDecl *ScopeLookupResult, 3237 bool ErrorRecoveryLookup); 3238 3239 /// \brief The parser has parsed a nested-name-specifier 'identifier::'. 3240 /// 3241 /// \param S The scope in which this nested-name-specifier occurs. 3242 /// 3243 /// \param Identifier The identifier preceding the '::'. 3244 /// 3245 /// \param IdentifierLoc The location of the identifier. 3246 /// 3247 /// \param CCLoc The location of the '::'. 3248 /// 3249 /// \param ObjectType The type of the object, if we're parsing 3250 /// nested-name-specifier in a member access expression. 3251 /// 3252 /// \param EnteringContext Whether we're entering the context nominated by 3253 /// this nested-name-specifier. 3254 /// 3255 /// \param SS The nested-name-specifier, which is both an input 3256 /// parameter (the nested-name-specifier before this type) and an 3257 /// output parameter (containing the full nested-name-specifier, 3258 /// including this new type). 3259 /// 3260 /// \returns true if an error occurred, false otherwise. 3261 bool ActOnCXXNestedNameSpecifier(Scope *S, 3262 IdentifierInfo &Identifier, 3263 SourceLocation IdentifierLoc, 3264 SourceLocation CCLoc, 3265 ParsedType ObjectType, 3266 bool EnteringContext, 3267 CXXScopeSpec &SS); 3268 3269 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, 3270 IdentifierInfo &Identifier, 3271 SourceLocation IdentifierLoc, 3272 SourceLocation ColonLoc, 3273 ParsedType ObjectType, 3274 bool EnteringContext); 3275 3276 /// \brief The parser has parsed a nested-name-specifier 3277 /// 'template[opt] template-name < template-args >::'. 3278 /// 3279 /// \param S The scope in which this nested-name-specifier occurs. 3280 /// 3281 /// \param TemplateLoc The location of the 'template' keyword, if any. 3282 /// 3283 /// \param SS The nested-name-specifier, which is both an input 3284 /// parameter (the nested-name-specifier before this type) and an 3285 /// output parameter (containing the full nested-name-specifier, 3286 /// including this new type). 3287 /// 3288 /// \param TemplateLoc the location of the 'template' keyword, if any. 3289 /// \param TemplateName The template name. 3290 /// \param TemplateNameLoc The location of the template name. 3291 /// \param LAngleLoc The location of the opening angle bracket ('<'). 3292 /// \param TemplateArgs The template arguments. 3293 /// \param RAngleLoc The location of the closing angle bracket ('>'). 3294 /// \param CCLoc The location of the '::'. 3295 3296 /// \param EnteringContext Whether we're entering the context of the 3297 /// nested-name-specifier. 3298 /// 3299 /// 3300 /// \returns true if an error occurred, false otherwise. 3301 bool ActOnCXXNestedNameSpecifier(Scope *S, 3302 SourceLocation TemplateLoc, 3303 CXXScopeSpec &SS, 3304 TemplateTy Template, 3305 SourceLocation TemplateNameLoc, 3306 SourceLocation LAngleLoc, 3307 ASTTemplateArgsPtr TemplateArgs, 3308 SourceLocation RAngleLoc, 3309 SourceLocation CCLoc, 3310 bool EnteringContext); 3311 3312 /// \brief Given a C++ nested-name-specifier, produce an annotation value 3313 /// that the parser can use later to reconstruct the given 3314 /// nested-name-specifier. 3315 /// 3316 /// \param SS A nested-name-specifier. 3317 /// 3318 /// \returns A pointer containing all of the information in the 3319 /// nested-name-specifier \p SS. 3320 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); 3321 3322 /// \brief Given an annotation pointer for a nested-name-specifier, restore 3323 /// the nested-name-specifier structure. 3324 /// 3325 /// \param Annotation The annotation pointer, produced by 3326 /// \c SaveNestedNameSpecifierAnnotation(). 3327 /// 3328 /// \param AnnotationRange The source range corresponding to the annotation. 3329 /// 3330 /// \param SS The nested-name-specifier that will be updated with the contents 3331 /// of the annotation pointer. 3332 void RestoreNestedNameSpecifierAnnotation(void *Annotation, 3333 SourceRange AnnotationRange, 3334 CXXScopeSpec &SS); 3335 3336 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 3337 3338 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global 3339 /// scope or nested-name-specifier) is parsed, part of a declarator-id. 3340 /// After this method is called, according to [C++ 3.4.3p3], names should be 3341 /// looked up in the declarator-id's scope, until the declarator is parsed and 3342 /// ActOnCXXExitDeclaratorScope is called. 3343 /// The 'SS' should be a non-empty valid CXXScopeSpec. 3344 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); 3345 3346 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously 3347 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same 3348 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. 3349 /// Used to indicate that names should revert to being looked up in the 3350 /// defining scope. 3351 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 3352 3353 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an 3354 /// initializer for the declaration 'Dcl'. 3355 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 3356 /// static data member of class X, names should be looked up in the scope of 3357 /// class X. 3358 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); 3359 3360 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 3361 /// initializer for the declaration 'Dcl'. 3362 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); 3363 3364 // ParseObjCStringLiteral - Parse Objective-C string literals. 3365 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, 3366 Expr **Strings, 3367 unsigned NumStrings); 3368 3369 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, 3370 TypeSourceInfo *EncodedTypeInfo, 3371 SourceLocation RParenLoc); 3372 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, 3373 CXXMethodDecl *Method, 3374 bool HadMultipleCandidates); 3375 3376 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, 3377 SourceLocation EncodeLoc, 3378 SourceLocation LParenLoc, 3379 ParsedType Ty, 3380 SourceLocation RParenLoc); 3381 3382 // ParseObjCSelectorExpression - Build selector expression for @selector 3383 ExprResult ParseObjCSelectorExpression(Selector Sel, 3384 SourceLocation AtLoc, 3385 SourceLocation SelLoc, 3386 SourceLocation LParenLoc, 3387 SourceLocation RParenLoc); 3388 3389 // ParseObjCProtocolExpression - Build protocol expression for @protocol 3390 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, 3391 SourceLocation AtLoc, 3392 SourceLocation ProtoLoc, 3393 SourceLocation LParenLoc, 3394 SourceLocation RParenLoc); 3395 3396 //===--------------------------------------------------------------------===// 3397 // C++ Declarations 3398 // 3399 Decl *ActOnStartLinkageSpecification(Scope *S, 3400 SourceLocation ExternLoc, 3401 SourceLocation LangLoc, 3402 StringRef Lang, 3403 SourceLocation LBraceLoc); 3404 Decl *ActOnFinishLinkageSpecification(Scope *S, 3405 Decl *LinkageSpec, 3406 SourceLocation RBraceLoc); 3407 3408 3409 //===--------------------------------------------------------------------===// 3410 // C++ Classes 3411 // 3412 bool isCurrentClassName(const IdentifierInfo &II, Scope *S, 3413 const CXXScopeSpec *SS = 0); 3414 3415 Decl *ActOnAccessSpecifier(AccessSpecifier Access, 3416 SourceLocation ASLoc, 3417 SourceLocation ColonLoc); 3418 3419 Decl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, 3420 Declarator &D, 3421 MultiTemplateParamsArg TemplateParameterLists, 3422 Expr *BitfieldWidth, const VirtSpecifiers &VS, 3423 bool HasDeferredInit); 3424 void ActOnCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, 3425 Expr *Init); 3426 3427 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 3428 Scope *S, 3429 CXXScopeSpec &SS, 3430 IdentifierInfo *MemberOrBase, 3431 ParsedType TemplateTypeTy, 3432 SourceLocation IdLoc, 3433 SourceLocation LParenLoc, 3434 Expr **Args, unsigned NumArgs, 3435 SourceLocation RParenLoc, 3436 SourceLocation EllipsisLoc); 3437 3438 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 3439 Scope *S, 3440 CXXScopeSpec &SS, 3441 IdentifierInfo *MemberOrBase, 3442 ParsedType TemplateTypeTy, 3443 SourceLocation IdLoc, 3444 Expr *InitList, 3445 SourceLocation EllipsisLoc); 3446 3447 MemInitResult BuildMemInitializer(Decl *ConstructorD, 3448 Scope *S, 3449 CXXScopeSpec &SS, 3450 IdentifierInfo *MemberOrBase, 3451 ParsedType TemplateTypeTy, 3452 SourceLocation IdLoc, 3453 const MultiInitializer &Init, 3454 SourceLocation EllipsisLoc); 3455 3456 MemInitResult BuildMemberInitializer(ValueDecl *Member, 3457 const MultiInitializer &Args, 3458 SourceLocation IdLoc); 3459 3460 MemInitResult BuildBaseInitializer(QualType BaseType, 3461 TypeSourceInfo *BaseTInfo, 3462 const MultiInitializer &Args, 3463 CXXRecordDecl *ClassDecl, 3464 SourceLocation EllipsisLoc); 3465 3466 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, 3467 const MultiInitializer &Args, 3468 SourceLocation BaseLoc, 3469 CXXRecordDecl *ClassDecl); 3470 3471 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3472 CXXCtorInitializer *Initializer); 3473 3474 bool SetCtorInitializers(CXXConstructorDecl *Constructor, 3475 CXXCtorInitializer **Initializers, 3476 unsigned NumInitializers, bool AnyErrors); 3477 3478 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); 3479 3480 3481 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, 3482 /// mark all the non-trivial destructors of its members and bases as 3483 /// referenced. 3484 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, 3485 CXXRecordDecl *Record); 3486 3487 /// \brief The list of classes whose vtables have been used within 3488 /// this translation unit, and the source locations at which the 3489 /// first use occurred. 3490 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; 3491 3492 /// \brief The list of vtables that are required but have not yet been 3493 /// materialized. 3494 SmallVector<VTableUse, 16> VTableUses; 3495 3496 /// \brief The set of classes whose vtables have been used within 3497 /// this translation unit, and a bit that will be true if the vtable is 3498 /// required to be emitted (otherwise, it should be emitted only if needed 3499 /// by code generation). 3500 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; 3501 3502 /// \brief Load any externally-stored vtable uses. 3503 void LoadExternalVTableUses(); 3504 3505 typedef LazyVector<CXXRecordDecl *, ExternalSemaSource, 3506 &ExternalSemaSource::ReadDynamicClasses, 2, 2> 3507 DynamicClassesType; 3508 3509 /// \brief A list of all of the dynamic classes in this translation 3510 /// unit. 3511 DynamicClassesType DynamicClasses; 3512 3513 /// \brief Note that the vtable for the given class was used at the 3514 /// given location. 3515 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 3516 bool DefinitionRequired = false); 3517 3518 /// MarkVirtualMembersReferenced - Will mark all members of the given 3519 /// CXXRecordDecl referenced. 3520 void MarkVirtualMembersReferenced(SourceLocation Loc, 3521 const CXXRecordDecl *RD); 3522 3523 /// \brief Define all of the vtables that have been used in this 3524 /// translation unit and reference any virtual members used by those 3525 /// vtables. 3526 /// 3527 /// \returns true if any work was done, false otherwise. 3528 bool DefineUsedVTables(); 3529 3530 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); 3531 3532 void ActOnMemInitializers(Decl *ConstructorDecl, 3533 SourceLocation ColonLoc, 3534 CXXCtorInitializer **MemInits, 3535 unsigned NumMemInits, 3536 bool AnyErrors); 3537 3538 void CheckCompletedCXXClass(CXXRecordDecl *Record); 3539 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 3540 Decl *TagDecl, 3541 SourceLocation LBrac, 3542 SourceLocation RBrac, 3543 AttributeList *AttrList); 3544 3545 void ActOnReenterTemplateScope(Scope *S, Decl *Template); 3546 void ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D); 3547 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); 3548 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 3549 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); 3550 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); 3551 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 3552 void ActOnFinishDelayedMemberInitializers(Decl *Record); 3553 void MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag = true); 3554 bool IsInsideALocalClassWithinATemplateFunction(); 3555 3556 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 3557 Expr *AssertExpr, 3558 Expr *AssertMessageExpr, 3559 SourceLocation RParenLoc); 3560 3561 FriendDecl *CheckFriendTypeDecl(SourceLocation FriendLoc, 3562 TypeSourceInfo *TSInfo); 3563 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 3564 MultiTemplateParamsArg TemplateParams); 3565 Decl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, 3566 MultiTemplateParamsArg TemplateParams); 3567 3568 QualType CheckConstructorDeclarator(Declarator &D, QualType R, 3569 StorageClass& SC); 3570 void CheckConstructor(CXXConstructorDecl *Constructor); 3571 QualType CheckDestructorDeclarator(Declarator &D, QualType R, 3572 StorageClass& SC); 3573 bool CheckDestructor(CXXDestructorDecl *Destructor); 3574 void CheckConversionDeclarator(Declarator &D, QualType &R, 3575 StorageClass& SC); 3576 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); 3577 3578 void CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record); 3579 void CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *Ctor); 3580 void CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *Ctor); 3581 void CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *Method); 3582 void CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *Ctor); 3583 void CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *Method); 3584 void CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *Dtor); 3585 3586 //===--------------------------------------------------------------------===// 3587 // C++ Derived Classes 3588 // 3589 3590 /// ActOnBaseSpecifier - Parsed a base specifier 3591 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, 3592 SourceRange SpecifierRange, 3593 bool Virtual, AccessSpecifier Access, 3594 TypeSourceInfo *TInfo, 3595 SourceLocation EllipsisLoc); 3596 3597 BaseResult ActOnBaseSpecifier(Decl *classdecl, 3598 SourceRange SpecifierRange, 3599 bool Virtual, AccessSpecifier Access, 3600 ParsedType basetype, 3601 SourceLocation BaseLoc, 3602 SourceLocation EllipsisLoc); 3603 3604 bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 3605 unsigned NumBases); 3606 void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 3607 unsigned NumBases); 3608 3609 bool IsDerivedFrom(QualType Derived, QualType Base); 3610 bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths); 3611 3612 // FIXME: I don't like this name. 3613 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); 3614 3615 bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath); 3616 3617 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 3618 SourceLocation Loc, SourceRange Range, 3619 CXXCastPath *BasePath = 0, 3620 bool IgnoreAccess = false); 3621 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 3622 unsigned InaccessibleBaseID, 3623 unsigned AmbigiousBaseConvID, 3624 SourceLocation Loc, SourceRange Range, 3625 DeclarationName Name, 3626 CXXCastPath *BasePath); 3627 3628 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); 3629 3630 /// CheckOverridingFunctionReturnType - Checks whether the return types are 3631 /// covariant, according to C++ [class.virtual]p5. 3632 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 3633 const CXXMethodDecl *Old); 3634 3635 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception 3636 /// spec is a subset of base spec. 3637 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, 3638 const CXXMethodDecl *Old); 3639 3640 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); 3641 3642 /// CheckOverrideControl - Check C++0x override control semantics. 3643 void CheckOverrideControl(const Decl *D); 3644 3645 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function 3646 /// overrides a virtual member function marked 'final', according to 3647 /// C++0x [class.virtual]p3. 3648 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3649 const CXXMethodDecl *Old); 3650 3651 3652 //===--------------------------------------------------------------------===// 3653 // C++ Access Control 3654 // 3655 3656 enum AccessResult { 3657 AR_accessible, 3658 AR_inaccessible, 3659 AR_dependent, 3660 AR_delayed 3661 }; 3662 3663 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, 3664 NamedDecl *PrevMemberDecl, 3665 AccessSpecifier LexicalAS); 3666 3667 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, 3668 DeclAccessPair FoundDecl); 3669 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, 3670 DeclAccessPair FoundDecl); 3671 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, 3672 SourceRange PlacementRange, 3673 CXXRecordDecl *NamingClass, 3674 DeclAccessPair FoundDecl, 3675 bool Diagnose = true); 3676 AccessResult CheckConstructorAccess(SourceLocation Loc, 3677 CXXConstructorDecl *D, 3678 const InitializedEntity &Entity, 3679 AccessSpecifier Access, 3680 bool IsCopyBindingRefToTemp = false); 3681 AccessResult CheckConstructorAccess(SourceLocation Loc, 3682 CXXConstructorDecl *D, 3683 AccessSpecifier Access, 3684 PartialDiagnostic PD); 3685 AccessResult CheckDestructorAccess(SourceLocation Loc, 3686 CXXDestructorDecl *Dtor, 3687 const PartialDiagnostic &PDiag); 3688 AccessResult CheckDirectMemberAccess(SourceLocation Loc, 3689 NamedDecl *D, 3690 const PartialDiagnostic &PDiag); 3691 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, 3692 Expr *ObjectExpr, 3693 Expr *ArgExpr, 3694 DeclAccessPair FoundDecl); 3695 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, 3696 DeclAccessPair FoundDecl); 3697 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, 3698 QualType Base, QualType Derived, 3699 const CXXBasePath &Path, 3700 unsigned DiagID, 3701 bool ForceCheck = false, 3702 bool ForceUnprivileged = false); 3703 void CheckLookupAccess(const LookupResult &R); 3704 bool IsSimplyAccessible(NamedDecl *decl, CXXRecordDecl *Class); 3705 3706 void HandleDependentAccessCheck(const DependentDiagnostic &DD, 3707 const MultiLevelTemplateArgumentList &TemplateArgs); 3708 void PerformDependentDiagnostics(const DeclContext *Pattern, 3709 const MultiLevelTemplateArgumentList &TemplateArgs); 3710 3711 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 3712 3713 /// A flag to suppress access checking. 3714 bool SuppressAccessChecking; 3715 3716 /// \brief When true, access checking violations are treated as SFINAE 3717 /// failures rather than hard errors. 3718 bool AccessCheckingSFINAE; 3719 3720 void ActOnStartSuppressingAccessChecks(); 3721 void ActOnStopSuppressingAccessChecks(); 3722 3723 enum AbstractDiagSelID { 3724 AbstractNone = -1, 3725 AbstractReturnType, 3726 AbstractParamType, 3727 AbstractVariableType, 3728 AbstractFieldType, 3729 AbstractArrayType 3730 }; 3731 3732 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 3733 const PartialDiagnostic &PD); 3734 void DiagnoseAbstractType(const CXXRecordDecl *RD); 3735 3736 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, 3737 AbstractDiagSelID SelID = AbstractNone); 3738 3739 //===--------------------------------------------------------------------===// 3740 // C++ Overloaded Operators [C++ 13.5] 3741 // 3742 3743 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); 3744 3745 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); 3746 3747 //===--------------------------------------------------------------------===// 3748 // C++ Templates [C++ 14] 3749 // 3750 void FilterAcceptableTemplateNames(LookupResult &R); 3751 bool hasAnyAcceptableTemplateNames(LookupResult &R); 3752 3753 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, 3754 QualType ObjectType, bool EnteringContext, 3755 bool &MemberOfUnknownSpecialization); 3756 3757 TemplateNameKind isTemplateName(Scope *S, 3758 CXXScopeSpec &SS, 3759 bool hasTemplateKeyword, 3760 UnqualifiedId &Name, 3761 ParsedType ObjectType, 3762 bool EnteringContext, 3763 TemplateTy &Template, 3764 bool &MemberOfUnknownSpecialization); 3765 3766 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, 3767 SourceLocation IILoc, 3768 Scope *S, 3769 const CXXScopeSpec *SS, 3770 TemplateTy &SuggestedTemplate, 3771 TemplateNameKind &SuggestedKind); 3772 3773 bool DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); 3774 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); 3775 3776 Decl *ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis, 3777 SourceLocation EllipsisLoc, 3778 SourceLocation KeyLoc, 3779 IdentifierInfo *ParamName, 3780 SourceLocation ParamNameLoc, 3781 unsigned Depth, unsigned Position, 3782 SourceLocation EqualLoc, 3783 ParsedType DefaultArg); 3784 3785 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); 3786 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 3787 unsigned Depth, 3788 unsigned Position, 3789 SourceLocation EqualLoc, 3790 Expr *DefaultArg); 3791 Decl *ActOnTemplateTemplateParameter(Scope *S, 3792 SourceLocation TmpLoc, 3793 TemplateParameterList *Params, 3794 SourceLocation EllipsisLoc, 3795 IdentifierInfo *ParamName, 3796 SourceLocation ParamNameLoc, 3797 unsigned Depth, 3798 unsigned Position, 3799 SourceLocation EqualLoc, 3800 ParsedTemplateArgument DefaultArg); 3801 3802 TemplateParameterList * 3803 ActOnTemplateParameterList(unsigned Depth, 3804 SourceLocation ExportLoc, 3805 SourceLocation TemplateLoc, 3806 SourceLocation LAngleLoc, 3807 Decl **Params, unsigned NumParams, 3808 SourceLocation RAngleLoc); 3809 3810 /// \brief The context in which we are checking a template parameter 3811 /// list. 3812 enum TemplateParamListContext { 3813 TPC_ClassTemplate, 3814 TPC_FunctionTemplate, 3815 TPC_ClassTemplateMember, 3816 TPC_FriendFunctionTemplate, 3817 TPC_FriendFunctionTemplateDefinition, 3818 TPC_TypeAliasTemplate 3819 }; 3820 3821 bool CheckTemplateParameterList(TemplateParameterList *NewParams, 3822 TemplateParameterList *OldParams, 3823 TemplateParamListContext TPC); 3824 TemplateParameterList * 3825 MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, 3826 SourceLocation DeclLoc, 3827 const CXXScopeSpec &SS, 3828 TemplateParameterList **ParamLists, 3829 unsigned NumParamLists, 3830 bool IsFriend, 3831 bool &IsExplicitSpecialization, 3832 bool &Invalid); 3833 3834 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, 3835 SourceLocation KWLoc, CXXScopeSpec &SS, 3836 IdentifierInfo *Name, SourceLocation NameLoc, 3837 AttributeList *Attr, 3838 TemplateParameterList *TemplateParams, 3839 AccessSpecifier AS, 3840 SourceLocation ModulePrivateLoc, 3841 unsigned NumOuterTemplateParamLists, 3842 TemplateParameterList **OuterTemplateParamLists); 3843 3844 void translateTemplateArguments(const ASTTemplateArgsPtr &In, 3845 TemplateArgumentListInfo &Out); 3846 3847 void NoteAllFoundTemplates(TemplateName Name); 3848 3849 QualType CheckTemplateIdType(TemplateName Template, 3850 SourceLocation TemplateLoc, 3851 TemplateArgumentListInfo &TemplateArgs); 3852 3853 TypeResult 3854 ActOnTemplateIdType(CXXScopeSpec &SS, 3855 TemplateTy Template, SourceLocation TemplateLoc, 3856 SourceLocation LAngleLoc, 3857 ASTTemplateArgsPtr TemplateArgs, 3858 SourceLocation RAngleLoc); 3859 3860 /// \brief Parsed an elaborated-type-specifier that refers to a template-id, 3861 /// such as \c class T::template apply<U>. 3862 /// 3863 /// \param TUK 3864 TypeResult ActOnTagTemplateIdType(TagUseKind TUK, 3865 TypeSpecifierType TagSpec, 3866 SourceLocation TagLoc, 3867 CXXScopeSpec &SS, 3868 TemplateTy TemplateD, 3869 SourceLocation TemplateLoc, 3870 SourceLocation LAngleLoc, 3871 ASTTemplateArgsPtr TemplateArgsIn, 3872 SourceLocation RAngleLoc); 3873 3874 3875 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, 3876 LookupResult &R, 3877 bool RequiresADL, 3878 const TemplateArgumentListInfo &TemplateArgs); 3879 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, 3880 const DeclarationNameInfo &NameInfo, 3881 const TemplateArgumentListInfo &TemplateArgs); 3882 3883 TemplateNameKind ActOnDependentTemplateName(Scope *S, 3884 SourceLocation TemplateKWLoc, 3885 CXXScopeSpec &SS, 3886 UnqualifiedId &Name, 3887 ParsedType ObjectType, 3888 bool EnteringContext, 3889 TemplateTy &Template); 3890 3891 DeclResult 3892 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, 3893 SourceLocation KWLoc, 3894 SourceLocation ModulePrivateLoc, 3895 CXXScopeSpec &SS, 3896 TemplateTy Template, 3897 SourceLocation TemplateNameLoc, 3898 SourceLocation LAngleLoc, 3899 ASTTemplateArgsPtr TemplateArgs, 3900 SourceLocation RAngleLoc, 3901 AttributeList *Attr, 3902 MultiTemplateParamsArg TemplateParameterLists); 3903 3904 Decl *ActOnTemplateDeclarator(Scope *S, 3905 MultiTemplateParamsArg TemplateParameterLists, 3906 Declarator &D); 3907 3908 Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope, 3909 MultiTemplateParamsArg TemplateParameterLists, 3910 Declarator &D); 3911 3912 bool 3913 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, 3914 TemplateSpecializationKind NewTSK, 3915 NamedDecl *PrevDecl, 3916 TemplateSpecializationKind PrevTSK, 3917 SourceLocation PrevPtOfInstantiation, 3918 bool &SuppressNew); 3919 3920 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, 3921 const TemplateArgumentListInfo &ExplicitTemplateArgs, 3922 LookupResult &Previous); 3923 3924 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, 3925 TemplateArgumentListInfo *ExplicitTemplateArgs, 3926 LookupResult &Previous); 3927 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); 3928 3929 DeclResult 3930 ActOnExplicitInstantiation(Scope *S, 3931 SourceLocation ExternLoc, 3932 SourceLocation TemplateLoc, 3933 unsigned TagSpec, 3934 SourceLocation KWLoc, 3935 const CXXScopeSpec &SS, 3936 TemplateTy Template, 3937 SourceLocation TemplateNameLoc, 3938 SourceLocation LAngleLoc, 3939 ASTTemplateArgsPtr TemplateArgs, 3940 SourceLocation RAngleLoc, 3941 AttributeList *Attr); 3942 3943 DeclResult 3944 ActOnExplicitInstantiation(Scope *S, 3945 SourceLocation ExternLoc, 3946 SourceLocation TemplateLoc, 3947 unsigned TagSpec, 3948 SourceLocation KWLoc, 3949 CXXScopeSpec &SS, 3950 IdentifierInfo *Name, 3951 SourceLocation NameLoc, 3952 AttributeList *Attr); 3953 3954 DeclResult ActOnExplicitInstantiation(Scope *S, 3955 SourceLocation ExternLoc, 3956 SourceLocation TemplateLoc, 3957 Declarator &D); 3958 3959 TemplateArgumentLoc 3960 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, 3961 SourceLocation TemplateLoc, 3962 SourceLocation RAngleLoc, 3963 Decl *Param, 3964 SmallVectorImpl<TemplateArgument> &Converted); 3965 3966 /// \brief Specifies the context in which a particular template 3967 /// argument is being checked. 3968 enum CheckTemplateArgumentKind { 3969 /// \brief The template argument was specified in the code or was 3970 /// instantiated with some deduced template arguments. 3971 CTAK_Specified, 3972 3973 /// \brief The template argument was deduced via template argument 3974 /// deduction. 3975 CTAK_Deduced, 3976 3977 /// \brief The template argument was deduced from an array bound 3978 /// via template argument deduction. 3979 CTAK_DeducedFromArrayBound 3980 }; 3981 3982 bool CheckTemplateArgument(NamedDecl *Param, 3983 const TemplateArgumentLoc &Arg, 3984 NamedDecl *Template, 3985 SourceLocation TemplateLoc, 3986 SourceLocation RAngleLoc, 3987 unsigned ArgumentPackIndex, 3988 SmallVectorImpl<TemplateArgument> &Converted, 3989 CheckTemplateArgumentKind CTAK = CTAK_Specified); 3990 3991 /// \brief Check that the given template arguments can be be provided to 3992 /// the given template, converting the arguments along the way. 3993 /// 3994 /// \param Template The template to which the template arguments are being 3995 /// provided. 3996 /// 3997 /// \param TemplateLoc The location of the template name in the source. 3998 /// 3999 /// \param TemplateArgs The list of template arguments. If the template is 4000 /// a template template parameter, this function may extend the set of 4001 /// template arguments to also include substituted, defaulted template 4002 /// arguments. 4003 /// 4004 /// \param PartialTemplateArgs True if the list of template arguments is 4005 /// intentionally partial, e.g., because we're checking just the initial 4006 /// set of template arguments. 4007 /// 4008 /// \param Converted Will receive the converted, canonicalized template 4009 /// arguments. 4010 /// 4011 /// \returns True if an error occurred, false otherwise. 4012 bool CheckTemplateArgumentList(TemplateDecl *Template, 4013 SourceLocation TemplateLoc, 4014 TemplateArgumentListInfo &TemplateArgs, 4015 bool PartialTemplateArgs, 4016 SmallVectorImpl<TemplateArgument> &Converted); 4017 4018 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, 4019 const TemplateArgumentLoc &Arg, 4020 SmallVectorImpl<TemplateArgument> &Converted); 4021 4022 bool CheckTemplateArgument(TemplateTypeParmDecl *Param, 4023 TypeSourceInfo *Arg); 4024 bool CheckTemplateArgumentPointerToMember(Expr *Arg, 4025 TemplateArgument &Converted); 4026 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 4027 QualType InstantiatedParamType, Expr *Arg, 4028 TemplateArgument &Converted, 4029 CheckTemplateArgumentKind CTAK = CTAK_Specified); 4030 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param, 4031 const TemplateArgumentLoc &Arg); 4032 4033 ExprResult 4034 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, 4035 QualType ParamType, 4036 SourceLocation Loc); 4037 ExprResult 4038 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, 4039 SourceLocation Loc); 4040 4041 /// \brief Enumeration describing how template parameter lists are compared 4042 /// for equality. 4043 enum TemplateParameterListEqualKind { 4044 /// \brief We are matching the template parameter lists of two templates 4045 /// that might be redeclarations. 4046 /// 4047 /// \code 4048 /// template<typename T> struct X; 4049 /// template<typename T> struct X; 4050 /// \endcode 4051 TPL_TemplateMatch, 4052 4053 /// \brief We are matching the template parameter lists of two template 4054 /// template parameters as part of matching the template parameter lists 4055 /// of two templates that might be redeclarations. 4056 /// 4057 /// \code 4058 /// template<template<int I> class TT> struct X; 4059 /// template<template<int Value> class Other> struct X; 4060 /// \endcode 4061 TPL_TemplateTemplateParmMatch, 4062 4063 /// \brief We are matching the template parameter lists of a template 4064 /// template argument against the template parameter lists of a template 4065 /// template parameter. 4066 /// 4067 /// \code 4068 /// template<template<int Value> class Metafun> struct X; 4069 /// template<int Value> struct integer_c; 4070 /// X<integer_c> xic; 4071 /// \endcode 4072 TPL_TemplateTemplateArgumentMatch 4073 }; 4074 4075 bool TemplateParameterListsAreEqual(TemplateParameterList *New, 4076 TemplateParameterList *Old, 4077 bool Complain, 4078 TemplateParameterListEqualKind Kind, 4079 SourceLocation TemplateArgLoc 4080 = SourceLocation()); 4081 4082 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); 4083 4084 /// \brief Called when the parser has parsed a C++ typename 4085 /// specifier, e.g., "typename T::type". 4086 /// 4087 /// \param S The scope in which this typename type occurs. 4088 /// \param TypenameLoc the location of the 'typename' keyword 4089 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 4090 /// \param II the identifier we're retrieving (e.g., 'type' in the example). 4091 /// \param IdLoc the location of the identifier. 4092 TypeResult 4093 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 4094 const CXXScopeSpec &SS, const IdentifierInfo &II, 4095 SourceLocation IdLoc); 4096 4097 /// \brief Called when the parser has parsed a C++ typename 4098 /// specifier that ends in a template-id, e.g., 4099 /// "typename MetaFun::template apply<T1, T2>". 4100 /// 4101 /// \param S The scope in which this typename type occurs. 4102 /// \param TypenameLoc the location of the 'typename' keyword 4103 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 4104 /// \param TemplateLoc the location of the 'template' keyword, if any. 4105 /// \param TemplateName The template name. 4106 /// \param TemplateNameLoc The location of the template name. 4107 /// \param LAngleLoc The location of the opening angle bracket ('<'). 4108 /// \param TemplateArgs The template arguments. 4109 /// \param RAngleLoc The location of the closing angle bracket ('>'). 4110 TypeResult 4111 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 4112 const CXXScopeSpec &SS, 4113 SourceLocation TemplateLoc, 4114 TemplateTy Template, 4115 SourceLocation TemplateNameLoc, 4116 SourceLocation LAngleLoc, 4117 ASTTemplateArgsPtr TemplateArgs, 4118 SourceLocation RAngleLoc); 4119 4120 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, 4121 SourceLocation KeywordLoc, 4122 NestedNameSpecifierLoc QualifierLoc, 4123 const IdentifierInfo &II, 4124 SourceLocation IILoc); 4125 4126 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, 4127 SourceLocation Loc, 4128 DeclarationName Name); 4129 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); 4130 4131 ExprResult RebuildExprInCurrentInstantiation(Expr *E); 4132 4133 std::string 4134 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 4135 const TemplateArgumentList &Args); 4136 4137 std::string 4138 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 4139 const TemplateArgument *Args, 4140 unsigned NumArgs); 4141 4142 //===--------------------------------------------------------------------===// 4143 // C++ Variadic Templates (C++0x [temp.variadic]) 4144 //===--------------------------------------------------------------------===// 4145 4146 /// \brief The context in which an unexpanded parameter pack is 4147 /// being diagnosed. 4148 /// 4149 /// Note that the values of this enumeration line up with the first 4150 /// argument to the \c err_unexpanded_parameter_pack diagnostic. 4151 enum UnexpandedParameterPackContext { 4152 /// \brief An arbitrary expression. 4153 UPPC_Expression = 0, 4154 4155 /// \brief The base type of a class type. 4156 UPPC_BaseType, 4157 4158 /// \brief The type of an arbitrary declaration. 4159 UPPC_DeclarationType, 4160 4161 /// \brief The type of a data member. 4162 UPPC_DataMemberType, 4163 4164 /// \brief The size of a bit-field. 4165 UPPC_BitFieldWidth, 4166 4167 /// \brief The expression in a static assertion. 4168 UPPC_StaticAssertExpression, 4169 4170 /// \brief The fixed underlying type of an enumeration. 4171 UPPC_FixedUnderlyingType, 4172 4173 /// \brief The enumerator value. 4174 UPPC_EnumeratorValue, 4175 4176 /// \brief A using declaration. 4177 UPPC_UsingDeclaration, 4178 4179 /// \brief A friend declaration. 4180 UPPC_FriendDeclaration, 4181 4182 /// \brief A declaration qualifier. 4183 UPPC_DeclarationQualifier, 4184 4185 /// \brief An initializer. 4186 UPPC_Initializer, 4187 4188 /// \brief A default argument. 4189 UPPC_DefaultArgument, 4190 4191 /// \brief The type of a non-type template parameter. 4192 UPPC_NonTypeTemplateParameterType, 4193 4194 /// \brief The type of an exception. 4195 UPPC_ExceptionType, 4196 4197 /// \brief Partial specialization. 4198 UPPC_PartialSpecialization 4199 }; 4200 4201 /// \brief If the given type contains an unexpanded parameter pack, 4202 /// diagnose the error. 4203 /// 4204 /// \param Loc The source location where a diagnostc should be emitted. 4205 /// 4206 /// \param T The type that is being checked for unexpanded parameter 4207 /// packs. 4208 /// 4209 /// \returns true if an error occurred, false otherwise. 4210 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, 4211 UnexpandedParameterPackContext UPPC); 4212 4213 /// \brief If the given expression contains an unexpanded parameter 4214 /// pack, diagnose the error. 4215 /// 4216 /// \param E The expression that is being checked for unexpanded 4217 /// parameter packs. 4218 /// 4219 /// \returns true if an error occurred, false otherwise. 4220 bool DiagnoseUnexpandedParameterPack(Expr *E, 4221 UnexpandedParameterPackContext UPPC = UPPC_Expression); 4222 4223 /// \brief If the given nested-name-specifier contains an unexpanded 4224 /// parameter pack, diagnose the error. 4225 /// 4226 /// \param SS The nested-name-specifier that is being checked for 4227 /// unexpanded parameter packs. 4228 /// 4229 /// \returns true if an error occurred, false otherwise. 4230 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, 4231 UnexpandedParameterPackContext UPPC); 4232 4233 /// \brief If the given name contains an unexpanded parameter pack, 4234 /// diagnose the error. 4235 /// 4236 /// \param NameInfo The name (with source location information) that 4237 /// is being checked for unexpanded parameter packs. 4238 /// 4239 /// \returns true if an error occurred, false otherwise. 4240 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, 4241 UnexpandedParameterPackContext UPPC); 4242 4243 /// \brief If the given template name contains an unexpanded parameter pack, 4244 /// diagnose the error. 4245 /// 4246 /// \param Loc The location of the template name. 4247 /// 4248 /// \param Template The template name that is being checked for unexpanded 4249 /// parameter packs. 4250 /// 4251 /// \returns true if an error occurred, false otherwise. 4252 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, 4253 TemplateName Template, 4254 UnexpandedParameterPackContext UPPC); 4255 4256 /// \brief If the given template argument contains an unexpanded parameter 4257 /// pack, diagnose the error. 4258 /// 4259 /// \param Arg The template argument that is being checked for unexpanded 4260 /// parameter packs. 4261 /// 4262 /// \returns true if an error occurred, false otherwise. 4263 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, 4264 UnexpandedParameterPackContext UPPC); 4265 4266 /// \brief Collect the set of unexpanded parameter packs within the given 4267 /// template argument. 4268 /// 4269 /// \param Arg The template argument that will be traversed to find 4270 /// unexpanded parameter packs. 4271 void collectUnexpandedParameterPacks(TemplateArgument Arg, 4272 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 4273 4274 /// \brief Collect the set of unexpanded parameter packs within the given 4275 /// template argument. 4276 /// 4277 /// \param Arg The template argument that will be traversed to find 4278 /// unexpanded parameter packs. 4279 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, 4280 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 4281 4282 /// \brief Collect the set of unexpanded parameter packs within the given 4283 /// type. 4284 /// 4285 /// \param T The type that will be traversed to find 4286 /// unexpanded parameter packs. 4287 void collectUnexpandedParameterPacks(QualType T, 4288 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 4289 4290 /// \brief Collect the set of unexpanded parameter packs within the given 4291 /// type. 4292 /// 4293 /// \param TL The type that will be traversed to find 4294 /// unexpanded parameter packs. 4295 void collectUnexpandedParameterPacks(TypeLoc TL, 4296 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 4297 4298 /// \brief Invoked when parsing a template argument followed by an 4299 /// ellipsis, which creates a pack expansion. 4300 /// 4301 /// \param Arg The template argument preceding the ellipsis, which 4302 /// may already be invalid. 4303 /// 4304 /// \param EllipsisLoc The location of the ellipsis. 4305 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, 4306 SourceLocation EllipsisLoc); 4307 4308 /// \brief Invoked when parsing a type followed by an ellipsis, which 4309 /// creates a pack expansion. 4310 /// 4311 /// \param Type The type preceding the ellipsis, which will become 4312 /// the pattern of the pack expansion. 4313 /// 4314 /// \param EllipsisLoc The location of the ellipsis. 4315 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); 4316 4317 /// \brief Construct a pack expansion type from the pattern of the pack 4318 /// expansion. 4319 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, 4320 SourceLocation EllipsisLoc, 4321 llvm::Optional<unsigned> NumExpansions); 4322 4323 /// \brief Construct a pack expansion type from the pattern of the pack 4324 /// expansion. 4325 QualType CheckPackExpansion(QualType Pattern, 4326 SourceRange PatternRange, 4327 SourceLocation EllipsisLoc, 4328 llvm::Optional<unsigned> NumExpansions); 4329 4330 /// \brief Invoked when parsing an expression followed by an ellipsis, which 4331 /// creates a pack expansion. 4332 /// 4333 /// \param Pattern The expression preceding the ellipsis, which will become 4334 /// the pattern of the pack expansion. 4335 /// 4336 /// \param EllipsisLoc The location of the ellipsis. 4337 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); 4338 4339 /// \brief Invoked when parsing an expression followed by an ellipsis, which 4340 /// creates a pack expansion. 4341 /// 4342 /// \param Pattern The expression preceding the ellipsis, which will become 4343 /// the pattern of the pack expansion. 4344 /// 4345 /// \param EllipsisLoc The location of the ellipsis. 4346 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, 4347 llvm::Optional<unsigned> NumExpansions); 4348 4349 /// \brief Determine whether we could expand a pack expansion with the 4350 /// given set of parameter packs into separate arguments by repeatedly 4351 /// transforming the pattern. 4352 /// 4353 /// \param EllipsisLoc The location of the ellipsis that identifies the 4354 /// pack expansion. 4355 /// 4356 /// \param PatternRange The source range that covers the entire pattern of 4357 /// the pack expansion. 4358 /// 4359 /// \param Unexpanded The set of unexpanded parameter packs within the 4360 /// pattern. 4361 /// 4362 /// \param NumUnexpanded The number of unexpanded parameter packs in 4363 /// \p Unexpanded. 4364 /// 4365 /// \param ShouldExpand Will be set to \c true if the transformer should 4366 /// expand the corresponding pack expansions into separate arguments. When 4367 /// set, \c NumExpansions must also be set. 4368 /// 4369 /// \param RetainExpansion Whether the caller should add an unexpanded 4370 /// pack expansion after all of the expanded arguments. This is used 4371 /// when extending explicitly-specified template argument packs per 4372 /// C++0x [temp.arg.explicit]p9. 4373 /// 4374 /// \param NumExpansions The number of separate arguments that will be in 4375 /// the expanded form of the corresponding pack expansion. This is both an 4376 /// input and an output parameter, which can be set by the caller if the 4377 /// number of expansions is known a priori (e.g., due to a prior substitution) 4378 /// and will be set by the callee when the number of expansions is known. 4379 /// The callee must set this value when \c ShouldExpand is \c true; it may 4380 /// set this value in other cases. 4381 /// 4382 /// \returns true if an error occurred (e.g., because the parameter packs 4383 /// are to be instantiated with arguments of different lengths), false 4384 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) 4385 /// must be set. 4386 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, 4387 SourceRange PatternRange, 4388 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded, 4389 const MultiLevelTemplateArgumentList &TemplateArgs, 4390 bool &ShouldExpand, 4391 bool &RetainExpansion, 4392 llvm::Optional<unsigned> &NumExpansions); 4393 4394 /// \brief Determine the number of arguments in the given pack expansion 4395 /// type. 4396 /// 4397 /// This routine already assumes that the pack expansion type can be 4398 /// expanded and that the number of arguments in the expansion is 4399 /// consistent across all of the unexpanded parameter packs in its pattern. 4400 unsigned getNumArgumentsInExpansion(QualType T, 4401 const MultiLevelTemplateArgumentList &TemplateArgs); 4402 4403 /// \brief Determine whether the given declarator contains any unexpanded 4404 /// parameter packs. 4405 /// 4406 /// This routine is used by the parser to disambiguate function declarators 4407 /// with an ellipsis prior to the ')', e.g., 4408 /// 4409 /// \code 4410 /// void f(T...); 4411 /// \endcode 4412 /// 4413 /// To determine whether we have an (unnamed) function parameter pack or 4414 /// a variadic function. 4415 /// 4416 /// \returns true if the declarator contains any unexpanded parameter packs, 4417 /// false otherwise. 4418 bool containsUnexpandedParameterPacks(Declarator &D); 4419 4420 //===--------------------------------------------------------------------===// 4421 // C++ Template Argument Deduction (C++ [temp.deduct]) 4422 //===--------------------------------------------------------------------===// 4423 4424 /// \brief Describes the result of template argument deduction. 4425 /// 4426 /// The TemplateDeductionResult enumeration describes the result of 4427 /// template argument deduction, as returned from 4428 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo 4429 /// structure provides additional information about the results of 4430 /// template argument deduction, e.g., the deduced template argument 4431 /// list (if successful) or the specific template parameters or 4432 /// deduced arguments that were involved in the failure. 4433 enum TemplateDeductionResult { 4434 /// \brief Template argument deduction was successful. 4435 TDK_Success = 0, 4436 /// \brief Template argument deduction exceeded the maximum template 4437 /// instantiation depth (which has already been diagnosed). 4438 TDK_InstantiationDepth, 4439 /// \brief Template argument deduction did not deduce a value 4440 /// for every template parameter. 4441 TDK_Incomplete, 4442 /// \brief Template argument deduction produced inconsistent 4443 /// deduced values for the given template parameter. 4444 TDK_Inconsistent, 4445 /// \brief Template argument deduction failed due to inconsistent 4446 /// cv-qualifiers on a template parameter type that would 4447 /// otherwise be deduced, e.g., we tried to deduce T in "const T" 4448 /// but were given a non-const "X". 4449 TDK_Underqualified, 4450 /// \brief Substitution of the deduced template argument values 4451 /// resulted in an error. 4452 TDK_SubstitutionFailure, 4453 /// \brief Substitution of the deduced template argument values 4454 /// into a non-deduced context produced a type or value that 4455 /// produces a type that does not match the original template 4456 /// arguments provided. 4457 TDK_NonDeducedMismatch, 4458 /// \brief When performing template argument deduction for a function 4459 /// template, there were too many call arguments. 4460 TDK_TooManyArguments, 4461 /// \brief When performing template argument deduction for a function 4462 /// template, there were too few call arguments. 4463 TDK_TooFewArguments, 4464 /// \brief The explicitly-specified template arguments were not valid 4465 /// template arguments for the given template. 4466 TDK_InvalidExplicitArguments, 4467 /// \brief The arguments included an overloaded function name that could 4468 /// not be resolved to a suitable function. 4469 TDK_FailedOverloadResolution 4470 }; 4471 4472 TemplateDeductionResult 4473 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, 4474 const TemplateArgumentList &TemplateArgs, 4475 sema::TemplateDeductionInfo &Info); 4476 4477 TemplateDeductionResult 4478 SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 4479 TemplateArgumentListInfo &ExplicitTemplateArgs, 4480 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 4481 SmallVectorImpl<QualType> &ParamTypes, 4482 QualType *FunctionType, 4483 sema::TemplateDeductionInfo &Info); 4484 4485 /// brief A function argument from which we performed template argument 4486 // deduction for a call. 4487 struct OriginalCallArg { 4488 OriginalCallArg(QualType OriginalParamType, 4489 unsigned ArgIdx, 4490 QualType OriginalArgType) 4491 : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx), 4492 OriginalArgType(OriginalArgType) { } 4493 4494 QualType OriginalParamType; 4495 unsigned ArgIdx; 4496 QualType OriginalArgType; 4497 }; 4498 4499 TemplateDeductionResult 4500 FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate, 4501 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 4502 unsigned NumExplicitlySpecified, 4503 FunctionDecl *&Specialization, 4504 sema::TemplateDeductionInfo &Info, 4505 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = 0); 4506 4507 TemplateDeductionResult 4508 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 4509 TemplateArgumentListInfo *ExplicitTemplateArgs, 4510 Expr **Args, unsigned NumArgs, 4511 FunctionDecl *&Specialization, 4512 sema::TemplateDeductionInfo &Info); 4513 4514 TemplateDeductionResult 4515 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 4516 TemplateArgumentListInfo *ExplicitTemplateArgs, 4517 QualType ArgFunctionType, 4518 FunctionDecl *&Specialization, 4519 sema::TemplateDeductionInfo &Info); 4520 4521 TemplateDeductionResult 4522 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 4523 QualType ToType, 4524 CXXConversionDecl *&Specialization, 4525 sema::TemplateDeductionInfo &Info); 4526 4527 TemplateDeductionResult 4528 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 4529 TemplateArgumentListInfo *ExplicitTemplateArgs, 4530 FunctionDecl *&Specialization, 4531 sema::TemplateDeductionInfo &Info); 4532 4533 bool DeduceAutoType(TypeSourceInfo *AutoType, Expr *Initializer, 4534 TypeSourceInfo *&Result); 4535 4536 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, 4537 FunctionTemplateDecl *FT2, 4538 SourceLocation Loc, 4539 TemplatePartialOrderingContext TPOC, 4540 unsigned NumCallArguments); 4541 UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, 4542 UnresolvedSetIterator SEnd, 4543 TemplatePartialOrderingContext TPOC, 4544 unsigned NumCallArguments, 4545 SourceLocation Loc, 4546 const PartialDiagnostic &NoneDiag, 4547 const PartialDiagnostic &AmbigDiag, 4548 const PartialDiagnostic &CandidateDiag, 4549 bool Complain = true); 4550 4551 ClassTemplatePartialSpecializationDecl * 4552 getMoreSpecializedPartialSpecialization( 4553 ClassTemplatePartialSpecializationDecl *PS1, 4554 ClassTemplatePartialSpecializationDecl *PS2, 4555 SourceLocation Loc); 4556 4557 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, 4558 bool OnlyDeduced, 4559 unsigned Depth, 4560 SmallVectorImpl<bool> &Used); 4561 void MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate, 4562 SmallVectorImpl<bool> &Deduced); 4563 4564 //===--------------------------------------------------------------------===// 4565 // C++ Template Instantiation 4566 // 4567 4568 MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D, 4569 const TemplateArgumentList *Innermost = 0, 4570 bool RelativeToPrimary = false, 4571 const FunctionDecl *Pattern = 0); 4572 4573 /// \brief A template instantiation that is currently in progress. 4574 struct ActiveTemplateInstantiation { 4575 /// \brief The kind of template instantiation we are performing 4576 enum InstantiationKind { 4577 /// We are instantiating a template declaration. The entity is 4578 /// the declaration we're instantiating (e.g., a CXXRecordDecl). 4579 TemplateInstantiation, 4580 4581 /// We are instantiating a default argument for a template 4582 /// parameter. The Entity is the template, and 4583 /// TemplateArgs/NumTemplateArguments provides the template 4584 /// arguments as specified. 4585 /// FIXME: Use a TemplateArgumentList 4586 DefaultTemplateArgumentInstantiation, 4587 4588 /// We are instantiating a default argument for a function. 4589 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs 4590 /// provides the template arguments as specified. 4591 DefaultFunctionArgumentInstantiation, 4592 4593 /// We are substituting explicit template arguments provided for 4594 /// a function template. The entity is a FunctionTemplateDecl. 4595 ExplicitTemplateArgumentSubstitution, 4596 4597 /// We are substituting template argument determined as part of 4598 /// template argument deduction for either a class template 4599 /// partial specialization or a function template. The 4600 /// Entity is either a ClassTemplatePartialSpecializationDecl or 4601 /// a FunctionTemplateDecl. 4602 DeducedTemplateArgumentSubstitution, 4603 4604 /// We are substituting prior template arguments into a new 4605 /// template parameter. The template parameter itself is either a 4606 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. 4607 PriorTemplateArgumentSubstitution, 4608 4609 /// We are checking the validity of a default template argument that 4610 /// has been used when naming a template-id. 4611 DefaultTemplateArgumentChecking 4612 } Kind; 4613 4614 /// \brief The point of instantiation within the source code. 4615 SourceLocation PointOfInstantiation; 4616 4617 /// \brief The template (or partial specialization) in which we are 4618 /// performing the instantiation, for substitutions of prior template 4619 /// arguments. 4620 NamedDecl *Template; 4621 4622 /// \brief The entity that is being instantiated. 4623 uintptr_t Entity; 4624 4625 /// \brief The list of template arguments we are substituting, if they 4626 /// are not part of the entity. 4627 const TemplateArgument *TemplateArgs; 4628 4629 /// \brief The number of template arguments in TemplateArgs. 4630 unsigned NumTemplateArgs; 4631 4632 /// \brief The template deduction info object associated with the 4633 /// substitution or checking of explicit or deduced template arguments. 4634 sema::TemplateDeductionInfo *DeductionInfo; 4635 4636 /// \brief The source range that covers the construct that cause 4637 /// the instantiation, e.g., the template-id that causes a class 4638 /// template instantiation. 4639 SourceRange InstantiationRange; 4640 4641 ActiveTemplateInstantiation() 4642 : Kind(TemplateInstantiation), Template(0), Entity(0), TemplateArgs(0), 4643 NumTemplateArgs(0), DeductionInfo(0) {} 4644 4645 /// \brief Determines whether this template is an actual instantiation 4646 /// that should be counted toward the maximum instantiation depth. 4647 bool isInstantiationRecord() const; 4648 4649 friend bool operator==(const ActiveTemplateInstantiation &X, 4650 const ActiveTemplateInstantiation &Y) { 4651 if (X.Kind != Y.Kind) 4652 return false; 4653 4654 if (X.Entity != Y.Entity) 4655 return false; 4656 4657 switch (X.Kind) { 4658 case TemplateInstantiation: 4659 return true; 4660 4661 case PriorTemplateArgumentSubstitution: 4662 case DefaultTemplateArgumentChecking: 4663 if (X.Template != Y.Template) 4664 return false; 4665 4666 // Fall through 4667 4668 case DefaultTemplateArgumentInstantiation: 4669 case ExplicitTemplateArgumentSubstitution: 4670 case DeducedTemplateArgumentSubstitution: 4671 case DefaultFunctionArgumentInstantiation: 4672 return X.TemplateArgs == Y.TemplateArgs; 4673 4674 } 4675 4676 return true; 4677 } 4678 4679 friend bool operator!=(const ActiveTemplateInstantiation &X, 4680 const ActiveTemplateInstantiation &Y) { 4681 return !(X == Y); 4682 } 4683 }; 4684 4685 /// \brief List of active template instantiations. 4686 /// 4687 /// This vector is treated as a stack. As one template instantiation 4688 /// requires another template instantiation, additional 4689 /// instantiations are pushed onto the stack up to a 4690 /// user-configurable limit LangOptions::InstantiationDepth. 4691 SmallVector<ActiveTemplateInstantiation, 16> 4692 ActiveTemplateInstantiations; 4693 4694 /// \brief Whether we are in a SFINAE context that is not associated with 4695 /// template instantiation. 4696 /// 4697 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside 4698 /// of a template instantiation or template argument deduction. 4699 bool InNonInstantiationSFINAEContext; 4700 4701 /// \brief The number of ActiveTemplateInstantiation entries in 4702 /// \c ActiveTemplateInstantiations that are not actual instantiations and, 4703 /// therefore, should not be counted as part of the instantiation depth. 4704 unsigned NonInstantiationEntries; 4705 4706 /// \brief The last template from which a template instantiation 4707 /// error or warning was produced. 4708 /// 4709 /// This value is used to suppress printing of redundant template 4710 /// instantiation backtraces when there are multiple errors in the 4711 /// same instantiation. FIXME: Does this belong in Sema? It's tough 4712 /// to implement it anywhere else. 4713 ActiveTemplateInstantiation LastTemplateInstantiationErrorContext; 4714 4715 /// \brief The current index into pack expansion arguments that will be 4716 /// used for substitution of parameter packs. 4717 /// 4718 /// The pack expansion index will be -1 to indicate that parameter packs 4719 /// should be instantiated as themselves. Otherwise, the index specifies 4720 /// which argument within the parameter pack will be used for substitution. 4721 int ArgumentPackSubstitutionIndex; 4722 4723 /// \brief RAII object used to change the argument pack substitution index 4724 /// within a \c Sema object. 4725 /// 4726 /// See \c ArgumentPackSubstitutionIndex for more information. 4727 class ArgumentPackSubstitutionIndexRAII { 4728 Sema &Self; 4729 int OldSubstitutionIndex; 4730 4731 public: 4732 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) 4733 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { 4734 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; 4735 } 4736 4737 ~ArgumentPackSubstitutionIndexRAII() { 4738 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; 4739 } 4740 }; 4741 4742 friend class ArgumentPackSubstitutionRAII; 4743 4744 /// \brief The stack of calls expression undergoing template instantiation. 4745 /// 4746 /// The top of this stack is used by a fixit instantiating unresolved 4747 /// function calls to fix the AST to match the textual change it prints. 4748 SmallVector<CallExpr *, 8> CallsUndergoingInstantiation; 4749 4750 /// \brief For each declaration that involved template argument deduction, the 4751 /// set of diagnostics that were suppressed during that template argument 4752 /// deduction. 4753 /// 4754 /// FIXME: Serialize this structure to the AST file. 4755 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > 4756 SuppressedDiagnostics; 4757 4758 /// \brief A stack object to be created when performing template 4759 /// instantiation. 4760 /// 4761 /// Construction of an object of type \c InstantiatingTemplate 4762 /// pushes the current instantiation onto the stack of active 4763 /// instantiations. If the size of this stack exceeds the maximum 4764 /// number of recursive template instantiations, construction 4765 /// produces an error and evaluates true. 4766 /// 4767 /// Destruction of this object will pop the named instantiation off 4768 /// the stack. 4769 struct InstantiatingTemplate { 4770 /// \brief Note that we are instantiating a class template, 4771 /// function template, or a member thereof. 4772 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 4773 Decl *Entity, 4774 SourceRange InstantiationRange = SourceRange()); 4775 4776 /// \brief Note that we are instantiating a default argument in a 4777 /// template-id. 4778 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 4779 TemplateDecl *Template, 4780 const TemplateArgument *TemplateArgs, 4781 unsigned NumTemplateArgs, 4782 SourceRange InstantiationRange = SourceRange()); 4783 4784 /// \brief Note that we are instantiating a default argument in a 4785 /// template-id. 4786 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 4787 FunctionTemplateDecl *FunctionTemplate, 4788 const TemplateArgument *TemplateArgs, 4789 unsigned NumTemplateArgs, 4790 ActiveTemplateInstantiation::InstantiationKind Kind, 4791 sema::TemplateDeductionInfo &DeductionInfo, 4792 SourceRange InstantiationRange = SourceRange()); 4793 4794 /// \brief Note that we are instantiating as part of template 4795 /// argument deduction for a class template partial 4796 /// specialization. 4797 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 4798 ClassTemplatePartialSpecializationDecl *PartialSpec, 4799 const TemplateArgument *TemplateArgs, 4800 unsigned NumTemplateArgs, 4801 sema::TemplateDeductionInfo &DeductionInfo, 4802 SourceRange InstantiationRange = SourceRange()); 4803 4804 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 4805 ParmVarDecl *Param, 4806 const TemplateArgument *TemplateArgs, 4807 unsigned NumTemplateArgs, 4808 SourceRange InstantiationRange = SourceRange()); 4809 4810 /// \brief Note that we are substituting prior template arguments into a 4811 /// non-type or template template parameter. 4812 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 4813 NamedDecl *Template, 4814 NonTypeTemplateParmDecl *Param, 4815 const TemplateArgument *TemplateArgs, 4816 unsigned NumTemplateArgs, 4817 SourceRange InstantiationRange); 4818 4819 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 4820 NamedDecl *Template, 4821 TemplateTemplateParmDecl *Param, 4822 const TemplateArgument *TemplateArgs, 4823 unsigned NumTemplateArgs, 4824 SourceRange InstantiationRange); 4825 4826 /// \brief Note that we are checking the default template argument 4827 /// against the template parameter for a given template-id. 4828 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 4829 TemplateDecl *Template, 4830 NamedDecl *Param, 4831 const TemplateArgument *TemplateArgs, 4832 unsigned NumTemplateArgs, 4833 SourceRange InstantiationRange); 4834 4835 4836 /// \brief Note that we have finished instantiating this template. 4837 void Clear(); 4838 4839 ~InstantiatingTemplate() { Clear(); } 4840 4841 /// \brief Determines whether we have exceeded the maximum 4842 /// recursive template instantiations. 4843 operator bool() const { return Invalid; } 4844 4845 private: 4846 Sema &SemaRef; 4847 bool Invalid; 4848 bool SavedInNonInstantiationSFINAEContext; 4849 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, 4850 SourceRange InstantiationRange); 4851 4852 InstantiatingTemplate(const InstantiatingTemplate&); // not implemented 4853 4854 InstantiatingTemplate& 4855 operator=(const InstantiatingTemplate&); // not implemented 4856 }; 4857 4858 void PrintInstantiationStack(); 4859 4860 /// \brief Determines whether we are currently in a context where 4861 /// template argument substitution failures are not considered 4862 /// errors. 4863 /// 4864 /// \returns An empty \c llvm::Optional if we're not in a SFINAE context. 4865 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest 4866 /// template-deduction context object, which can be used to capture 4867 /// diagnostics that will be suppressed. 4868 llvm::Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; 4869 4870 /// \brief RAII class used to determine whether SFINAE has 4871 /// trapped any errors that occur during template argument 4872 /// deduction.` 4873 class SFINAETrap { 4874 Sema &SemaRef; 4875 unsigned PrevSFINAEErrors; 4876 bool PrevInNonInstantiationSFINAEContext; 4877 bool PrevAccessCheckingSFINAE; 4878 4879 public: 4880 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) 4881 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), 4882 PrevInNonInstantiationSFINAEContext( 4883 SemaRef.InNonInstantiationSFINAEContext), 4884 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE) 4885 { 4886 if (!SemaRef.isSFINAEContext()) 4887 SemaRef.InNonInstantiationSFINAEContext = true; 4888 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; 4889 } 4890 4891 ~SFINAETrap() { 4892 SemaRef.NumSFINAEErrors = PrevSFINAEErrors; 4893 SemaRef.InNonInstantiationSFINAEContext 4894 = PrevInNonInstantiationSFINAEContext; 4895 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; 4896 } 4897 4898 /// \brief Determine whether any SFINAE errors have been trapped. 4899 bool hasErrorOccurred() const { 4900 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; 4901 } 4902 }; 4903 4904 /// \brief The current instantiation scope used to store local 4905 /// variables. 4906 LocalInstantiationScope *CurrentInstantiationScope; 4907 4908 /// \brief The number of typos corrected by CorrectTypo. 4909 unsigned TyposCorrected; 4910 4911 typedef llvm::DenseMap<IdentifierInfo *, TypoCorrection> 4912 UnqualifiedTyposCorrectedMap; 4913 4914 /// \brief A cache containing the results of typo correction for unqualified 4915 /// name lookup. 4916 /// 4917 /// The string is the string that we corrected to (which may be empty, if 4918 /// there was no correction), while the boolean will be true when the 4919 /// string represents a keyword. 4920 UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected; 4921 4922 /// \brief Worker object for performing CFG-based warnings. 4923 sema::AnalysisBasedWarnings AnalysisWarnings; 4924 4925 /// \brief An entity for which implicit template instantiation is required. 4926 /// 4927 /// The source location associated with the declaration is the first place in 4928 /// the source code where the declaration was "used". It is not necessarily 4929 /// the point of instantiation (which will be either before or after the 4930 /// namespace-scope declaration that triggered this implicit instantiation), 4931 /// However, it is the location that diagnostics should generally refer to, 4932 /// because users will need to know what code triggered the instantiation. 4933 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; 4934 4935 /// \brief The queue of implicit template instantiations that are required 4936 /// but have not yet been performed. 4937 std::deque<PendingImplicitInstantiation> PendingInstantiations; 4938 4939 /// \brief The queue of implicit template instantiations that are required 4940 /// and must be performed within the current local scope. 4941 /// 4942 /// This queue is only used for member functions of local classes in 4943 /// templates, which must be instantiated in the same scope as their 4944 /// enclosing function, so that they can reference function-local 4945 /// types, static variables, enumerators, etc. 4946 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; 4947 4948 void PerformPendingInstantiations(bool LocalOnly = false); 4949 4950 TypeSourceInfo *SubstType(TypeSourceInfo *T, 4951 const MultiLevelTemplateArgumentList &TemplateArgs, 4952 SourceLocation Loc, DeclarationName Entity); 4953 4954 QualType SubstType(QualType T, 4955 const MultiLevelTemplateArgumentList &TemplateArgs, 4956 SourceLocation Loc, DeclarationName Entity); 4957 4958 TypeSourceInfo *SubstType(TypeLoc TL, 4959 const MultiLevelTemplateArgumentList &TemplateArgs, 4960 SourceLocation Loc, DeclarationName Entity); 4961 4962 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, 4963 const MultiLevelTemplateArgumentList &TemplateArgs, 4964 SourceLocation Loc, 4965 DeclarationName Entity); 4966 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, 4967 const MultiLevelTemplateArgumentList &TemplateArgs, 4968 int indexAdjustment, 4969 llvm::Optional<unsigned> NumExpansions); 4970 bool SubstParmTypes(SourceLocation Loc, 4971 ParmVarDecl **Params, unsigned NumParams, 4972 const MultiLevelTemplateArgumentList &TemplateArgs, 4973 SmallVectorImpl<QualType> &ParamTypes, 4974 SmallVectorImpl<ParmVarDecl *> *OutParams = 0); 4975 ExprResult SubstExpr(Expr *E, 4976 const MultiLevelTemplateArgumentList &TemplateArgs); 4977 4978 /// \brief Substitute the given template arguments into a list of 4979 /// expressions, expanding pack expansions if required. 4980 /// 4981 /// \param Exprs The list of expressions to substitute into. 4982 /// 4983 /// \param NumExprs The number of expressions in \p Exprs. 4984 /// 4985 /// \param IsCall Whether this is some form of call, in which case 4986 /// default arguments will be dropped. 4987 /// 4988 /// \param TemplateArgs The set of template arguments to substitute. 4989 /// 4990 /// \param Outputs Will receive all of the substituted arguments. 4991 /// 4992 /// \returns true if an error occurred, false otherwise. 4993 bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall, 4994 const MultiLevelTemplateArgumentList &TemplateArgs, 4995 SmallVectorImpl<Expr *> &Outputs); 4996 4997 StmtResult SubstStmt(Stmt *S, 4998 const MultiLevelTemplateArgumentList &TemplateArgs); 4999 5000 Decl *SubstDecl(Decl *D, DeclContext *Owner, 5001 const MultiLevelTemplateArgumentList &TemplateArgs); 5002 5003 bool 5004 SubstBaseSpecifiers(CXXRecordDecl *Instantiation, 5005 CXXRecordDecl *Pattern, 5006 const MultiLevelTemplateArgumentList &TemplateArgs); 5007 5008 bool 5009 InstantiateClass(SourceLocation PointOfInstantiation, 5010 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, 5011 const MultiLevelTemplateArgumentList &TemplateArgs, 5012 TemplateSpecializationKind TSK, 5013 bool Complain = true); 5014 5015 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, 5016 const Decl *Pattern, Decl *Inst); 5017 5018 bool 5019 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, 5020 ClassTemplateSpecializationDecl *ClassTemplateSpec, 5021 TemplateSpecializationKind TSK, 5022 bool Complain = true); 5023 5024 void InstantiateClassMembers(SourceLocation PointOfInstantiation, 5025 CXXRecordDecl *Instantiation, 5026 const MultiLevelTemplateArgumentList &TemplateArgs, 5027 TemplateSpecializationKind TSK); 5028 5029 void InstantiateClassTemplateSpecializationMembers( 5030 SourceLocation PointOfInstantiation, 5031 ClassTemplateSpecializationDecl *ClassTemplateSpec, 5032 TemplateSpecializationKind TSK); 5033 5034 NestedNameSpecifierLoc 5035 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 5036 const MultiLevelTemplateArgumentList &TemplateArgs); 5037 5038 DeclarationNameInfo 5039 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 5040 const MultiLevelTemplateArgumentList &TemplateArgs); 5041 TemplateName 5042 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, 5043 SourceLocation Loc, 5044 const MultiLevelTemplateArgumentList &TemplateArgs); 5045 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, 5046 TemplateArgumentListInfo &Result, 5047 const MultiLevelTemplateArgumentList &TemplateArgs); 5048 5049 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 5050 FunctionDecl *Function, 5051 bool Recursive = false, 5052 bool DefinitionRequired = false); 5053 void InstantiateStaticDataMemberDefinition( 5054 SourceLocation PointOfInstantiation, 5055 VarDecl *Var, 5056 bool Recursive = false, 5057 bool DefinitionRequired = false); 5058 5059 void InstantiateMemInitializers(CXXConstructorDecl *New, 5060 const CXXConstructorDecl *Tmpl, 5061 const MultiLevelTemplateArgumentList &TemplateArgs); 5062 bool InstantiateInitializer(Expr *Init, 5063 const MultiLevelTemplateArgumentList &TemplateArgs, 5064 SourceLocation &LParenLoc, 5065 ASTOwningVector<Expr*> &NewArgs, 5066 SourceLocation &RParenLoc); 5067 5068 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 5069 const MultiLevelTemplateArgumentList &TemplateArgs); 5070 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, 5071 const MultiLevelTemplateArgumentList &TemplateArgs); 5072 5073 // Objective-C declarations. 5074 Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc, 5075 IdentifierInfo *ClassName, 5076 SourceLocation ClassLoc, 5077 IdentifierInfo *SuperName, 5078 SourceLocation SuperLoc, 5079 Decl * const *ProtoRefs, 5080 unsigned NumProtoRefs, 5081 const SourceLocation *ProtoLocs, 5082 SourceLocation EndProtoLoc, 5083 AttributeList *AttrList); 5084 5085 Decl *ActOnCompatiblityAlias( 5086 SourceLocation AtCompatibilityAliasLoc, 5087 IdentifierInfo *AliasName, SourceLocation AliasLocation, 5088 IdentifierInfo *ClassName, SourceLocation ClassLocation); 5089 5090 bool CheckForwardProtocolDeclarationForCircularDependency( 5091 IdentifierInfo *PName, 5092 SourceLocation &PLoc, SourceLocation PrevLoc, 5093 const ObjCList<ObjCProtocolDecl> &PList); 5094 5095 Decl *ActOnStartProtocolInterface( 5096 SourceLocation AtProtoInterfaceLoc, 5097 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, 5098 Decl * const *ProtoRefNames, unsigned NumProtoRefs, 5099 const SourceLocation *ProtoLocs, 5100 SourceLocation EndProtoLoc, 5101 AttributeList *AttrList); 5102 5103 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc, 5104 IdentifierInfo *ClassName, 5105 SourceLocation ClassLoc, 5106 IdentifierInfo *CategoryName, 5107 SourceLocation CategoryLoc, 5108 Decl * const *ProtoRefs, 5109 unsigned NumProtoRefs, 5110 const SourceLocation *ProtoLocs, 5111 SourceLocation EndProtoLoc); 5112 5113 Decl *ActOnStartClassImplementation( 5114 SourceLocation AtClassImplLoc, 5115 IdentifierInfo *ClassName, SourceLocation ClassLoc, 5116 IdentifierInfo *SuperClassname, 5117 SourceLocation SuperClassLoc); 5118 5119 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, 5120 IdentifierInfo *ClassName, 5121 SourceLocation ClassLoc, 5122 IdentifierInfo *CatName, 5123 SourceLocation CatLoc); 5124 5125 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, 5126 IdentifierInfo **IdentList, 5127 SourceLocation *IdentLocs, 5128 unsigned NumElts); 5129 5130 Decl *ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, 5131 const IdentifierLocPair *IdentList, 5132 unsigned NumElts, 5133 AttributeList *attrList); 5134 5135 void FindProtocolDeclaration(bool WarnOnDeclarations, 5136 const IdentifierLocPair *ProtocolId, 5137 unsigned NumProtocols, 5138 SmallVectorImpl<Decl *> &Protocols); 5139 5140 /// Ensure attributes are consistent with type. 5141 /// \param [in, out] Attributes The attributes to check; they will 5142 /// be modified to be consistent with \arg PropertyTy. 5143 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, 5144 SourceLocation Loc, 5145 unsigned &Attributes); 5146 5147 /// Process the specified property declaration and create decls for the 5148 /// setters and getters as needed. 5149 /// \param property The property declaration being processed 5150 /// \param DC The semantic container for the property 5151 /// \param redeclaredProperty Declaration for property if redeclared 5152 /// in class extension. 5153 /// \param lexicalDC Container for redeclaredProperty. 5154 void ProcessPropertyDecl(ObjCPropertyDecl *property, 5155 ObjCContainerDecl *DC, 5156 ObjCPropertyDecl *redeclaredProperty = 0, 5157 ObjCContainerDecl *lexicalDC = 0); 5158 5159 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, 5160 ObjCPropertyDecl *SuperProperty, 5161 const IdentifierInfo *Name); 5162 void ComparePropertiesInBaseAndSuper(ObjCInterfaceDecl *IDecl); 5163 5164 void CompareMethodParamsInBaseAndSuper(Decl *IDecl, 5165 ObjCMethodDecl *MethodDecl, 5166 bool IsInstance); 5167 5168 void CompareProperties(Decl *CDecl, Decl *MergeProtocols); 5169 5170 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, 5171 ObjCInterfaceDecl *ID); 5172 5173 void MatchOneProtocolPropertiesInClass(Decl *CDecl, 5174 ObjCProtocolDecl *PDecl); 5175 5176 void ActOnAtEnd(Scope *S, SourceRange AtEnd, 5177 Decl **allMethods = 0, unsigned allNum = 0, 5178 Decl **allProperties = 0, unsigned pNum = 0, 5179 DeclGroupPtrTy *allTUVars = 0, unsigned tuvNum = 0); 5180 5181 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, 5182 FieldDeclarator &FD, ObjCDeclSpec &ODS, 5183 Selector GetterSel, Selector SetterSel, 5184 bool *OverridingProperty, 5185 tok::ObjCKeywordKind MethodImplKind, 5186 DeclContext *lexicalDC = 0); 5187 5188 Decl *ActOnPropertyImplDecl(Scope *S, 5189 SourceLocation AtLoc, 5190 SourceLocation PropertyLoc, 5191 bool ImplKind, 5192 IdentifierInfo *PropertyId, 5193 IdentifierInfo *PropertyIvar, 5194 SourceLocation PropertyIvarLoc); 5195 5196 enum ObjCSpecialMethodKind { 5197 OSMK_None, 5198 OSMK_Alloc, 5199 OSMK_New, 5200 OSMK_Copy, 5201 OSMK_RetainingInit, 5202 OSMK_NonRetainingInit 5203 }; 5204 5205 struct ObjCArgInfo { 5206 IdentifierInfo *Name; 5207 SourceLocation NameLoc; 5208 // The Type is null if no type was specified, and the DeclSpec is invalid 5209 // in this case. 5210 ParsedType Type; 5211 ObjCDeclSpec DeclSpec; 5212 5213 /// ArgAttrs - Attribute list for this argument. 5214 AttributeList *ArgAttrs; 5215 }; 5216 5217 Decl *ActOnMethodDeclaration( 5218 Scope *S, 5219 SourceLocation BeginLoc, // location of the + or -. 5220 SourceLocation EndLoc, // location of the ; or {. 5221 tok::TokenKind MethodType, 5222 ObjCDeclSpec &ReturnQT, ParsedType ReturnType, 5223 ArrayRef<SourceLocation> SelectorLocs, Selector Sel, 5224 // optional arguments. The number of types/arguments is obtained 5225 // from the Sel.getNumArgs(). 5226 ObjCArgInfo *ArgInfo, 5227 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args 5228 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind, 5229 bool isVariadic, bool MethodDefinition); 5230 5231 // Helper method for ActOnClassMethod/ActOnInstanceMethod. 5232 // Will search "local" class/category implementations for a method decl. 5233 // Will also search in class's root looking for instance method. 5234 // Returns 0 if no method is found. 5235 ObjCMethodDecl *LookupPrivateClassMethod(Selector Sel, 5236 ObjCInterfaceDecl *CDecl); 5237 ObjCMethodDecl *LookupPrivateInstanceMethod(Selector Sel, 5238 ObjCInterfaceDecl *ClassDecl); 5239 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, 5240 const ObjCObjectPointerType *OPT, 5241 bool IsInstance); 5242 5243 bool inferObjCARCLifetime(ValueDecl *decl); 5244 5245 ExprResult 5246 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, 5247 Expr *BaseExpr, 5248 SourceLocation OpLoc, 5249 DeclarationName MemberName, 5250 SourceLocation MemberLoc, 5251 SourceLocation SuperLoc, QualType SuperType, 5252 bool Super); 5253 5254 ExprResult 5255 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, 5256 IdentifierInfo &propertyName, 5257 SourceLocation receiverNameLoc, 5258 SourceLocation propertyNameLoc); 5259 5260 ObjCMethodDecl *tryCaptureObjCSelf(); 5261 5262 /// \brief Describes the kind of message expression indicated by a message 5263 /// send that starts with an identifier. 5264 enum ObjCMessageKind { 5265 /// \brief The message is sent to 'super'. 5266 ObjCSuperMessage, 5267 /// \brief The message is an instance message. 5268 ObjCInstanceMessage, 5269 /// \brief The message is a class message, and the identifier is a type 5270 /// name. 5271 ObjCClassMessage 5272 }; 5273 5274 ObjCMessageKind getObjCMessageKind(Scope *S, 5275 IdentifierInfo *Name, 5276 SourceLocation NameLoc, 5277 bool IsSuper, 5278 bool HasTrailingDot, 5279 ParsedType &ReceiverType); 5280 5281 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, 5282 Selector Sel, 5283 SourceLocation LBracLoc, 5284 ArrayRef<SourceLocation> SelectorLocs, 5285 SourceLocation RBracLoc, 5286 MultiExprArg Args); 5287 5288 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, 5289 QualType ReceiverType, 5290 SourceLocation SuperLoc, 5291 Selector Sel, 5292 ObjCMethodDecl *Method, 5293 SourceLocation LBracLoc, 5294 ArrayRef<SourceLocation> SelectorLocs, 5295 SourceLocation RBracLoc, 5296 MultiExprArg Args); 5297 5298 ExprResult ActOnClassMessage(Scope *S, 5299 ParsedType Receiver, 5300 Selector Sel, 5301 SourceLocation LBracLoc, 5302 ArrayRef<SourceLocation> SelectorLocs, 5303 SourceLocation RBracLoc, 5304 MultiExprArg Args); 5305 5306 ExprResult BuildInstanceMessage(Expr *Receiver, 5307 QualType ReceiverType, 5308 SourceLocation SuperLoc, 5309 Selector Sel, 5310 ObjCMethodDecl *Method, 5311 SourceLocation LBracLoc, 5312 ArrayRef<SourceLocation> SelectorLocs, 5313 SourceLocation RBracLoc, 5314 MultiExprArg Args); 5315 5316 ExprResult ActOnInstanceMessage(Scope *S, 5317 Expr *Receiver, 5318 Selector Sel, 5319 SourceLocation LBracLoc, 5320 ArrayRef<SourceLocation> SelectorLocs, 5321 SourceLocation RBracLoc, 5322 MultiExprArg Args); 5323 5324 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, 5325 ObjCBridgeCastKind Kind, 5326 SourceLocation BridgeKeywordLoc, 5327 TypeSourceInfo *TSInfo, 5328 Expr *SubExpr); 5329 5330 ExprResult ActOnObjCBridgedCast(Scope *S, 5331 SourceLocation LParenLoc, 5332 ObjCBridgeCastKind Kind, 5333 SourceLocation BridgeKeywordLoc, 5334 ParsedType Type, 5335 SourceLocation RParenLoc, 5336 Expr *SubExpr); 5337 5338 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); 5339 5340 /// \brief Check whether the given new method is a valid override of the 5341 /// given overridden method, and set any properties that should be inherited. 5342 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, 5343 const ObjCMethodDecl *Overridden, 5344 bool IsImplementation); 5345 5346 /// \brief Check whether the given method overrides any methods in its class, 5347 /// calling \c CheckObjCMethodOverride for each overridden method. 5348 bool CheckObjCMethodOverrides(ObjCMethodDecl *NewMethod, DeclContext *DC); 5349 5350 enum PragmaOptionsAlignKind { 5351 POAK_Native, // #pragma options align=native 5352 POAK_Natural, // #pragma options align=natural 5353 POAK_Packed, // #pragma options align=packed 5354 POAK_Power, // #pragma options align=power 5355 POAK_Mac68k, // #pragma options align=mac68k 5356 POAK_Reset // #pragma options align=reset 5357 }; 5358 5359 /// ActOnPragmaOptionsAlign - Called on well formed #pragma options align. 5360 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, 5361 SourceLocation PragmaLoc, 5362 SourceLocation KindLoc); 5363 5364 enum PragmaPackKind { 5365 PPK_Default, // #pragma pack([n]) 5366 PPK_Show, // #pragma pack(show), only supported by MSVC. 5367 PPK_Push, // #pragma pack(push, [identifier], [n]) 5368 PPK_Pop // #pragma pack(pop, [identifier], [n]) 5369 }; 5370 5371 enum PragmaMSStructKind { 5372 PMSST_OFF, // #pragms ms_struct off 5373 PMSST_ON // #pragms ms_struct on 5374 }; 5375 5376 /// ActOnPragmaPack - Called on well formed #pragma pack(...). 5377 void ActOnPragmaPack(PragmaPackKind Kind, 5378 IdentifierInfo *Name, 5379 Expr *Alignment, 5380 SourceLocation PragmaLoc, 5381 SourceLocation LParenLoc, 5382 SourceLocation RParenLoc); 5383 5384 /// ActOnPragmaMSStruct - Called on well formed #pragms ms_struct [on|off]. 5385 void ActOnPragmaMSStruct(PragmaMSStructKind Kind); 5386 5387 /// ActOnPragmaUnused - Called on well-formed '#pragma unused'. 5388 void ActOnPragmaUnused(const Token &Identifier, 5389 Scope *curScope, 5390 SourceLocation PragmaLoc); 5391 5392 /// ActOnPragmaVisibility - Called on well formed #pragma GCC visibility... . 5393 void ActOnPragmaVisibility(bool IsPush, const IdentifierInfo* VisType, 5394 SourceLocation PragmaLoc); 5395 5396 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, 5397 SourceLocation Loc); 5398 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); 5399 5400 /// ActOnPragmaWeakID - Called on well formed #pragma weak ident. 5401 void ActOnPragmaWeakID(IdentifierInfo* WeakName, 5402 SourceLocation PragmaLoc, 5403 SourceLocation WeakNameLoc); 5404 5405 /// ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident. 5406 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, 5407 IdentifierInfo* AliasName, 5408 SourceLocation PragmaLoc, 5409 SourceLocation WeakNameLoc, 5410 SourceLocation AliasNameLoc); 5411 5412 /// ActOnPragmaFPContract - Called on well formed 5413 /// #pragma {STDC,OPENCL} FP_CONTRACT 5414 void ActOnPragmaFPContract(tok::OnOffSwitch OOS); 5415 5416 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to 5417 /// a the record decl, to handle '#pragma pack' and '#pragma options align'. 5418 void AddAlignmentAttributesForRecord(RecordDecl *RD); 5419 5420 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. 5421 void AddMsStructLayoutForRecord(RecordDecl *RD); 5422 5423 /// FreePackedContext - Deallocate and null out PackContext. 5424 void FreePackedContext(); 5425 5426 /// PushNamespaceVisibilityAttr - Note that we've entered a 5427 /// namespace with a visibility attribute. 5428 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr); 5429 5430 /// AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, 5431 /// add an appropriate visibility attribute. 5432 void AddPushedVisibilityAttribute(Decl *RD); 5433 5434 /// PopPragmaVisibility - Pop the top element of the visibility stack; used 5435 /// for '#pragma GCC visibility' and visibility attributes on namespaces. 5436 void PopPragmaVisibility(); 5437 5438 /// FreeVisContext - Deallocate and null out VisContext. 5439 void FreeVisContext(); 5440 5441 /// AddCFAuditedAttribute - Check whether we're currently within 5442 /// '#pragma clang arc_cf_code_audited' and, if so, consider adding 5443 /// the appropriate attribute. 5444 void AddCFAuditedAttribute(Decl *D); 5445 5446 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. 5447 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E); 5448 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T); 5449 5450 /// \brief The kind of conversion being performed. 5451 enum CheckedConversionKind { 5452 /// \brief An implicit conversion. 5453 CCK_ImplicitConversion, 5454 /// \brief A C-style cast. 5455 CCK_CStyleCast, 5456 /// \brief A functional-style cast. 5457 CCK_FunctionalCast, 5458 /// \brief A cast other than a C-style cast. 5459 CCK_OtherCast 5460 }; 5461 5462 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit 5463 /// cast. If there is already an implicit cast, merge into the existing one. 5464 /// If isLvalue, the result of the cast is an lvalue. 5465 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, 5466 ExprValueKind VK = VK_RValue, 5467 const CXXCastPath *BasePath = 0, 5468 CheckedConversionKind CCK 5469 = CCK_ImplicitConversion); 5470 5471 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding 5472 /// to the conversion from scalar type ScalarTy to the Boolean type. 5473 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); 5474 5475 /// IgnoredValueConversions - Given that an expression's result is 5476 /// syntactically ignored, perform any conversions that are 5477 /// required. 5478 ExprResult IgnoredValueConversions(Expr *E); 5479 5480 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts 5481 // functions and arrays to their respective pointers (C99 6.3.2.1). 5482 ExprResult UsualUnaryConversions(Expr *E); 5483 5484 // DefaultFunctionArrayConversion - converts functions and arrays 5485 // to their respective pointers (C99 6.3.2.1). 5486 ExprResult DefaultFunctionArrayConversion(Expr *E); 5487 5488 // DefaultFunctionArrayLvalueConversion - converts functions and 5489 // arrays to their respective pointers and performs the 5490 // lvalue-to-rvalue conversion. 5491 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E); 5492 5493 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on 5494 // the operand. This is DefaultFunctionArrayLvalueConversion, 5495 // except that it assumes the operand isn't of function or array 5496 // type. 5497 ExprResult DefaultLvalueConversion(Expr *E); 5498 5499 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 5500 // do not have a prototype. Integer promotions are performed on each 5501 // argument, and arguments that have type float are promoted to double. 5502 ExprResult DefaultArgumentPromotion(Expr *E); 5503 5504 // Used for emitting the right warning by DefaultVariadicArgumentPromotion 5505 enum VariadicCallType { 5506 VariadicFunction, 5507 VariadicBlock, 5508 VariadicMethod, 5509 VariadicConstructor, 5510 VariadicDoesNotApply 5511 }; 5512 5513 /// GatherArgumentsForCall - Collector argument expressions for various 5514 /// form of call prototypes. 5515 bool GatherArgumentsForCall(SourceLocation CallLoc, 5516 FunctionDecl *FDecl, 5517 const FunctionProtoType *Proto, 5518 unsigned FirstProtoArg, 5519 Expr **Args, unsigned NumArgs, 5520 SmallVector<Expr *, 8> &AllArgs, 5521 VariadicCallType CallType = VariadicDoesNotApply); 5522 5523 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 5524 // will warn if the resulting type is not a POD type. 5525 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 5526 FunctionDecl *FDecl); 5527 5528 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's 5529 // operands and then handles various conversions that are common to binary 5530 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this 5531 // routine returns the first non-arithmetic type found. The client is 5532 // responsible for emitting appropriate error diagnostics. 5533 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 5534 bool IsCompAssign = false); 5535 5536 /// AssignConvertType - All of the 'assignment' semantic checks return this 5537 /// enum to indicate whether the assignment was allowed. These checks are 5538 /// done for simple assignments, as well as initialization, return from 5539 /// function, argument passing, etc. The query is phrased in terms of a 5540 /// source and destination type. 5541 enum AssignConvertType { 5542 /// Compatible - the types are compatible according to the standard. 5543 Compatible, 5544 5545 /// PointerToInt - The assignment converts a pointer to an int, which we 5546 /// accept as an extension. 5547 PointerToInt, 5548 5549 /// IntToPointer - The assignment converts an int to a pointer, which we 5550 /// accept as an extension. 5551 IntToPointer, 5552 5553 /// FunctionVoidPointer - The assignment is between a function pointer and 5554 /// void*, which the standard doesn't allow, but we accept as an extension. 5555 FunctionVoidPointer, 5556 5557 /// IncompatiblePointer - The assignment is between two pointers types that 5558 /// are not compatible, but we accept them as an extension. 5559 IncompatiblePointer, 5560 5561 /// IncompatiblePointer - The assignment is between two pointers types which 5562 /// point to integers which have a different sign, but are otherwise identical. 5563 /// This is a subset of the above, but broken out because it's by far the most 5564 /// common case of incompatible pointers. 5565 IncompatiblePointerSign, 5566 5567 /// CompatiblePointerDiscardsQualifiers - The assignment discards 5568 /// c/v/r qualifiers, which we accept as an extension. 5569 CompatiblePointerDiscardsQualifiers, 5570 5571 /// IncompatiblePointerDiscardsQualifiers - The assignment 5572 /// discards qualifiers that we don't permit to be discarded, 5573 /// like address spaces. 5574 IncompatiblePointerDiscardsQualifiers, 5575 5576 /// IncompatibleNestedPointerQualifiers - The assignment is between two 5577 /// nested pointer types, and the qualifiers other than the first two 5578 /// levels differ e.g. char ** -> const char **, but we accept them as an 5579 /// extension. 5580 IncompatibleNestedPointerQualifiers, 5581 5582 /// IncompatibleVectors - The assignment is between two vector types that 5583 /// have the same size, which we accept as an extension. 5584 IncompatibleVectors, 5585 5586 /// IntToBlockPointer - The assignment converts an int to a block 5587 /// pointer. We disallow this. 5588 IntToBlockPointer, 5589 5590 /// IncompatibleBlockPointer - The assignment is between two block 5591 /// pointers types that are not compatible. 5592 IncompatibleBlockPointer, 5593 5594 /// IncompatibleObjCQualifiedId - The assignment is between a qualified 5595 /// id type and something else (that is incompatible with it). For example, 5596 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. 5597 IncompatibleObjCQualifiedId, 5598 5599 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an 5600 /// object with __weak qualifier. 5601 IncompatibleObjCWeakRef, 5602 5603 /// Incompatible - We reject this conversion outright, it is invalid to 5604 /// represent it in the AST. 5605 Incompatible 5606 }; 5607 5608 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the 5609 /// assignment conversion type specified by ConvTy. This returns true if the 5610 /// conversion was invalid or false if the conversion was accepted. 5611 bool DiagnoseAssignmentResult(AssignConvertType ConvTy, 5612 SourceLocation Loc, 5613 QualType DstType, QualType SrcType, 5614 Expr *SrcExpr, AssignmentAction Action, 5615 bool *Complained = 0); 5616 5617 /// CheckAssignmentConstraints - Perform type checking for assignment, 5618 /// argument passing, variable initialization, and function return values. 5619 /// C99 6.5.16. 5620 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, 5621 QualType LHSType, 5622 QualType RHSType); 5623 5624 /// Check assignment constraints and prepare for a conversion of the 5625 /// RHS to the LHS type. 5626 AssignConvertType CheckAssignmentConstraints(QualType LHSType, 5627 ExprResult &RHS, 5628 CastKind &Kind); 5629 5630 // CheckSingleAssignmentConstraints - Currently used by 5631 // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking, 5632 // this routine performs the default function/array converions. 5633 AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, 5634 ExprResult &RHS, 5635 bool Diagnose = true); 5636 5637 // \brief If the lhs type is a transparent union, check whether we 5638 // can initialize the transparent union with the given expression. 5639 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, 5640 ExprResult &RHS); 5641 5642 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); 5643 5644 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); 5645 5646 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 5647 AssignmentAction Action, 5648 bool AllowExplicit = false, 5649 bool Diagnose = true); 5650 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 5651 AssignmentAction Action, 5652 bool AllowExplicit, 5653 ImplicitConversionSequence& ICS, 5654 bool Diagnose = true); 5655 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 5656 const ImplicitConversionSequence& ICS, 5657 AssignmentAction Action, 5658 CheckedConversionKind CCK 5659 = CCK_ImplicitConversion); 5660 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 5661 const StandardConversionSequence& SCS, 5662 AssignmentAction Action, 5663 CheckedConversionKind CCK); 5664 5665 /// the following "Check" methods will return a valid/converted QualType 5666 /// or a null QualType (indicating an error diagnostic was issued). 5667 5668 /// type checking binary operators (subroutines of CreateBuiltinBinOp). 5669 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, 5670 ExprResult &RHS); 5671 QualType CheckPointerToMemberOperands( // C++ 5.5 5672 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, 5673 SourceLocation OpLoc, bool isIndirect); 5674 QualType CheckMultiplyDivideOperands( // C99 6.5.5 5675 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, 5676 bool IsDivide); 5677 QualType CheckRemainderOperands( // C99 6.5.5 5678 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 5679 bool IsCompAssign = false); 5680 QualType CheckAdditionOperands( // C99 6.5.6 5681 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 5682 QualType* CompLHSTy = 0); 5683 QualType CheckSubtractionOperands( // C99 6.5.6 5684 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 5685 QualType* CompLHSTy = 0); 5686 QualType CheckShiftOperands( // C99 6.5.7 5687 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 5688 bool IsCompAssign = false); 5689 QualType CheckCompareOperands( // C99 6.5.8/9 5690 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc, 5691 bool isRelational); 5692 QualType CheckBitwiseOperands( // C99 6.5.[10...12] 5693 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 5694 bool IsCompAssign = false); 5695 QualType CheckLogicalOperands( // C99 6.5.[13,14] 5696 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc); 5697 // CheckAssignmentOperands is used for both simple and compound assignment. 5698 // For simple assignment, pass both expressions and a null converted type. 5699 // For compound assignment, pass both expressions and the converted type. 5700 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] 5701 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); 5702 5703 void ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, 5704 QualType& LHSTy); 5705 ExprResult ConvertPropertyForRValue(Expr *E); 5706 5707 QualType CheckConditionalOperands( // C99 6.5.15 5708 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, 5709 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); 5710 QualType CXXCheckConditionalOperands( // C++ 5.16 5711 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, 5712 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); 5713 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, 5714 bool *NonStandardCompositeType = 0); 5715 QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2, 5716 bool *NonStandardCompositeType = 0) { 5717 Expr *E1Tmp = E1.take(), *E2Tmp = E2.take(); 5718 QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, NonStandardCompositeType); 5719 E1 = Owned(E1Tmp); 5720 E2 = Owned(E2Tmp); 5721 return Composite; 5722 } 5723 5724 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 5725 SourceLocation QuestionLoc); 5726 5727 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 5728 SourceLocation QuestionLoc); 5729 5730 /// type checking for vector binary operators. 5731 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 5732 SourceLocation Loc, bool IsCompAssign); 5733 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 5734 SourceLocation Loc, bool isRelational); 5735 5736 /// type checking declaration initializers (C99 6.7.8) 5737 bool CheckForConstantInitializer(Expr *e, QualType t); 5738 5739 // type checking C++ declaration initializers (C++ [dcl.init]). 5740 5741 /// ReferenceCompareResult - Expresses the result of comparing two 5742 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the 5743 /// purposes of initialization by reference (C++ [dcl.init.ref]p4). 5744 enum ReferenceCompareResult { 5745 /// Ref_Incompatible - The two types are incompatible, so direct 5746 /// reference binding is not possible. 5747 Ref_Incompatible = 0, 5748 /// Ref_Related - The two types are reference-related, which means 5749 /// that their unqualified forms (T1 and T2) are either the same 5750 /// or T1 is a base class of T2. 5751 Ref_Related, 5752 /// Ref_Compatible_With_Added_Qualification - The two types are 5753 /// reference-compatible with added qualification, meaning that 5754 /// they are reference-compatible and the qualifiers on T1 (cv1) 5755 /// are greater than the qualifiers on T2 (cv2). 5756 Ref_Compatible_With_Added_Qualification, 5757 /// Ref_Compatible - The two types are reference-compatible and 5758 /// have equivalent qualifiers (cv1 == cv2). 5759 Ref_Compatible 5760 }; 5761 5762 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, 5763 QualType T1, QualType T2, 5764 bool &DerivedToBase, 5765 bool &ObjCConversion, 5766 bool &ObjCLifetimeConversion); 5767 5768 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 5769 Expr *CastExpr, CastKind &CastKind, 5770 ExprValueKind &VK, CXXCastPath &Path); 5771 5772 // CheckVectorCast - check type constraints for vectors. 5773 // Since vectors are an extension, there are no C standard reference for this. 5774 // We allow casting between vectors and integer datatypes of the same size. 5775 // returns true if the cast is invalid 5776 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5777 CastKind &Kind); 5778 5779 // CheckExtVectorCast - check type constraints for extended vectors. 5780 // Since vectors are an extension, there are no C standard reference for this. 5781 // We allow casting between vectors and integer datatypes of the same size, 5782 // or vectors and the element type of that vector. 5783 // returns the cast expr 5784 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, 5785 CastKind &Kind); 5786 5787 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, 5788 SourceLocation LParenLoc, 5789 Expr *CastExpr, 5790 SourceLocation RParenLoc); 5791 5792 /// \brief Checks for invalid conversions and casts between 5793 /// retainable pointers and other pointer kinds. 5794 void CheckObjCARCConversion(SourceRange castRange, QualType castType, 5795 Expr *&op, CheckedConversionKind CCK); 5796 5797 bool CheckObjCARCUnavailableWeakConversion(QualType castType, 5798 QualType ExprType); 5799 5800 /// checkRetainCycles - Check whether an Objective-C message send 5801 /// might create an obvious retain cycle. 5802 void checkRetainCycles(ObjCMessageExpr *msg); 5803 void checkRetainCycles(Expr *receiver, Expr *argument); 5804 5805 /// checkUnsafeAssigns - Check whether +1 expr is being assigned 5806 /// to weak/__unsafe_unretained type. 5807 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); 5808 5809 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned 5810 /// to weak/__unsafe_unretained expression. 5811 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); 5812 5813 /// CheckMessageArgumentTypes - Check types in an Obj-C message send. 5814 /// \param Method - May be null. 5815 /// \param [out] ReturnType - The return type of the send. 5816 /// \return true iff there were any incompatible types. 5817 bool CheckMessageArgumentTypes(QualType ReceiverType, 5818 Expr **Args, unsigned NumArgs, Selector Sel, 5819 ObjCMethodDecl *Method, bool isClassMessage, 5820 bool isSuperMessage, 5821 SourceLocation lbrac, SourceLocation rbrac, 5822 QualType &ReturnType, ExprValueKind &VK); 5823 5824 /// \brief Determine the result of a message send expression based on 5825 /// the type of the receiver, the method expected to receive the message, 5826 /// and the form of the message send. 5827 QualType getMessageSendResultType(QualType ReceiverType, 5828 ObjCMethodDecl *Method, 5829 bool isClassMessage, bool isSuperMessage); 5830 5831 /// \brief If the given expression involves a message send to a method 5832 /// with a related result type, emit a note describing what happened. 5833 void EmitRelatedResultTypeNote(const Expr *E); 5834 5835 /// CheckBooleanCondition - Diagnose problems involving the use of 5836 /// the given expression as a boolean condition (e.g. in an if 5837 /// statement). Also performs the standard function and array 5838 /// decays, possibly changing the input variable. 5839 /// 5840 /// \param Loc - A location associated with the condition, e.g. the 5841 /// 'if' keyword. 5842 /// \return true iff there were any errors 5843 ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc); 5844 5845 ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc, 5846 Expr *SubExpr); 5847 5848 /// DiagnoseAssignmentAsCondition - Given that an expression is 5849 /// being used as a boolean condition, warn if it's an assignment. 5850 void DiagnoseAssignmentAsCondition(Expr *E); 5851 5852 /// \brief Redundant parentheses over an equality comparison can indicate 5853 /// that the user intended an assignment used as condition. 5854 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); 5855 5856 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. 5857 ExprResult CheckCXXBooleanCondition(Expr *CondExpr); 5858 5859 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 5860 /// the specified width and sign. If an overflow occurs, detect it and emit 5861 /// the specified diagnostic. 5862 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, 5863 unsigned NewWidth, bool NewSign, 5864 SourceLocation Loc, unsigned DiagID); 5865 5866 /// Checks that the Objective-C declaration is declared in the global scope. 5867 /// Emits an error and marks the declaration as invalid if it's not declared 5868 /// in the global scope. 5869 bool CheckObjCDeclScope(Decl *D); 5870 5871 /// VerifyIntegerConstantExpression - verifies that an expression is an ICE, 5872 /// and reports the appropriate diagnostics. Returns false on success. 5873 /// Can optionally return the value of the expression. 5874 bool VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result = 0); 5875 5876 /// VerifyBitField - verifies that a bit field expression is an ICE and has 5877 /// the correct width, and that the field type is valid. 5878 /// Returns false on success. 5879 /// Can optionally return whether the bit-field is of width 0 5880 bool VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 5881 QualType FieldTy, const Expr *BitWidth, 5882 bool *ZeroWidth = 0); 5883 5884 enum CUDAFunctionTarget { 5885 CFT_Device, 5886 CFT_Global, 5887 CFT_Host, 5888 CFT_HostDevice 5889 }; 5890 5891 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D); 5892 5893 bool CheckCUDATarget(CUDAFunctionTarget CallerTarget, 5894 CUDAFunctionTarget CalleeTarget); 5895 5896 bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee) { 5897 return CheckCUDATarget(IdentifyCUDATarget(Caller), 5898 IdentifyCUDATarget(Callee)); 5899 } 5900 5901 /// \name Code completion 5902 //@{ 5903 /// \brief Describes the context in which code completion occurs. 5904 enum ParserCompletionContext { 5905 /// \brief Code completion occurs at top-level or namespace context. 5906 PCC_Namespace, 5907 /// \brief Code completion occurs within a class, struct, or union. 5908 PCC_Class, 5909 /// \brief Code completion occurs within an Objective-C interface, protocol, 5910 /// or category. 5911 PCC_ObjCInterface, 5912 /// \brief Code completion occurs within an Objective-C implementation or 5913 /// category implementation 5914 PCC_ObjCImplementation, 5915 /// \brief Code completion occurs within the list of instance variables 5916 /// in an Objective-C interface, protocol, category, or implementation. 5917 PCC_ObjCInstanceVariableList, 5918 /// \brief Code completion occurs following one or more template 5919 /// headers. 5920 PCC_Template, 5921 /// \brief Code completion occurs following one or more template 5922 /// headers within a class. 5923 PCC_MemberTemplate, 5924 /// \brief Code completion occurs within an expression. 5925 PCC_Expression, 5926 /// \brief Code completion occurs within a statement, which may 5927 /// also be an expression or a declaration. 5928 PCC_Statement, 5929 /// \brief Code completion occurs at the beginning of the 5930 /// initialization statement (or expression) in a for loop. 5931 PCC_ForInit, 5932 /// \brief Code completion occurs within the condition of an if, 5933 /// while, switch, or for statement. 5934 PCC_Condition, 5935 /// \brief Code completion occurs within the body of a function on a 5936 /// recovery path, where we do not have a specific handle on our position 5937 /// in the grammar. 5938 PCC_RecoveryInFunction, 5939 /// \brief Code completion occurs where only a type is permitted. 5940 PCC_Type, 5941 /// \brief Code completion occurs in a parenthesized expression, which 5942 /// might also be a type cast. 5943 PCC_ParenthesizedExpression, 5944 /// \brief Code completion occurs within a sequence of declaration 5945 /// specifiers within a function, method, or block. 5946 PCC_LocalDeclarationSpecifiers 5947 }; 5948 5949 void CodeCompleteOrdinaryName(Scope *S, 5950 ParserCompletionContext CompletionContext); 5951 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, 5952 bool AllowNonIdentifiers, 5953 bool AllowNestedNameSpecifiers); 5954 5955 struct CodeCompleteExpressionData; 5956 void CodeCompleteExpression(Scope *S, 5957 const CodeCompleteExpressionData &Data); 5958 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, 5959 SourceLocation OpLoc, 5960 bool IsArrow); 5961 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS); 5962 void CodeCompleteTag(Scope *S, unsigned TagSpec); 5963 void CodeCompleteTypeQualifiers(DeclSpec &DS); 5964 void CodeCompleteCase(Scope *S); 5965 void CodeCompleteCall(Scope *S, Expr *Fn, Expr **Args, unsigned NumArgs); 5966 void CodeCompleteInitializer(Scope *S, Decl *D); 5967 void CodeCompleteReturn(Scope *S); 5968 void CodeCompleteAfterIf(Scope *S); 5969 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS); 5970 5971 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, 5972 bool EnteringContext); 5973 void CodeCompleteUsing(Scope *S); 5974 void CodeCompleteUsingDirective(Scope *S); 5975 void CodeCompleteNamespaceDecl(Scope *S); 5976 void CodeCompleteNamespaceAliasDecl(Scope *S); 5977 void CodeCompleteOperatorName(Scope *S); 5978 void CodeCompleteConstructorInitializer(Decl *Constructor, 5979 CXXCtorInitializer** Initializers, 5980 unsigned NumInitializers); 5981 5982 void CodeCompleteObjCAtDirective(Scope *S); 5983 void CodeCompleteObjCAtVisibility(Scope *S); 5984 void CodeCompleteObjCAtStatement(Scope *S); 5985 void CodeCompleteObjCAtExpression(Scope *S); 5986 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); 5987 void CodeCompleteObjCPropertyGetter(Scope *S); 5988 void CodeCompleteObjCPropertySetter(Scope *S); 5989 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, 5990 bool IsParameter); 5991 void CodeCompleteObjCMessageReceiver(Scope *S); 5992 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, 5993 IdentifierInfo **SelIdents, 5994 unsigned NumSelIdents, 5995 bool AtArgumentExpression); 5996 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, 5997 IdentifierInfo **SelIdents, 5998 unsigned NumSelIdents, 5999 bool AtArgumentExpression, 6000 bool IsSuper = false); 6001 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, 6002 IdentifierInfo **SelIdents, 6003 unsigned NumSelIdents, 6004 bool AtArgumentExpression, 6005 ObjCInterfaceDecl *Super = 0); 6006 void CodeCompleteObjCForCollection(Scope *S, 6007 DeclGroupPtrTy IterationVar); 6008 void CodeCompleteObjCSelector(Scope *S, 6009 IdentifierInfo **SelIdents, 6010 unsigned NumSelIdents); 6011 void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols, 6012 unsigned NumProtocols); 6013 void CodeCompleteObjCProtocolDecl(Scope *S); 6014 void CodeCompleteObjCInterfaceDecl(Scope *S); 6015 void CodeCompleteObjCSuperclass(Scope *S, 6016 IdentifierInfo *ClassName, 6017 SourceLocation ClassNameLoc); 6018 void CodeCompleteObjCImplementationDecl(Scope *S); 6019 void CodeCompleteObjCInterfaceCategory(Scope *S, 6020 IdentifierInfo *ClassName, 6021 SourceLocation ClassNameLoc); 6022 void CodeCompleteObjCImplementationCategory(Scope *S, 6023 IdentifierInfo *ClassName, 6024 SourceLocation ClassNameLoc); 6025 void CodeCompleteObjCPropertyDefinition(Scope *S); 6026 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, 6027 IdentifierInfo *PropertyName); 6028 void CodeCompleteObjCMethodDecl(Scope *S, 6029 bool IsInstanceMethod, 6030 ParsedType ReturnType); 6031 void CodeCompleteObjCMethodDeclSelector(Scope *S, 6032 bool IsInstanceMethod, 6033 bool AtParameterName, 6034 ParsedType ReturnType, 6035 IdentifierInfo **SelIdents, 6036 unsigned NumSelIdents); 6037 void CodeCompletePreprocessorDirective(bool InConditional); 6038 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); 6039 void CodeCompletePreprocessorMacroName(bool IsDefinition); 6040 void CodeCompletePreprocessorExpression(); 6041 void CodeCompletePreprocessorMacroArgument(Scope *S, 6042 IdentifierInfo *Macro, 6043 MacroInfo *MacroInfo, 6044 unsigned Argument); 6045 void CodeCompleteNaturalLanguage(); 6046 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, 6047 SmallVectorImpl<CodeCompletionResult> &Results); 6048 //@} 6049 6050 //===--------------------------------------------------------------------===// 6051 // Extra semantic analysis beyond the C type system 6052 6053public: 6054 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, 6055 unsigned ByteNo) const; 6056 6057private: 6058 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 6059 bool isSubscript=false, bool AllowOnePastEnd=true); 6060 void CheckArrayAccess(const Expr *E); 6061 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall); 6062 bool CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall); 6063 6064 bool CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall); 6065 bool CheckObjCString(Expr *Arg); 6066 6067 ExprResult CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 6068 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 6069 6070 bool SemaBuiltinVAStart(CallExpr *TheCall); 6071 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); 6072 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); 6073 6074public: 6075 // Used by C++ template instantiation. 6076 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); 6077 6078private: 6079 bool SemaBuiltinPrefetch(CallExpr *TheCall); 6080 bool SemaBuiltinObjectSize(CallExpr *TheCall); 6081 bool SemaBuiltinLongjmp(CallExpr *TheCall); 6082 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); 6083 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, 6084 AtomicExpr::AtomicOp Op); 6085 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6086 llvm::APSInt &Result); 6087 6088 bool SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall, 6089 bool HasVAListArg, unsigned format_idx, 6090 unsigned firstDataArg, bool isPrintf); 6091 6092 void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr, 6093 const CallExpr *TheCall, bool HasVAListArg, 6094 unsigned format_idx, unsigned firstDataArg, 6095 bool isPrintf); 6096 6097 void CheckNonNullArguments(const NonNullAttr *NonNull, 6098 const Expr * const *ExprArgs, 6099 SourceLocation CallSiteLoc); 6100 6101 void CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg, 6102 unsigned format_idx, unsigned firstDataArg, 6103 bool isPrintf); 6104 6105 /// \brief Enumeration used to describe which of the memory setting or copying 6106 /// functions is being checked by \c CheckMemaccessArguments(). 6107 enum CheckedMemoryFunction { 6108 CMF_Memset, 6109 CMF_Memcpy, 6110 CMF_Memmove, 6111 CMF_Memcmp 6112 }; 6113 6114 void CheckMemaccessArguments(const CallExpr *Call, CheckedMemoryFunction CMF, 6115 IdentifierInfo *FnName); 6116 6117 void CheckStrlcpycatArguments(const CallExpr *Call, 6118 IdentifierInfo *FnName); 6119 6120 void CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, 6121 SourceLocation ReturnLoc); 6122 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS); 6123 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); 6124 6125 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, 6126 Expr *Init); 6127 6128 /// \brief The parser's current scope. 6129 /// 6130 /// The parser maintains this state here. 6131 Scope *CurScope; 6132 6133protected: 6134 friend class Parser; 6135 friend class InitializationSequence; 6136 friend class ASTReader; 6137 friend class ASTWriter; 6138 6139public: 6140 /// \brief Retrieve the parser's current scope. 6141 /// 6142 /// This routine must only be used when it is certain that semantic analysis 6143 /// and the parser are in precisely the same context, which is not the case 6144 /// when, e.g., we are performing any kind of template instantiation. 6145 /// Therefore, the only safe places to use this scope are in the parser 6146 /// itself and in routines directly invoked from the parser and *never* from 6147 /// template substitution or instantiation. 6148 Scope *getCurScope() const { return CurScope; } 6149 6150 Decl *getObjCDeclContext() const; 6151 6152 DeclContext *getCurLexicalContext() const { 6153 return OriginalLexicalContext ? OriginalLexicalContext : CurContext; 6154 } 6155 6156 AvailabilityResult getCurContextAvailability() const; 6157}; 6158 6159/// \brief RAII object that enters a new expression evaluation context. 6160class EnterExpressionEvaluationContext { 6161 Sema &Actions; 6162 6163public: 6164 EnterExpressionEvaluationContext(Sema &Actions, 6165 Sema::ExpressionEvaluationContext NewContext) 6166 : Actions(Actions) { 6167 Actions.PushExpressionEvaluationContext(NewContext); 6168 } 6169 6170 ~EnterExpressionEvaluationContext() { 6171 Actions.PopExpressionEvaluationContext(); 6172 } 6173}; 6174 6175} // end namespace clang 6176 6177#endif 6178