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