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