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