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