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