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