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