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