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