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