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