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