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