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