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