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