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