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