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