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