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