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