1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the Sema class, which performs semantic analysis and
11// builds ASTs.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_SEMA_SEMA_H
16#define LLVM_CLANG_SEMA_SEMA_H
17
18#include "clang/AST/Attr.h"
19#include "clang/AST/Availability.h"
20#include "clang/AST/DeclarationName.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprObjC.h"
24#include "clang/AST/ExternalASTSource.h"
25#include "clang/AST/LocInfoType.h"
26#include "clang/AST/MangleNumberingContext.h"
27#include "clang/AST/NSAPI.h"
28#include "clang/AST/PrettyPrinter.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/TypeLoc.h"
31#include "clang/AST/TypeOrdering.h"
32#include "clang/Basic/ExpressionTraits.h"
33#include "clang/Basic/LangOptions.h"
34#include "clang/Basic/Module.h"
35#include "clang/Basic/OpenMPKinds.h"
36#include "clang/Basic/PragmaKinds.h"
37#include "clang/Basic/Specifiers.h"
38#include "clang/Basic/TemplateKinds.h"
39#include "clang/Basic/TypeTraits.h"
40#include "clang/Sema/AnalysisBasedWarnings.h"
41#include "clang/Sema/CleanupInfo.h"
42#include "clang/Sema/DeclSpec.h"
43#include "clang/Sema/ExternalSemaSource.h"
44#include "clang/Sema/IdentifierResolver.h"
45#include "clang/Sema/ObjCMethodList.h"
46#include "clang/Sema/Ownership.h"
47#include "clang/Sema/Scope.h"
48#include "clang/Sema/ScopeInfo.h"
49#include "clang/Sema/TypoCorrection.h"
50#include "clang/Sema/Weak.h"
51#include "llvm/ADT/ArrayRef.h"
52#include "llvm/ADT/Optional.h"
53#include "llvm/ADT/SetVector.h"
54#include "llvm/ADT/SmallPtrSet.h"
55#include "llvm/ADT/SmallVector.h"
56#include "llvm/ADT/TinyPtrVector.h"
57#include <deque>
58#include <memory>
59#include <string>
60#include <vector>
61
62namespace llvm {
63  class APSInt;
64  template <typename ValueT> struct DenseMapInfo;
65  template <typename ValueT, typename ValueInfoT> class DenseSet;
66  class SmallBitVector;
67  class InlineAsmIdentifierInfo;
68}
69
70namespace clang {
71  class ADLResult;
72  class ASTConsumer;
73  class ASTContext;
74  class ASTMutationListener;
75  class ASTReader;
76  class ASTWriter;
77  class ArrayType;
78  class AttributeList;
79  class BindingDecl;
80  class BlockDecl;
81  class CapturedDecl;
82  class CXXBasePath;
83  class CXXBasePaths;
84  class CXXBindTemporaryExpr;
85  typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
86  class CXXConstructorDecl;
87  class CXXConversionDecl;
88  class CXXDeleteExpr;
89  class CXXDestructorDecl;
90  class CXXFieldCollector;
91  class CXXMemberCallExpr;
92  class CXXMethodDecl;
93  class CXXScopeSpec;
94  class CXXTemporary;
95  class CXXTryStmt;
96  class CallExpr;
97  class ClassTemplateDecl;
98  class ClassTemplatePartialSpecializationDecl;
99  class ClassTemplateSpecializationDecl;
100  class VarTemplatePartialSpecializationDecl;
101  class CodeCompleteConsumer;
102  class CodeCompletionAllocator;
103  class CodeCompletionTUInfo;
104  class CodeCompletionResult;
105  class CoroutineBodyStmt;
106  class Decl;
107  class DeclAccessPair;
108  class DeclContext;
109  class DeclRefExpr;
110  class DeclaratorDecl;
111  class DeducedTemplateArgument;
112  class DependentDiagnostic;
113  class DesignatedInitExpr;
114  class Designation;
115  class EnableIfAttr;
116  class EnumConstantDecl;
117  class Expr;
118  class ExtVectorType;
119  class FormatAttr;
120  class FriendDecl;
121  class FunctionDecl;
122  class FunctionProtoType;
123  class FunctionTemplateDecl;
124  class ImplicitConversionSequence;
125  typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
126  class InitListExpr;
127  class InitializationKind;
128  class InitializationSequence;
129  class InitializedEntity;
130  class IntegerLiteral;
131  class LabelStmt;
132  class LambdaExpr;
133  class LangOptions;
134  class LocalInstantiationScope;
135  class LookupResult;
136  class MacroInfo;
137  typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
138  class ModuleLoader;
139  class MultiLevelTemplateArgumentList;
140  class NamedDecl;
141  class ObjCCategoryDecl;
142  class ObjCCategoryImplDecl;
143  class ObjCCompatibleAliasDecl;
144  class ObjCContainerDecl;
145  class ObjCImplDecl;
146  class ObjCImplementationDecl;
147  class ObjCInterfaceDecl;
148  class ObjCIvarDecl;
149  template <class T> class ObjCList;
150  class ObjCMessageExpr;
151  class ObjCMethodDecl;
152  class ObjCPropertyDecl;
153  class ObjCProtocolDecl;
154  class OMPThreadPrivateDecl;
155  class OMPDeclareReductionDecl;
156  class OMPDeclareSimdDecl;
157  class OMPClause;
158  struct OverloadCandidate;
159  class OverloadCandidateSet;
160  class OverloadExpr;
161  class ParenListExpr;
162  class ParmVarDecl;
163  class Preprocessor;
164  class PseudoDestructorTypeStorage;
165  class PseudoObjectExpr;
166  class QualType;
167  class StandardConversionSequence;
168  class Stmt;
169  class StringLiteral;
170  class SwitchStmt;
171  class TemplateArgument;
172  class TemplateArgumentList;
173  class TemplateArgumentLoc;
174  class TemplateDecl;
175  class TemplateParameterList;
176  class TemplatePartialOrderingContext;
177  class TemplateTemplateParmDecl;
178  class Token;
179  class TypeAliasDecl;
180  class TypedefDecl;
181  class TypedefNameDecl;
182  class TypeLoc;
183  class TypoCorrectionConsumer;
184  class UnqualifiedId;
185  class UnresolvedLookupExpr;
186  class UnresolvedMemberExpr;
187  class UnresolvedSetImpl;
188  class UnresolvedSetIterator;
189  class UsingDecl;
190  class UsingShadowDecl;
191  class ValueDecl;
192  class VarDecl;
193  class VarTemplateSpecializationDecl;
194  class VisibilityAttr;
195  class VisibleDeclConsumer;
196  class IndirectFieldDecl;
197  struct DeductionFailureInfo;
198  class TemplateSpecCandidateSet;
199
200namespace sema {
201  class AccessedEntity;
202  class BlockScopeInfo;
203  class CapturedRegionScopeInfo;
204  class CapturingScopeInfo;
205  class CompoundScopeInfo;
206  class DelayedDiagnostic;
207  class DelayedDiagnosticPool;
208  class FunctionScopeInfo;
209  class LambdaScopeInfo;
210  class PossiblyUnreachableDiag;
211  class TemplateDeductionInfo;
212}
213
214namespace threadSafety {
215  class BeforeSet;
216  void threadSafetyCleanup(BeforeSet* Cache);
217}
218
219// FIXME: No way to easily map from TemplateTypeParmTypes to
220// TemplateTypeParmDecls, so we have this horrible PointerUnion.
221typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
222                  SourceLocation> UnexpandedParameterPack;
223
224/// Describes whether we've seen any nullability information for the given
225/// file.
226struct FileNullability {
227  /// The first pointer declarator (of any pointer kind) in the file that does
228  /// not have a corresponding nullability annotation.
229  SourceLocation PointerLoc;
230
231  /// Which kind of pointer declarator we saw.
232  uint8_t PointerKind;
233
234  /// Whether we saw any type nullability annotations in the given file.
235  bool SawTypeNullability = false;
236};
237
238/// A mapping from file IDs to a record of whether we've seen nullability
239/// information in that file.
240class FileNullabilityMap {
241  /// A mapping from file IDs to the nullability information for each file ID.
242  llvm::DenseMap<FileID, FileNullability> Map;
243
244  /// A single-element cache based on the file ID.
245  struct {
246    FileID File;
247    FileNullability Nullability;
248  } Cache;
249
250public:
251  FileNullability &operator[](FileID file) {
252    // Check the single-element cache.
253    if (file == Cache.File)
254      return Cache.Nullability;
255
256    // It's not in the single-element cache; flush the cache if we have one.
257    if (!Cache.File.isInvalid()) {
258      Map[Cache.File] = Cache.Nullability;
259    }
260
261    // Pull this entry into the cache.
262    Cache.File = file;
263    Cache.Nullability = Map[file];
264    return Cache.Nullability;
265  }
266};
267
268/// Sema - This implements semantic analysis and AST building for C.
269class Sema {
270  Sema(const Sema &) = delete;
271  void operator=(const Sema &) = delete;
272
273  ///\brief Source of additional semantic information.
274  ExternalSemaSource *ExternalSource;
275
276  ///\brief Whether Sema has generated a multiplexer and has to delete it.
277  bool isMultiplexExternalSource;
278
279  static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
280
281  bool isVisibleSlow(const NamedDecl *D);
282
283  bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
284                                    const NamedDecl *New) {
285    // We are about to link these. It is now safe to compute the linkage of
286    // the new decl. If the new decl has external linkage, we will
287    // link it with the hidden decl (which also has external linkage) and
288    // it will keep having external linkage. If it has internal linkage, we
289    // will not link it. Since it has no previous decls, it will remain
290    // with internal linkage.
291    return isVisible(Old) || New->isExternallyVisible();
292  }
293  bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
294
295public:
296  typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
297  typedef OpaquePtr<TemplateName> TemplateTy;
298  typedef OpaquePtr<QualType> TypeTy;
299
300  OpenCLOptions OpenCLFeatures;
301  FPOptions FPFeatures;
302
303  const LangOptions &LangOpts;
304  Preprocessor &PP;
305  ASTContext &Context;
306  ASTConsumer &Consumer;
307  DiagnosticsEngine &Diags;
308  SourceManager &SourceMgr;
309
310  /// \brief Flag indicating whether or not to collect detailed statistics.
311  bool CollectStats;
312
313  /// \brief Code-completion consumer.
314  CodeCompleteConsumer *CodeCompleter;
315
316  /// CurContext - This is the current declaration context of parsing.
317  DeclContext *CurContext;
318
319  /// \brief Generally null except when we temporarily switch decl contexts,
320  /// like in \see ActOnObjCTemporaryExitContainerContext.
321  DeclContext *OriginalLexicalContext;
322
323  /// VAListTagName - The declaration name corresponding to __va_list_tag.
324  /// This is used as part of a hack to omit that class from ADL results.
325  DeclarationName VAListTagName;
326
327  bool MSStructPragmaOn; // True when \#pragma ms_struct on
328
329  /// \brief Controls member pointer representation format under the MS ABI.
330  LangOptions::PragmaMSPointersToMembersKind
331      MSPointerToMemberRepresentationMethod;
332
333  /// Stack of active SEH __finally scopes.  Can be empty.
334  SmallVector<Scope*, 2> CurrentSEHFinally;
335
336  /// \brief Source location for newly created implicit MSInheritanceAttrs
337  SourceLocation ImplicitMSInheritanceAttrLoc;
338
339  enum PragmaMsStackAction {
340    PSK_Reset     = 0x0,                // #pragma ()
341    PSK_Set       = 0x1,                // #pragma (value)
342    PSK_Push      = 0x2,                // #pragma (push[, id])
343    PSK_Pop       = 0x4,                // #pragma (pop[, id])
344    PSK_Show      = 0x8,                // #pragma (show) -- only for "pack"!
345    PSK_Push_Set  = PSK_Push | PSK_Set, // #pragma (push[, id], value)
346    PSK_Pop_Set   = PSK_Pop | PSK_Set,  // #pragma (pop[, id], value)
347  };
348
349  template<typename ValueType>
350  struct PragmaStack {
351    struct Slot {
352      llvm::StringRef StackSlotLabel;
353      ValueType Value;
354      SourceLocation PragmaLocation;
355      Slot(llvm::StringRef StackSlotLabel,
356           ValueType Value,
357           SourceLocation PragmaLocation)
358        : StackSlotLabel(StackSlotLabel), Value(Value),
359          PragmaLocation(PragmaLocation) {}
360    };
361    void Act(SourceLocation PragmaLocation,
362             PragmaMsStackAction Action,
363             llvm::StringRef StackSlotLabel,
364             ValueType Value);
365
366    // MSVC seems to add artificial slots to #pragma stacks on entering a C++
367    // method body to restore the stacks on exit, so it works like this:
368    //
369    //   struct S {
370    //     #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
371    //     void Method {}
372    //     #pragma <name>(pop, InternalPragmaSlot)
373    //   };
374    //
375    // It works even with #pragma vtordisp, although MSVC doesn't support
376    //   #pragma vtordisp(push [, id], n)
377    // syntax.
378    //
379    // Push / pop a named sentinel slot.
380    void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
381      assert((Action == PSK_Push || Action == PSK_Pop) &&
382             "Can only push / pop #pragma stack sentinels!");
383      Act(CurrentPragmaLocation, Action, Label, CurrentValue);
384    }
385
386    // Constructors.
387    explicit PragmaStack(const ValueType &Default)
388        : DefaultValue(Default), CurrentValue(Default) {}
389
390    SmallVector<Slot, 2> Stack;
391    ValueType DefaultValue; // Value used for PSK_Reset action.
392    ValueType CurrentValue;
393    SourceLocation CurrentPragmaLocation;
394  };
395  // FIXME: We should serialize / deserialize these if they occur in a PCH (but
396  // we shouldn't do so if they're in a module).
397
398  /// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft
399  /// C++ ABI.  Possible values are 0, 1, and 2, which mean:
400  ///
401  /// 0: Suppress all vtordisps
402  /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
403  ///    structors
404  /// 2: Always insert vtordisps to support RTTI on partially constructed
405  ///    objects
406  PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
407  // #pragma pack.
408  // Sentinel to represent when the stack is set to mac68k alignment.
409  static const unsigned kMac68kAlignmentSentinel = ~0U;
410  PragmaStack<unsigned> PackStack;
411  // Segment #pragmas.
412  PragmaStack<StringLiteral *> DataSegStack;
413  PragmaStack<StringLiteral *> BSSSegStack;
414  PragmaStack<StringLiteral *> ConstSegStack;
415  PragmaStack<StringLiteral *> CodeSegStack;
416
417  // RAII object to push / pop sentinel slots for all MS #pragma stacks.
418  // Actions should be performed only if we enter / exit a C++ method body.
419  class PragmaStackSentinelRAII {
420  public:
421    PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
422    ~PragmaStackSentinelRAII();
423
424  private:
425    Sema &S;
426    StringRef SlotLabel;
427    bool ShouldAct;
428  };
429
430  /// A mapping that describes the nullability we've seen in each header file.
431  FileNullabilityMap NullabilityMap;
432
433  /// Last section used with #pragma init_seg.
434  StringLiteral *CurInitSeg;
435  SourceLocation CurInitSegLoc;
436
437  /// VisContext - Manages the stack for \#pragma GCC visibility.
438  void *VisContext; // Really a "PragmaVisStack*"
439
440  /// \brief This represents the last location of a "#pragma clang optimize off"
441  /// directive if such a directive has not been closed by an "on" yet. If
442  /// optimizations are currently "on", this is set to an invalid location.
443  SourceLocation OptimizeOffPragmaLocation;
444
445  /// \brief Flag indicating if Sema is building a recovery call expression.
446  ///
447  /// This flag is used to avoid building recovery call expressions
448  /// if Sema is already doing so, which would cause infinite recursions.
449  bool IsBuildingRecoveryCallExpr;
450
451  /// Used to control the generation of ExprWithCleanups.
452  CleanupInfo Cleanup;
453
454  /// ExprCleanupObjects - This is the stack of objects requiring
455  /// cleanup that are created by the current full expression.  The
456  /// element type here is ExprWithCleanups::Object.
457  SmallVector<BlockDecl*, 8> ExprCleanupObjects;
458
459  /// \brief Store a list of either DeclRefExprs or MemberExprs
460  ///  that contain a reference to a variable (constant) that may or may not
461  ///  be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
462  ///  and discarded value conversions have been applied to all subexpressions
463  ///  of the enclosing full expression.  This is cleared at the end of each
464  ///  full expression.
465  llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
466
467  /// \brief Stack containing information about each of the nested
468  /// function, block, and method scopes that are currently active.
469  ///
470  /// This array is never empty.  Clients should ignore the first
471  /// element, which is used to cache a single FunctionScopeInfo
472  /// that's used to parse every top-level function.
473  SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
474
475  typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
476                     &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
477    ExtVectorDeclsType;
478
479  /// ExtVectorDecls - This is a list all the extended vector types. This allows
480  /// us to associate a raw vector type with one of the ext_vector type names.
481  /// This is only necessary for issuing pretty diagnostics.
482  ExtVectorDeclsType ExtVectorDecls;
483
484  /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
485  std::unique_ptr<CXXFieldCollector> FieldCollector;
486
487  typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
488
489  /// \brief Set containing all declared private fields that are not used.
490  NamedDeclSetType UnusedPrivateFields;
491
492  /// \brief Set containing all typedefs that are likely unused.
493  llvm::SmallSetVector<const TypedefNameDecl *, 4>
494      UnusedLocalTypedefNameCandidates;
495
496  /// \brief Delete-expressions to be analyzed at the end of translation unit
497  ///
498  /// This list contains class members, and locations of delete-expressions
499  /// that could not be proven as to whether they mismatch with new-expression
500  /// used in initializer of the field.
501  typedef std::pair<SourceLocation, bool> DeleteExprLoc;
502  typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
503  llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
504
505  typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
506
507  /// PureVirtualClassDiagSet - a set of class declarations which we have
508  /// emitted a list of pure virtual functions. Used to prevent emitting the
509  /// same list more than once.
510  std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
511
512  /// ParsingInitForAutoVars - a set of declarations with auto types for which
513  /// we are currently parsing the initializer.
514  llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
515
516  /// \brief Look for a locally scoped extern "C" declaration by the given name.
517  NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
518
519  typedef LazyVector<VarDecl *, ExternalSemaSource,
520                     &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
521    TentativeDefinitionsType;
522
523  /// \brief All the tentative definitions encountered in the TU.
524  TentativeDefinitionsType TentativeDefinitions;
525
526  typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
527                     &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
528    UnusedFileScopedDeclsType;
529
530  /// \brief The set of file scoped decls seen so far that have not been used
531  /// and must warn if not used. Only contains the first declaration.
532  UnusedFileScopedDeclsType UnusedFileScopedDecls;
533
534  typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
535                     &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
536    DelegatingCtorDeclsType;
537
538  /// \brief All the delegating constructors seen so far in the file, used for
539  /// cycle detection at the end of the TU.
540  DelegatingCtorDeclsType DelegatingCtorDecls;
541
542  /// \brief All the overriding functions seen during a class definition
543  /// that had their exception spec checks delayed, plus the overridden
544  /// function.
545  SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
546    DelayedExceptionSpecChecks;
547
548  /// \brief All the members seen during a class definition which were both
549  /// explicitly defaulted and had explicitly-specified exception
550  /// specifications, along with the function type containing their
551  /// user-specified exception specification. Those exception specifications
552  /// were overridden with the default specifications, but we still need to
553  /// check whether they are compatible with the default specification, and
554  /// we can't do that until the nesting set of class definitions is complete.
555  SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
556    DelayedDefaultedMemberExceptionSpecs;
557
558  typedef llvm::MapVector<const FunctionDecl *,
559                          std::unique_ptr<LateParsedTemplate>>
560      LateParsedTemplateMapT;
561  LateParsedTemplateMapT LateParsedTemplateMap;
562
563  /// \brief Callback to the parser to parse templated functions when needed.
564  typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
565  typedef void LateTemplateParserCleanupCB(void *P);
566  LateTemplateParserCB *LateTemplateParser;
567  LateTemplateParserCleanupCB *LateTemplateParserCleanup;
568  void *OpaqueParser;
569
570  void SetLateTemplateParser(LateTemplateParserCB *LTP,
571                             LateTemplateParserCleanupCB *LTPCleanup,
572                             void *P) {
573    LateTemplateParser = LTP;
574    LateTemplateParserCleanup = LTPCleanup;
575    OpaqueParser = P;
576  }
577
578  class DelayedDiagnostics;
579
580  class DelayedDiagnosticsState {
581    sema::DelayedDiagnosticPool *SavedPool;
582    friend class Sema::DelayedDiagnostics;
583  };
584  typedef DelayedDiagnosticsState ParsingDeclState;
585  typedef DelayedDiagnosticsState ProcessingContextState;
586
587  /// A class which encapsulates the logic for delaying diagnostics
588  /// during parsing and other processing.
589  class DelayedDiagnostics {
590    /// \brief The current pool of diagnostics into which delayed
591    /// diagnostics should go.
592    sema::DelayedDiagnosticPool *CurPool;
593
594  public:
595    DelayedDiagnostics() : CurPool(nullptr) {}
596
597    /// Adds a delayed diagnostic.
598    void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
599
600    /// Determines whether diagnostics should be delayed.
601    bool shouldDelayDiagnostics() { return CurPool != nullptr; }
602
603    /// Returns the current delayed-diagnostics pool.
604    sema::DelayedDiagnosticPool *getCurrentPool() const {
605      return CurPool;
606    }
607
608    /// Enter a new scope.  Access and deprecation diagnostics will be
609    /// collected in this pool.
610    DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
611      DelayedDiagnosticsState state;
612      state.SavedPool = CurPool;
613      CurPool = &pool;
614      return state;
615    }
616
617    /// Leave a delayed-diagnostic state that was previously pushed.
618    /// Do not emit any of the diagnostics.  This is performed as part
619    /// of the bookkeeping of popping a pool "properly".
620    void popWithoutEmitting(DelayedDiagnosticsState state) {
621      CurPool = state.SavedPool;
622    }
623
624    /// Enter a new scope where access and deprecation diagnostics are
625    /// not delayed.
626    DelayedDiagnosticsState pushUndelayed() {
627      DelayedDiagnosticsState state;
628      state.SavedPool = CurPool;
629      CurPool = nullptr;
630      return state;
631    }
632
633    /// Undo a previous pushUndelayed().
634    void popUndelayed(DelayedDiagnosticsState state) {
635      assert(CurPool == nullptr);
636      CurPool = state.SavedPool;
637    }
638  } DelayedDiagnostics;
639
640  /// A RAII object to temporarily push a declaration context.
641  class ContextRAII {
642  private:
643    Sema &S;
644    DeclContext *SavedContext;
645    ProcessingContextState SavedContextState;
646    QualType SavedCXXThisTypeOverride;
647
648  public:
649    ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
650      : S(S), SavedContext(S.CurContext),
651        SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
652        SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
653    {
654      assert(ContextToPush && "pushing null context");
655      S.CurContext = ContextToPush;
656      if (NewThisContext)
657        S.CXXThisTypeOverride = QualType();
658    }
659
660    void pop() {
661      if (!SavedContext) return;
662      S.CurContext = SavedContext;
663      S.DelayedDiagnostics.popUndelayed(SavedContextState);
664      S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
665      SavedContext = nullptr;
666    }
667
668    ~ContextRAII() {
669      pop();
670    }
671  };
672
673  /// \brief RAII object to handle the state changes required to synthesize
674  /// a function body.
675  class SynthesizedFunctionScope {
676    Sema &S;
677    Sema::ContextRAII SavedContext;
678
679  public:
680    SynthesizedFunctionScope(Sema &S, DeclContext *DC)
681      : S(S), SavedContext(S, DC)
682    {
683      S.PushFunctionScope();
684      S.PushExpressionEvaluationContext(
685          Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
686    }
687
688    ~SynthesizedFunctionScope() {
689      S.PopExpressionEvaluationContext();
690      S.PopFunctionScopeInfo();
691    }
692  };
693
694  /// WeakUndeclaredIdentifiers - Identifiers contained in
695  /// \#pragma weak before declared. rare. may alias another
696  /// identifier, declared or undeclared
697  llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
698
699  /// ExtnameUndeclaredIdentifiers - Identifiers contained in
700  /// \#pragma redefine_extname before declared.  Used in Solaris system headers
701  /// to define functions that occur in multiple standards to call the version
702  /// in the currently selected standard.
703  llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
704
705
706  /// \brief Load weak undeclared identifiers from the external source.
707  void LoadExternalWeakUndeclaredIdentifiers();
708
709  /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
710  /// \#pragma weak during processing of other Decls.
711  /// I couldn't figure out a clean way to generate these in-line, so
712  /// we store them here and handle separately -- which is a hack.
713  /// It would be best to refactor this.
714  SmallVector<Decl*,2> WeakTopLevelDecl;
715
716  IdentifierResolver IdResolver;
717
718  /// Translation Unit Scope - useful to Objective-C actions that need
719  /// to lookup file scope declarations in the "ordinary" C decl namespace.
720  /// For example, user-defined classes, built-in "id" type, etc.
721  Scope *TUScope;
722
723  /// \brief The C++ "std" namespace, where the standard library resides.
724  LazyDeclPtr StdNamespace;
725
726  /// \brief The C++ "std::bad_alloc" class, which is defined by the C++
727  /// standard library.
728  LazyDeclPtr StdBadAlloc;
729
730  /// \brief The C++ "std::align_val_t" enum class, which is defined by the C++
731  /// standard library.
732  LazyDeclPtr StdAlignValT;
733
734  /// \brief The C++ "std::experimental" namespace, where the experimental parts
735  /// of the standard library resides.
736  NamespaceDecl *StdExperimentalNamespaceCache;
737
738  /// \brief The C++ "std::initializer_list" template, which is defined in
739  /// \<initializer_list>.
740  ClassTemplateDecl *StdInitializerList;
741
742  /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
743  RecordDecl *CXXTypeInfoDecl;
744
745  /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
746  RecordDecl *MSVCGuidDecl;
747
748  /// \brief Caches identifiers/selectors for NSFoundation APIs.
749  std::unique_ptr<NSAPI> NSAPIObj;
750
751  /// \brief The declaration of the Objective-C NSNumber class.
752  ObjCInterfaceDecl *NSNumberDecl;
753
754  /// \brief The declaration of the Objective-C NSValue class.
755  ObjCInterfaceDecl *NSValueDecl;
756
757  /// \brief Pointer to NSNumber type (NSNumber *).
758  QualType NSNumberPointer;
759
760  /// \brief Pointer to NSValue type (NSValue *).
761  QualType NSValuePointer;
762
763  /// \brief The Objective-C NSNumber methods used to create NSNumber literals.
764  ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
765
766  /// \brief The declaration of the Objective-C NSString class.
767  ObjCInterfaceDecl *NSStringDecl;
768
769  /// \brief Pointer to NSString type (NSString *).
770  QualType NSStringPointer;
771
772  /// \brief The declaration of the stringWithUTF8String: method.
773  ObjCMethodDecl *StringWithUTF8StringMethod;
774
775  /// \brief The declaration of the valueWithBytes:objCType: method.
776  ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
777
778  /// \brief The declaration of the Objective-C NSArray class.
779  ObjCInterfaceDecl *NSArrayDecl;
780
781  /// \brief The declaration of the arrayWithObjects:count: method.
782  ObjCMethodDecl *ArrayWithObjectsMethod;
783
784  /// \brief The declaration of the Objective-C NSDictionary class.
785  ObjCInterfaceDecl *NSDictionaryDecl;
786
787  /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
788  ObjCMethodDecl *DictionaryWithObjectsMethod;
789
790  /// \brief id<NSCopying> type.
791  QualType QIDNSCopying;
792
793  /// \brief will hold 'respondsToSelector:'
794  Selector RespondsToSelectorSel;
795
796  /// A flag to remember whether the implicit forms of operator new and delete
797  /// have been declared.
798  bool GlobalNewDeleteDeclared;
799
800  /// A flag to indicate that we're in a context that permits abstract
801  /// references to fields.  This is really a
802  bool AllowAbstractFieldReference;
803
804  /// \brief Describes how the expressions currently being parsed are
805  /// evaluated at run-time, if at all.
806  enum class ExpressionEvaluationContext {
807    /// \brief The current expression and its subexpressions occur within an
808    /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
809    /// \c sizeof, where the type of the expression may be significant but
810    /// no code will be generated to evaluate the value of the expression at
811    /// run time.
812    Unevaluated,
813
814    /// \brief The current expression occurs within a braced-init-list within
815    /// an unevaluated operand. This is mostly like a regular unevaluated
816    /// context, except that we still instantiate constexpr functions that are
817    /// referenced here so that we can perform narrowing checks correctly.
818    UnevaluatedList,
819
820    /// \brief The current expression occurs within a discarded statement.
821    /// This behaves largely similarly to an unevaluated operand in preventing
822    /// definitions from being required, but not in other ways.
823    DiscardedStatement,
824
825    /// \brief The current expression occurs within an unevaluated
826    /// operand that unconditionally permits abstract references to
827    /// fields, such as a SIZE operator in MS-style inline assembly.
828    UnevaluatedAbstract,
829
830    /// \brief The current context is "potentially evaluated" in C++11 terms,
831    /// but the expression is evaluated at compile-time (like the values of
832    /// cases in a switch statement).
833    ConstantEvaluated,
834
835    /// \brief The current expression is potentially evaluated at run time,
836    /// which means that code may be generated to evaluate the value of the
837    /// expression at run time.
838    PotentiallyEvaluated,
839
840    /// \brief The current expression is potentially evaluated, but any
841    /// declarations referenced inside that expression are only used if
842    /// in fact the current expression is used.
843    ///
844    /// This value is used when parsing default function arguments, for which
845    /// we would like to provide diagnostics (e.g., passing non-POD arguments
846    /// through varargs) but do not want to mark declarations as "referenced"
847    /// until the default argument is used.
848    PotentiallyEvaluatedIfUsed
849  };
850
851  /// \brief Data structure used to record current or nested
852  /// expression evaluation contexts.
853  struct ExpressionEvaluationContextRecord {
854    /// \brief The expression evaluation context.
855    ExpressionEvaluationContext Context;
856
857    /// \brief Whether the enclosing context needed a cleanup.
858    CleanupInfo ParentCleanup;
859
860    /// \brief Whether we are in a decltype expression.
861    bool IsDecltype;
862
863    /// \brief The number of active cleanup objects when we entered
864    /// this expression evaluation context.
865    unsigned NumCleanupObjects;
866
867    /// \brief The number of typos encountered during this expression evaluation
868    /// context (i.e. the number of TypoExprs created).
869    unsigned NumTypos;
870
871    llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
872
873    /// \brief The lambdas that are present within this context, if it
874    /// is indeed an unevaluated context.
875    SmallVector<LambdaExpr *, 2> Lambdas;
876
877    /// \brief The declaration that provides context for lambda expressions
878    /// and block literals if the normal declaration context does not
879    /// suffice, e.g., in a default function argument.
880    Decl *ManglingContextDecl;
881
882    /// \brief The context information used to mangle lambda expressions
883    /// and block literals within this context.
884    ///
885    /// This mangling information is allocated lazily, since most contexts
886    /// do not have lambda expressions or block literals.
887    std::unique_ptr<MangleNumberingContext> MangleNumbering;
888
889    /// \brief If we are processing a decltype type, a set of call expressions
890    /// for which we have deferred checking the completeness of the return type.
891    SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
892
893    /// \brief If we are processing a decltype type, a set of temporary binding
894    /// expressions for which we have deferred checking the destructor.
895    SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
896
897    ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
898                                      unsigned NumCleanupObjects,
899                                      CleanupInfo ParentCleanup,
900                                      Decl *ManglingContextDecl,
901                                      bool IsDecltype)
902      : Context(Context), ParentCleanup(ParentCleanup),
903        IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
904        NumTypos(0),
905        ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
906
907    /// \brief Retrieve the mangling numbering context, used to consistently
908    /// number constructs like lambdas for mangling.
909    MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
910
911    bool isUnevaluated() const {
912      return Context == ExpressionEvaluationContext::Unevaluated ||
913             Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
914             Context == ExpressionEvaluationContext::UnevaluatedList;
915    }
916    bool isConstantEvaluated() const {
917      return Context == ExpressionEvaluationContext::ConstantEvaluated;
918    }
919  };
920
921  /// A stack of expression evaluation contexts.
922  SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
923
924  /// \brief Compute the mangling number context for a lambda expression or
925  /// block literal.
926  ///
927  /// \param DC - The DeclContext containing the lambda expression or
928  /// block literal.
929  /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
930  /// associated with the context, if relevant.
931  MangleNumberingContext *getCurrentMangleNumberContext(
932    const DeclContext *DC,
933    Decl *&ManglingContextDecl);
934
935
936  /// SpecialMemberOverloadResult - The overloading result for a special member
937  /// function.
938  ///
939  /// This is basically a wrapper around PointerIntPair. The lowest bits of the
940  /// integer are used to determine whether overload resolution succeeded.
941  class SpecialMemberOverloadResult {
942  public:
943    enum Kind {
944      NoMemberOrDeleted,
945      Ambiguous,
946      Success
947    };
948
949  private:
950    llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
951
952  public:
953    SpecialMemberOverloadResult() : Pair() {}
954    SpecialMemberOverloadResult(CXXMethodDecl *MD)
955        : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
956
957    CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
958    void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
959
960    Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
961    void setKind(Kind K) { Pair.setInt(K); }
962  };
963
964  class SpecialMemberOverloadResultEntry
965      : public llvm::FastFoldingSetNode,
966        public SpecialMemberOverloadResult {
967  public:
968    SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
969      : FastFoldingSetNode(ID)
970    {}
971  };
972
973  /// \brief A cache of special member function overload resolution results
974  /// for C++ records.
975  llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
976
977  /// \brief A cache of the flags available in enumerations with the flag_bits
978  /// attribute.
979  mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
980
981  /// \brief The kind of translation unit we are processing.
982  ///
983  /// When we're processing a complete translation unit, Sema will perform
984  /// end-of-translation-unit semantic tasks (such as creating
985  /// initializers for tentative definitions in C) once parsing has
986  /// completed. Modules and precompiled headers perform different kinds of
987  /// checks.
988  TranslationUnitKind TUKind;
989
990  llvm::BumpPtrAllocator BumpAlloc;
991
992  /// \brief The number of SFINAE diagnostics that have been trapped.
993  unsigned NumSFINAEErrors;
994
995  typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
996    UnparsedDefaultArgInstantiationsMap;
997
998  /// \brief A mapping from parameters with unparsed default arguments to the
999  /// set of instantiations of each parameter.
1000  ///
1001  /// This mapping is a temporary data structure used when parsing
1002  /// nested class templates or nested classes of class templates,
1003  /// where we might end up instantiating an inner class before the
1004  /// default arguments of its methods have been parsed.
1005  UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1006
1007  // Contains the locations of the beginning of unparsed default
1008  // argument locations.
1009  llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1010
1011  /// UndefinedInternals - all the used, undefined objects which require a
1012  /// definition in this translation unit.
1013  llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1014
1015  /// Obtain a sorted list of functions that are undefined but ODR-used.
1016  void getUndefinedButUsed(
1017      SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1018
1019  /// Retrieves list of suspicious delete-expressions that will be checked at
1020  /// the end of translation unit.
1021  const llvm::MapVector<FieldDecl *, DeleteLocs> &
1022  getMismatchingDeleteExpressions() const;
1023
1024  typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
1025  typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
1026
1027  /// Method Pool - allows efficient lookup when typechecking messages to "id".
1028  /// We need to maintain a list, since selectors can have differing signatures
1029  /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1030  /// of selectors are "overloaded").
1031  /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1032  /// methods inside categories with a particular selector.
1033  GlobalMethodPool MethodPool;
1034
1035  /// Method selectors used in a \@selector expression. Used for implementation
1036  /// of -Wselector.
1037  llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1038
1039  /// Kinds of C++ special members.
1040  enum CXXSpecialMember {
1041    CXXDefaultConstructor,
1042    CXXCopyConstructor,
1043    CXXMoveConstructor,
1044    CXXCopyAssignment,
1045    CXXMoveAssignment,
1046    CXXDestructor,
1047    CXXInvalid
1048  };
1049
1050  typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl;
1051
1052  /// The C++ special members which we are currently in the process of
1053  /// declaring. If this process recursively triggers the declaration of the
1054  /// same special member, we should act as if it is not yet declared.
1055  llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1056
1057  void ReadMethodPool(Selector Sel);
1058  void updateOutOfDateSelector(Selector Sel);
1059
1060  /// Private Helper predicate to check for 'self'.
1061  bool isSelfExpr(Expr *RExpr);
1062  bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1063
1064  /// \brief Cause the active diagnostic on the DiagosticsEngine to be
1065  /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1066  /// should not be used elsewhere.
1067  void EmitCurrentDiagnostic(unsigned DiagID);
1068
1069  /// Records and restores the FP_CONTRACT state on entry/exit of compound
1070  /// statements.
1071  class FPContractStateRAII {
1072  public:
1073    FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
1074    ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
1075
1076  private:
1077    Sema& S;
1078    FPOptions OldFPFeaturesState;
1079  };
1080
1081  void addImplicitTypedef(StringRef Name, QualType T);
1082
1083public:
1084  Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1085       TranslationUnitKind TUKind = TU_Complete,
1086       CodeCompleteConsumer *CompletionConsumer = nullptr);
1087  ~Sema();
1088
1089  /// \brief Perform initialization that occurs after the parser has been
1090  /// initialized but before it parses anything.
1091  void Initialize();
1092
1093  const LangOptions &getLangOpts() const { return LangOpts; }
1094  OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1095  FPOptions     &getFPOptions() { return FPFeatures; }
1096
1097  DiagnosticsEngine &getDiagnostics() const { return Diags; }
1098  SourceManager &getSourceManager() const { return SourceMgr; }
1099  Preprocessor &getPreprocessor() const { return PP; }
1100  ASTContext &getASTContext() const { return Context; }
1101  ASTConsumer &getASTConsumer() const { return Consumer; }
1102  ASTMutationListener *getASTMutationListener() const;
1103  ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1104
1105  ///\brief Registers an external source. If an external source already exists,
1106  /// creates a multiplex external source and appends to it.
1107  ///
1108  ///\param[in] E - A non-null external sema source.
1109  ///
1110  void addExternalSource(ExternalSemaSource *E);
1111
1112  void PrintStats() const;
1113
1114  /// \brief Helper class that creates diagnostics with optional
1115  /// template instantiation stacks.
1116  ///
1117  /// This class provides a wrapper around the basic DiagnosticBuilder
1118  /// class that emits diagnostics. SemaDiagnosticBuilder is
1119  /// responsible for emitting the diagnostic (as DiagnosticBuilder
1120  /// does) and, if the diagnostic comes from inside a template
1121  /// instantiation, printing the template instantiation stack as
1122  /// well.
1123  class SemaDiagnosticBuilder : public DiagnosticBuilder {
1124    Sema &SemaRef;
1125    unsigned DiagID;
1126
1127  public:
1128    SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1129      : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
1130
1131    // This is a cunning lie. DiagnosticBuilder actually performs move
1132    // construction in its copy constructor (but due to varied uses, it's not
1133    // possible to conveniently express this as actual move construction). So
1134    // the default copy ctor here is fine, because the base class disables the
1135    // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
1136    // in that case anwyay.
1137    SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
1138
1139    ~SemaDiagnosticBuilder() {
1140      // If we aren't active, there is nothing to do.
1141      if (!isActive()) return;
1142
1143      // Otherwise, we need to emit the diagnostic. First flush the underlying
1144      // DiagnosticBuilder data, and clear the diagnostic builder itself so it
1145      // won't emit the diagnostic in its own destructor.
1146      //
1147      // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1148      // do its own needless checks to see if the diagnostic needs to be
1149      // emitted. However, because we take care to ensure that the builder
1150      // objects never escape, a sufficiently smart compiler will be able to
1151      // eliminate that code.
1152      FlushCounts();
1153      Clear();
1154
1155      // Dispatch to Sema to emit the diagnostic.
1156      SemaRef.EmitCurrentDiagnostic(DiagID);
1157    }
1158
1159    /// Teach operator<< to produce an object of the correct type.
1160    template<typename T>
1161    friend const SemaDiagnosticBuilder &operator<<(
1162        const SemaDiagnosticBuilder &Diag, const T &Value) {
1163      const DiagnosticBuilder &BaseDiag = Diag;
1164      BaseDiag << Value;
1165      return Diag;
1166    }
1167  };
1168
1169  /// \brief Emit a diagnostic.
1170  SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
1171    DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
1172    return SemaDiagnosticBuilder(DB, *this, DiagID);
1173  }
1174
1175  /// \brief Emit a partial diagnostic.
1176  SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
1177
1178  /// \brief Build a partial diagnostic.
1179  PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1180
1181  bool findMacroSpelling(SourceLocation &loc, StringRef name);
1182
1183  /// \brief Get a string to suggest for zero-initialization of a type.
1184  std::string
1185  getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1186  std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1187
1188  /// \brief Calls \c Lexer::getLocForEndOfToken()
1189  SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1190
1191  /// \brief Retrieve the module loader associated with the preprocessor.
1192  ModuleLoader &getModuleLoader() const;
1193
1194  void emitAndClearUnusedLocalTypedefWarnings();
1195
1196  void ActOnEndOfTranslationUnit();
1197
1198  void CheckDelegatingCtorCycles();
1199
1200  Scope *getScopeForContext(DeclContext *Ctx);
1201
1202  void PushFunctionScope();
1203  void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1204  sema::LambdaScopeInfo *PushLambdaScope();
1205
1206  /// \brief This is used to inform Sema what the current TemplateParameterDepth
1207  /// is during Parsing.  Currently it is used to pass on the depth
1208  /// when parsing generic lambda 'auto' parameters.
1209  void RecordParsingTemplateParameterDepth(unsigned Depth);
1210
1211  void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1212                               RecordDecl *RD,
1213                               CapturedRegionKind K);
1214  void
1215  PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1216                       const Decl *D = nullptr,
1217                       const BlockExpr *blkExpr = nullptr);
1218
1219  sema::FunctionScopeInfo *getCurFunction() const {
1220    return FunctionScopes.back();
1221  }
1222
1223  sema::FunctionScopeInfo *getEnclosingFunction() const {
1224    if (FunctionScopes.empty())
1225      return nullptr;
1226
1227    for (int e = FunctionScopes.size()-1; e >= 0; --e) {
1228      if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
1229        continue;
1230      return FunctionScopes[e];
1231    }
1232    return nullptr;
1233  }
1234
1235  template <typename ExprT>
1236  void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
1237    if (!isUnevaluatedContext())
1238      getCurFunction()->recordUseOfWeak(E, IsRead);
1239  }
1240
1241  void PushCompoundScope();
1242  void PopCompoundScope();
1243
1244  sema::CompoundScopeInfo &getCurCompoundScope() const;
1245
1246  bool hasAnyUnrecoverableErrorsInThisFunction() const;
1247
1248  /// \brief Retrieve the current block, if any.
1249  sema::BlockScopeInfo *getCurBlock();
1250
1251  /// Retrieve the current lambda scope info, if any.
1252  /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1253  /// lambda scope info ignoring all inner capturing scopes that are not
1254  /// lambda scopes.
1255  sema::LambdaScopeInfo *
1256  getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1257
1258  /// \brief Retrieve the current generic lambda info, if any.
1259  sema::LambdaScopeInfo *getCurGenericLambda();
1260
1261  /// \brief Retrieve the current captured region, if any.
1262  sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1263
1264  /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1265  SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1266
1267  void ActOnComment(SourceRange Comment);
1268
1269  //===--------------------------------------------------------------------===//
1270  // Type Analysis / Processing: SemaType.cpp.
1271  //
1272
1273  QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
1274                              const DeclSpec *DS = nullptr);
1275  QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
1276                              const DeclSpec *DS = nullptr);
1277  QualType BuildPointerType(QualType T,
1278                            SourceLocation Loc, DeclarationName Entity);
1279  QualType BuildReferenceType(QualType T, bool LValueRef,
1280                              SourceLocation Loc, DeclarationName Entity);
1281  QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1282                          Expr *ArraySize, unsigned Quals,
1283                          SourceRange Brackets, DeclarationName Entity);
1284  QualType BuildExtVectorType(QualType T, Expr *ArraySize,
1285                              SourceLocation AttrLoc);
1286
1287  bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
1288
1289  /// \brief Build a function type.
1290  ///
1291  /// This routine checks the function type according to C++ rules and
1292  /// under the assumption that the result type and parameter types have
1293  /// just been instantiated from a template. It therefore duplicates
1294  /// some of the behavior of GetTypeForDeclarator, but in a much
1295  /// simpler form that is only suitable for this narrow use case.
1296  ///
1297  /// \param T The return type of the function.
1298  ///
1299  /// \param ParamTypes The parameter types of the function. This array
1300  /// will be modified to account for adjustments to the types of the
1301  /// function parameters.
1302  ///
1303  /// \param Loc The location of the entity whose type involves this
1304  /// function type or, if there is no such entity, the location of the
1305  /// type that will have function type.
1306  ///
1307  /// \param Entity The name of the entity that involves the function
1308  /// type, if known.
1309  ///
1310  /// \param EPI Extra information about the function type. Usually this will
1311  /// be taken from an existing function with the same prototype.
1312  ///
1313  /// \returns A suitable function type, if there are no errors. The
1314  /// unqualified type will always be a FunctionProtoType.
1315  /// Otherwise, returns a NULL type.
1316  QualType BuildFunctionType(QualType T,
1317                             MutableArrayRef<QualType> ParamTypes,
1318                             SourceLocation Loc, DeclarationName Entity,
1319                             const FunctionProtoType::ExtProtoInfo &EPI);
1320
1321  QualType BuildMemberPointerType(QualType T, QualType Class,
1322                                  SourceLocation Loc,
1323                                  DeclarationName Entity);
1324  QualType BuildBlockPointerType(QualType T,
1325                                 SourceLocation Loc, DeclarationName Entity);
1326  QualType BuildParenType(QualType T);
1327  QualType BuildAtomicType(QualType T, SourceLocation Loc);
1328  QualType BuildReadPipeType(QualType T,
1329                         SourceLocation Loc);
1330  QualType BuildWritePipeType(QualType T,
1331                         SourceLocation Loc);
1332
1333  TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
1334  TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
1335  TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
1336                                               TypeSourceInfo *ReturnTypeInfo);
1337
1338  /// \brief Package the given type and TSI into a ParsedType.
1339  ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
1340  DeclarationNameInfo GetNameForDeclarator(Declarator &D);
1341  DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
1342  static QualType GetTypeFromParser(ParsedType Ty,
1343                                    TypeSourceInfo **TInfo = nullptr);
1344  CanThrowResult canThrow(const Expr *E);
1345  const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
1346                                                const FunctionProtoType *FPT);
1347  void UpdateExceptionSpec(FunctionDecl *FD,
1348                           const FunctionProtoType::ExceptionSpecInfo &ESI);
1349  bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
1350  bool CheckDistantExceptionSpec(QualType T);
1351  bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
1352  bool CheckEquivalentExceptionSpec(
1353      const FunctionProtoType *Old, SourceLocation OldLoc,
1354      const FunctionProtoType *New, SourceLocation NewLoc);
1355  bool CheckEquivalentExceptionSpec(
1356      const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
1357      const FunctionProtoType *Old, SourceLocation OldLoc,
1358      const FunctionProtoType *New, SourceLocation NewLoc);
1359  bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
1360                                const PartialDiagnostic &NestedDiagID,
1361                                const PartialDiagnostic &NoteID,
1362                                const FunctionProtoType *Superset,
1363                                SourceLocation SuperLoc,
1364                                const FunctionProtoType *Subset,
1365                                SourceLocation SubLoc);
1366  bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
1367                               const PartialDiagnostic &NoteID,
1368                               const FunctionProtoType *Target,
1369                               SourceLocation TargetLoc,
1370                               const FunctionProtoType *Source,
1371                               SourceLocation SourceLoc);
1372
1373  TypeResult ActOnTypeName(Scope *S, Declarator &D);
1374
1375  /// \brief The parser has parsed the context-sensitive type 'instancetype'
1376  /// in an Objective-C message declaration. Return the appropriate type.
1377  ParsedType ActOnObjCInstanceType(SourceLocation Loc);
1378
1379  /// \brief Abstract class used to diagnose incomplete types.
1380  struct TypeDiagnoser {
1381    TypeDiagnoser() {}
1382
1383    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
1384    virtual ~TypeDiagnoser() {}
1385  };
1386
1387  static int getPrintable(int I) { return I; }
1388  static unsigned getPrintable(unsigned I) { return I; }
1389  static bool getPrintable(bool B) { return B; }
1390  static const char * getPrintable(const char *S) { return S; }
1391  static StringRef getPrintable(StringRef S) { return S; }
1392  static const std::string &getPrintable(const std::string &S) { return S; }
1393  static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
1394    return II;
1395  }
1396  static DeclarationName getPrintable(DeclarationName N) { return N; }
1397  static QualType getPrintable(QualType T) { return T; }
1398  static SourceRange getPrintable(SourceRange R) { return R; }
1399  static SourceRange getPrintable(SourceLocation L) { return L; }
1400  static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
1401  static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
1402
1403  template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
1404    unsigned DiagID;
1405    std::tuple<const Ts &...> Args;
1406
1407    template <std::size_t... Is>
1408    void emit(const SemaDiagnosticBuilder &DB,
1409              llvm::index_sequence<Is...>) const {
1410      // Apply all tuple elements to the builder in order.
1411      bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
1412      (void)Dummy;
1413    }
1414
1415  public:
1416    BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
1417        : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
1418      assert(DiagID != 0 && "no diagnostic for type diagnoser");
1419    }
1420
1421    void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
1422      const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
1423      emit(DB, llvm::index_sequence_for<Ts...>());
1424      DB << T;
1425    }
1426  };
1427
1428private:
1429  bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
1430                               TypeDiagnoser *Diagnoser);
1431
1432  struct ModuleScope {
1433    clang::Module *Module;
1434    VisibleModuleSet OuterVisibleModules;
1435  };
1436  /// The modules we're currently parsing.
1437  llvm::SmallVector<ModuleScope, 16> ModuleScopes;
1438
1439  VisibleModuleSet VisibleModules;
1440
1441  Module *CachedFakeTopLevelModule;
1442
1443public:
1444  /// \brief Get the module owning an entity.
1445  Module *getOwningModule(Decl *Entity);
1446
1447  /// \brief Make a merged definition of an existing hidden definition \p ND
1448  /// visible at the specified location.
1449  void makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc);
1450
1451  bool isModuleVisible(Module *M) { return VisibleModules.isVisible(M); }
1452
1453  /// Determine whether a declaration is visible to name lookup.
1454  bool isVisible(const NamedDecl *D) {
1455    return !D->isHidden() || isVisibleSlow(D);
1456  }
1457
1458  /// Determine whether any declaration of an entity is visible.
1459  bool
1460  hasVisibleDeclaration(const NamedDecl *D,
1461                        llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
1462    return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
1463  }
1464  bool hasVisibleDeclarationSlow(const NamedDecl *D,
1465                                 llvm::SmallVectorImpl<Module *> *Modules);
1466
1467  bool hasVisibleMergedDefinition(NamedDecl *Def);
1468
1469  /// Determine if \p D has a visible definition. If not, suggest a declaration
1470  /// that should be made visible to expose the definition.
1471  bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
1472                            bool OnlyNeedComplete = false);
1473  bool hasVisibleDefinition(const NamedDecl *D) {
1474    NamedDecl *Hidden;
1475    return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
1476  }
1477
1478  /// Determine if the template parameter \p D has a visible default argument.
1479  bool
1480  hasVisibleDefaultArgument(const NamedDecl *D,
1481                            llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1482
1483  /// Determine if there is a visible declaration of \p D that is a member
1484  /// specialization declaration (as opposed to an instantiated declaration).
1485  bool hasVisibleMemberSpecialization(
1486      const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
1487
1488  /// Determine if \p A and \p B are equivalent internal linkage declarations
1489  /// from different modules, and thus an ambiguity error can be downgraded to
1490  /// an extension warning.
1491  bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
1492                                              const NamedDecl *B);
1493  void diagnoseEquivalentInternalLinkageDeclarations(
1494      SourceLocation Loc, const NamedDecl *D,
1495      ArrayRef<const NamedDecl *> Equiv);
1496
1497  bool isCompleteType(SourceLocation Loc, QualType T) {
1498    return !RequireCompleteTypeImpl(Loc, T, nullptr);
1499  }
1500  bool RequireCompleteType(SourceLocation Loc, QualType T,
1501                           TypeDiagnoser &Diagnoser);
1502  bool RequireCompleteType(SourceLocation Loc, QualType T,
1503                           unsigned DiagID);
1504
1505  template <typename... Ts>
1506  bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
1507                           const Ts &...Args) {
1508    BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1509    return RequireCompleteType(Loc, T, Diagnoser);
1510  }
1511
1512  void completeExprArrayBound(Expr *E);
1513  bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
1514  bool RequireCompleteExprType(Expr *E, unsigned DiagID);
1515
1516  template <typename... Ts>
1517  bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
1518    BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1519    return RequireCompleteExprType(E, Diagnoser);
1520  }
1521
1522  bool RequireLiteralType(SourceLocation Loc, QualType T,
1523                          TypeDiagnoser &Diagnoser);
1524  bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
1525
1526  template <typename... Ts>
1527  bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
1528                          const Ts &...Args) {
1529    BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
1530    return RequireLiteralType(Loc, T, Diagnoser);
1531  }
1532
1533  QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1534                             const CXXScopeSpec &SS, QualType T);
1535
1536  QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
1537  /// If AsUnevaluated is false, E is treated as though it were an evaluated
1538  /// context, such as when building a type for decltype(auto).
1539  QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
1540                             bool AsUnevaluated = true);
1541  QualType BuildUnaryTransformType(QualType BaseType,
1542                                   UnaryTransformType::UTTKind UKind,
1543                                   SourceLocation Loc);
1544
1545  //===--------------------------------------------------------------------===//
1546  // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
1547  //
1548
1549  struct SkipBodyInfo {
1550    SkipBodyInfo() : ShouldSkip(false), Previous(nullptr) {}
1551    bool ShouldSkip;
1552    NamedDecl *Previous;
1553  };
1554
1555  DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
1556
1557  void DiagnoseUseOfUnimplementedSelectors();
1558
1559  bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
1560
1561  ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
1562                         Scope *S, CXXScopeSpec *SS = nullptr,
1563                         bool isClassName = false, bool HasTrailingDot = false,
1564                         ParsedType ObjectType = nullptr,
1565                         bool IsCtorOrDtorName = false,
1566                         bool WantNontrivialTypeSourceInfo = false,
1567                         bool IsClassTemplateDeductionContext = true,
1568                         IdentifierInfo **CorrectedII = nullptr);
1569  TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
1570  bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
1571  void DiagnoseUnknownTypeName(IdentifierInfo *&II,
1572                               SourceLocation IILoc,
1573                               Scope *S,
1574                               CXXScopeSpec *SS,
1575                               ParsedType &SuggestedType,
1576                               bool AllowClassTemplates = false);
1577
1578  /// Attempt to behave like MSVC in situations where lookup of an unqualified
1579  /// type name has failed in a dependent context. In these situations, we
1580  /// automatically form a DependentTypeName that will retry lookup in a related
1581  /// scope during instantiation.
1582  ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
1583                                      SourceLocation NameLoc,
1584                                      bool IsTemplateTypeArg);
1585
1586  /// \brief Describes the result of the name lookup and resolution performed
1587  /// by \c ClassifyName().
1588  enum NameClassificationKind {
1589    NC_Unknown,
1590    NC_Error,
1591    NC_Keyword,
1592    NC_Type,
1593    NC_Expression,
1594    NC_NestedNameSpecifier,
1595    NC_TypeTemplate,
1596    NC_VarTemplate,
1597    NC_FunctionTemplate
1598  };
1599
1600  class NameClassification {
1601    NameClassificationKind Kind;
1602    ExprResult Expr;
1603    TemplateName Template;
1604    ParsedType Type;
1605    const IdentifierInfo *Keyword;
1606
1607    explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
1608
1609  public:
1610    NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
1611
1612    NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
1613
1614    NameClassification(const IdentifierInfo *Keyword)
1615      : Kind(NC_Keyword), Keyword(Keyword) { }
1616
1617    static NameClassification Error() {
1618      return NameClassification(NC_Error);
1619    }
1620
1621    static NameClassification Unknown() {
1622      return NameClassification(NC_Unknown);
1623    }
1624
1625    static NameClassification NestedNameSpecifier() {
1626      return NameClassification(NC_NestedNameSpecifier);
1627    }
1628
1629    static NameClassification TypeTemplate(TemplateName Name) {
1630      NameClassification Result(NC_TypeTemplate);
1631      Result.Template = Name;
1632      return Result;
1633    }
1634
1635    static NameClassification VarTemplate(TemplateName Name) {
1636      NameClassification Result(NC_VarTemplate);
1637      Result.Template = Name;
1638      return Result;
1639    }
1640
1641    static NameClassification FunctionTemplate(TemplateName Name) {
1642      NameClassification Result(NC_FunctionTemplate);
1643      Result.Template = Name;
1644      return Result;
1645    }
1646
1647    NameClassificationKind getKind() const { return Kind; }
1648
1649    ParsedType getType() const {
1650      assert(Kind == NC_Type);
1651      return Type;
1652    }
1653
1654    ExprResult getExpression() const {
1655      assert(Kind == NC_Expression);
1656      return Expr;
1657    }
1658
1659    TemplateName getTemplateName() const {
1660      assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
1661             Kind == NC_VarTemplate);
1662      return Template;
1663    }
1664
1665    TemplateNameKind getTemplateNameKind() const {
1666      switch (Kind) {
1667      case NC_TypeTemplate:
1668        return TNK_Type_template;
1669      case NC_FunctionTemplate:
1670        return TNK_Function_template;
1671      case NC_VarTemplate:
1672        return TNK_Var_template;
1673      default:
1674        llvm_unreachable("unsupported name classification.");
1675      }
1676    }
1677  };
1678
1679  /// \brief Perform name lookup on the given name, classifying it based on
1680  /// the results of name lookup and the following token.
1681  ///
1682  /// This routine is used by the parser to resolve identifiers and help direct
1683  /// parsing. When the identifier cannot be found, this routine will attempt
1684  /// to correct the typo and classify based on the resulting name.
1685  ///
1686  /// \param S The scope in which we're performing name lookup.
1687  ///
1688  /// \param SS The nested-name-specifier that precedes the name.
1689  ///
1690  /// \param Name The identifier. If typo correction finds an alternative name,
1691  /// this pointer parameter will be updated accordingly.
1692  ///
1693  /// \param NameLoc The location of the identifier.
1694  ///
1695  /// \param NextToken The token following the identifier. Used to help
1696  /// disambiguate the name.
1697  ///
1698  /// \param IsAddressOfOperand True if this name is the operand of a unary
1699  ///        address of ('&') expression, assuming it is classified as an
1700  ///        expression.
1701  ///
1702  /// \param CCC The correction callback, if typo correction is desired.
1703  NameClassification
1704  ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
1705               SourceLocation NameLoc, const Token &NextToken,
1706               bool IsAddressOfOperand,
1707               std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
1708
1709  /// Describes the detailed kind of a template name. Used in diagnostics.
1710  enum class TemplateNameKindForDiagnostics {
1711    ClassTemplate,
1712    FunctionTemplate,
1713    VarTemplate,
1714    AliasTemplate,
1715    TemplateTemplateParam,
1716    DependentTemplate
1717  };
1718  TemplateNameKindForDiagnostics
1719  getTemplateNameKindForDiagnostics(TemplateName Name);
1720
1721  Decl *ActOnDeclarator(Scope *S, Declarator &D);
1722
1723  NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
1724                              MultiTemplateParamsArg TemplateParameterLists);
1725  void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
1726  bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
1727  bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
1728                                    DeclarationName Name,
1729                                    SourceLocation Loc);
1730  void
1731  diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1732                            SourceLocation FallbackLoc,
1733                            SourceLocation ConstQualLoc = SourceLocation(),
1734                            SourceLocation VolatileQualLoc = SourceLocation(),
1735                            SourceLocation RestrictQualLoc = SourceLocation(),
1736                            SourceLocation AtomicQualLoc = SourceLocation(),
1737                            SourceLocation UnalignedQualLoc = SourceLocation());
1738
1739  static bool adjustContextForLocalExternDecl(DeclContext *&DC);
1740  void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
1741  NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
1742                                    const LookupResult &R);
1743  NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
1744  void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
1745                   const LookupResult &R);
1746  void CheckShadow(Scope *S, VarDecl *D);
1747
1748  /// Warn if 'E', which is an expression that is about to be modified, refers
1749  /// to a shadowing declaration.
1750  void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
1751
1752  void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
1753
1754private:
1755  /// Map of current shadowing declarations to shadowed declarations. Warn if
1756  /// it looks like the user is trying to modify the shadowing declaration.
1757  llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
1758
1759public:
1760  void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
1761  void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
1762  void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
1763                                    TypedefNameDecl *NewTD);
1764  void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
1765  NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1766                                    TypeSourceInfo *TInfo,
1767                                    LookupResult &Previous);
1768  NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
1769                                  LookupResult &Previous, bool &Redeclaration);
1770  NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
1771                                     TypeSourceInfo *TInfo,
1772                                     LookupResult &Previous,
1773                                     MultiTemplateParamsArg TemplateParamLists,
1774                                     bool &AddToScope,
1775                                     ArrayRef<BindingDecl *> Bindings = None);
1776  NamedDecl *
1777  ActOnDecompositionDeclarator(Scope *S, Declarator &D,
1778                               MultiTemplateParamsArg TemplateParamLists);
1779  // Returns true if the variable declaration is a redeclaration
1780  bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
1781  void CheckVariableDeclarationType(VarDecl *NewVD);
1782  bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
1783                                     Expr *Init);
1784  void CheckCompleteVariableDeclaration(VarDecl *VD);
1785  void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
1786  void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
1787
1788  NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
1789                                     TypeSourceInfo *TInfo,
1790                                     LookupResult &Previous,
1791                                     MultiTemplateParamsArg TemplateParamLists,
1792                                     bool &AddToScope);
1793  bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
1794
1795  bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
1796  bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
1797
1798  void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
1799  void FindHiddenVirtualMethods(CXXMethodDecl *MD,
1800                          SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1801  void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
1802                          SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
1803  // Returns true if the function declaration is a redeclaration
1804  bool CheckFunctionDeclaration(Scope *S,
1805                                FunctionDecl *NewFD, LookupResult &Previous,
1806                                bool IsMemberSpecialization);
1807  bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
1808  void CheckMain(FunctionDecl *FD, const DeclSpec &D);
1809  void CheckMSVCRTEntryPoint(FunctionDecl *FD);
1810  Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
1811  ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
1812                                          SourceLocation Loc,
1813                                          QualType T);
1814  ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
1815                              SourceLocation NameLoc, IdentifierInfo *Name,
1816                              QualType T, TypeSourceInfo *TSInfo,
1817                              StorageClass SC);
1818  void ActOnParamDefaultArgument(Decl *param,
1819                                 SourceLocation EqualLoc,
1820                                 Expr *defarg);
1821  void ActOnParamUnparsedDefaultArgument(Decl *param,
1822                                         SourceLocation EqualLoc,
1823                                         SourceLocation ArgLoc);
1824  void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
1825  bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
1826                               SourceLocation EqualLoc);
1827
1828  void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
1829  void ActOnUninitializedDecl(Decl *dcl);
1830  void ActOnInitializerError(Decl *Dcl);
1831
1832  void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
1833  void ActOnCXXForRangeDecl(Decl *D);
1834  StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
1835                                        IdentifierInfo *Ident,
1836                                        ParsedAttributes &Attrs,
1837                                        SourceLocation AttrEnd);
1838  void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
1839  void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
1840  void FinalizeDeclaration(Decl *D);
1841  DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
1842                                         ArrayRef<Decl *> Group);
1843  DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
1844
1845  /// Should be called on all declarations that might have attached
1846  /// documentation comments.
1847  void ActOnDocumentableDecl(Decl *D);
1848  void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
1849
1850  void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
1851                                       SourceLocation LocAfterDecls);
1852  void CheckForFunctionRedefinition(
1853      FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
1854      SkipBodyInfo *SkipBody = nullptr);
1855  Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
1856                                MultiTemplateParamsArg TemplateParamLists,
1857                                SkipBodyInfo *SkipBody = nullptr);
1858  Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
1859                                SkipBodyInfo *SkipBody = nullptr);
1860  void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
1861  bool isObjCMethodDecl(Decl *D) {
1862    return D && isa<ObjCMethodDecl>(D);
1863  }
1864
1865  /// \brief Determine whether we can delay parsing the body of a function or
1866  /// function template until it is used, assuming we don't care about emitting
1867  /// code for that function.
1868  ///
1869  /// This will be \c false if we may need the body of the function in the
1870  /// middle of parsing an expression (where it's impractical to switch to
1871  /// parsing a different function), for instance, if it's constexpr in C++11
1872  /// or has an 'auto' return type in C++14. These cases are essentially bugs.
1873  bool canDelayFunctionBody(const Declarator &D);
1874
1875  /// \brief Determine whether we can skip parsing the body of a function
1876  /// definition, assuming we don't care about analyzing its body or emitting
1877  /// code for that function.
1878  ///
1879  /// This will be \c false only if we may need the body of the function in
1880  /// order to parse the rest of the program (for instance, if it is
1881  /// \c constexpr in C++11 or has an 'auto' return type in C++14).
1882  bool canSkipFunctionBody(Decl *D);
1883
1884  void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
1885  Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
1886  Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
1887  Decl *ActOnSkippedFunctionBody(Decl *Decl);
1888  void ActOnFinishInlineFunctionDef(FunctionDecl *D);
1889
1890  /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
1891  /// attribute for which parsing is delayed.
1892  void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
1893
1894  /// \brief Diagnose any unused parameters in the given sequence of
1895  /// ParmVarDecl pointers.
1896  void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
1897
1898  /// \brief Diagnose whether the size of parameters or return value of a
1899  /// function or obj-c method definition is pass-by-value and larger than a
1900  /// specified threshold.
1901  void
1902  DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
1903                                         QualType ReturnTy, NamedDecl *D);
1904
1905  void DiagnoseInvalidJumps(Stmt *Body);
1906  Decl *ActOnFileScopeAsmDecl(Expr *expr,
1907                              SourceLocation AsmLoc,
1908                              SourceLocation RParenLoc);
1909
1910  /// \brief Handle a C++11 empty-declaration and attribute-declaration.
1911  Decl *ActOnEmptyDeclaration(Scope *S,
1912                              AttributeList *AttrList,
1913                              SourceLocation SemiLoc);
1914
1915  enum class ModuleDeclKind {
1916    Module,         ///< 'module X;'
1917    Partition,      ///< 'module partition X;'
1918    Implementation, ///< 'module implementation X;'
1919  };
1920
1921  /// The parser has processed a module-declaration that begins the definition
1922  /// of a module interface or implementation.
1923  DeclGroupPtrTy ActOnModuleDecl(SourceLocation ModuleLoc, ModuleDeclKind MDK,
1924                                 ModuleIdPath Path);
1925
1926  /// \brief The parser has processed a module import declaration.
1927  ///
1928  /// \param AtLoc The location of the '@' symbol, if any.
1929  ///
1930  /// \param ImportLoc The location of the 'import' keyword.
1931  ///
1932  /// \param Path The module access path.
1933  DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
1934                               ModuleIdPath Path);
1935
1936  /// \brief The parser has processed a module import translated from a
1937  /// #include or similar preprocessing directive.
1938  void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1939  void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
1940
1941  /// \brief The parsed has entered a submodule.
1942  void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
1943  /// \brief The parser has left a submodule.
1944  void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
1945
1946  /// \brief Create an implicit import of the given module at the given
1947  /// source location, for error recovery, if possible.
1948  ///
1949  /// This routine is typically used when an entity found by name lookup
1950  /// is actually hidden within a module that we know about but the user
1951  /// has forgotten to import.
1952  void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
1953                                                  Module *Mod);
1954
1955  /// Kinds of missing import. Note, the values of these enumerators correspond
1956  /// to %select values in diagnostics.
1957  enum class MissingImportKind {
1958    Declaration,
1959    Definition,
1960    DefaultArgument,
1961    ExplicitSpecialization,
1962    PartialSpecialization
1963  };
1964
1965  /// \brief Diagnose that the specified declaration needs to be visible but
1966  /// isn't, and suggest a module import that would resolve the problem.
1967  void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
1968                             MissingImportKind MIK, bool Recover = true);
1969  void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
1970                             SourceLocation DeclLoc, ArrayRef<Module *> Modules,
1971                             MissingImportKind MIK, bool Recover);
1972
1973  Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
1974                             SourceLocation LBraceLoc);
1975  Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
1976                              SourceLocation RBraceLoc);
1977
1978  /// \brief We've found a use of a templated declaration that would trigger an
1979  /// implicit instantiation. Check that any relevant explicit specializations
1980  /// and partial specializations are visible, and diagnose if not.
1981  void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
1982
1983  /// \brief We've found a use of a template specialization that would select a
1984  /// partial specialization. Check that the partial specialization is visible,
1985  /// and diagnose if not.
1986  void checkPartialSpecializationVisibility(SourceLocation Loc,
1987                                            NamedDecl *Spec);
1988
1989  /// \brief Retrieve a suitable printing policy.
1990  PrintingPolicy getPrintingPolicy() const {
1991    return getPrintingPolicy(Context, PP);
1992  }
1993
1994  /// \brief Retrieve a suitable printing policy.
1995  static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
1996                                          const Preprocessor &PP);
1997
1998  /// Scope actions.
1999  void ActOnPopScope(SourceLocation Loc, Scope *S);
2000  void ActOnTranslationUnitScope(Scope *S);
2001
2002  Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2003                                   RecordDecl *&AnonRecord);
2004  Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
2005                                   MultiTemplateParamsArg TemplateParams,
2006                                   bool IsExplicitInstantiation,
2007                                   RecordDecl *&AnonRecord);
2008
2009  Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
2010                                    AccessSpecifier AS,
2011                                    RecordDecl *Record,
2012                                    const PrintingPolicy &Policy);
2013
2014  Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
2015                                       RecordDecl *Record);
2016
2017  /// Common ways to introduce type names without a tag for use in diagnostics.
2018  /// Keep in sync with err_tag_reference_non_tag.
2019  enum NonTagKind {
2020    NTK_NonStruct,
2021    NTK_NonClass,
2022    NTK_NonUnion,
2023    NTK_NonEnum,
2024    NTK_Typedef,
2025    NTK_TypeAlias,
2026    NTK_Template,
2027    NTK_TypeAliasTemplate,
2028    NTK_TemplateTemplateArgument,
2029  };
2030
2031  /// Given a non-tag type declaration, returns an enum useful for indicating
2032  /// what kind of non-tag type this is.
2033  NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
2034
2035  bool isAcceptableTagRedeclaration(const TagDecl *Previous,
2036                                    TagTypeKind NewTag, bool isDefinition,
2037                                    SourceLocation NewTagLoc,
2038                                    const IdentifierInfo *Name);
2039
2040  enum TagUseKind {
2041    TUK_Reference,   // Reference to a tag:  'struct foo *X;'
2042    TUK_Declaration, // Fwd decl of a tag:   'struct foo;'
2043    TUK_Definition,  // Definition of a tag: 'struct foo { int X; } Y;'
2044    TUK_Friend       // Friend declaration:  'friend struct foo;'
2045  };
2046
2047  Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
2048                 SourceLocation KWLoc, CXXScopeSpec &SS,
2049                 IdentifierInfo *Name, SourceLocation NameLoc,
2050                 AttributeList *Attr, AccessSpecifier AS,
2051                 SourceLocation ModulePrivateLoc,
2052                 MultiTemplateParamsArg TemplateParameterLists,
2053                 bool &OwnedDecl, bool &IsDependent,
2054                 SourceLocation ScopedEnumKWLoc,
2055                 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
2056                 bool IsTypeSpecifier, SkipBodyInfo *SkipBody = nullptr);
2057
2058  Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
2059                                unsigned TagSpec, SourceLocation TagLoc,
2060                                CXXScopeSpec &SS,
2061                                IdentifierInfo *Name, SourceLocation NameLoc,
2062                                AttributeList *Attr,
2063                                MultiTemplateParamsArg TempParamLists);
2064
2065  TypeResult ActOnDependentTag(Scope *S,
2066                               unsigned TagSpec,
2067                               TagUseKind TUK,
2068                               const CXXScopeSpec &SS,
2069                               IdentifierInfo *Name,
2070                               SourceLocation TagLoc,
2071                               SourceLocation NameLoc);
2072
2073  void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2074                 IdentifierInfo *ClassName,
2075                 SmallVectorImpl<Decl *> &Decls);
2076  Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
2077                   Declarator &D, Expr *BitfieldWidth);
2078
2079  FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
2080                         Declarator &D, Expr *BitfieldWidth,
2081                         InClassInitStyle InitStyle,
2082                         AccessSpecifier AS);
2083  MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
2084                                   SourceLocation DeclStart,
2085                                   Declarator &D, Expr *BitfieldWidth,
2086                                   InClassInitStyle InitStyle,
2087                                   AccessSpecifier AS,
2088                                   AttributeList *MSPropertyAttr);
2089
2090  FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
2091                            TypeSourceInfo *TInfo,
2092                            RecordDecl *Record, SourceLocation Loc,
2093                            bool Mutable, Expr *BitfieldWidth,
2094                            InClassInitStyle InitStyle,
2095                            SourceLocation TSSL,
2096                            AccessSpecifier AS, NamedDecl *PrevDecl,
2097                            Declarator *D = nullptr);
2098
2099  bool CheckNontrivialField(FieldDecl *FD);
2100  void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
2101  bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
2102                              bool Diagnose = false);
2103  CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
2104  void ActOnLastBitfield(SourceLocation DeclStart,
2105                         SmallVectorImpl<Decl *> &AllIvarDecls);
2106  Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
2107                  Declarator &D, Expr *BitfieldWidth,
2108                  tok::ObjCKeywordKind visibility);
2109
2110  // This is used for both record definitions and ObjC interface declarations.
2111  void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
2112                   ArrayRef<Decl *> Fields,
2113                   SourceLocation LBrac, SourceLocation RBrac,
2114                   AttributeList *AttrList);
2115
2116  /// ActOnTagStartDefinition - Invoked when we have entered the
2117  /// scope of a tag's definition (e.g., for an enumeration, class,
2118  /// struct, or union).
2119  void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
2120
2121  typedef void *SkippedDefinitionContext;
2122
2123  /// \brief Invoked when we enter a tag definition that we're skipping.
2124  SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
2125
2126  Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
2127
2128  /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
2129  /// C++ record definition's base-specifiers clause and are starting its
2130  /// member declarations.
2131  void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
2132                                       SourceLocation FinalLoc,
2133                                       bool IsFinalSpelledSealed,
2134                                       SourceLocation LBraceLoc);
2135
2136  /// ActOnTagFinishDefinition - Invoked once we have finished parsing
2137  /// the definition of a tag (enumeration, class, struct, or union).
2138  void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
2139                                SourceRange BraceRange);
2140
2141  void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
2142
2143  void ActOnObjCContainerFinishDefinition();
2144
2145  /// \brief Invoked when we must temporarily exit the objective-c container
2146  /// scope for parsing/looking-up C constructs.
2147  ///
2148  /// Must be followed by a call to \see ActOnObjCReenterContainerContext
2149  void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
2150  void ActOnObjCReenterContainerContext(DeclContext *DC);
2151
2152  /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
2153  /// error parsing the definition of a tag.
2154  void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
2155
2156  EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
2157                                      EnumConstantDecl *LastEnumConst,
2158                                      SourceLocation IdLoc,
2159                                      IdentifierInfo *Id,
2160                                      Expr *val);
2161  bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
2162  bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
2163                              QualType EnumUnderlyingTy,
2164                              bool EnumUnderlyingIsImplicit,
2165                              const EnumDecl *Prev);
2166
2167  /// Determine whether the body of an anonymous enumeration should be skipped.
2168  /// \param II The name of the first enumerator.
2169  SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
2170                                      SourceLocation IILoc);
2171
2172  Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
2173                          SourceLocation IdLoc, IdentifierInfo *Id,
2174                          AttributeList *Attrs,
2175                          SourceLocation EqualLoc, Expr *Val);
2176  void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
2177                     Decl *EnumDecl,
2178                     ArrayRef<Decl *> Elements,
2179                     Scope *S, AttributeList *Attr);
2180
2181  DeclContext *getContainingDC(DeclContext *DC);
2182
2183  /// Set the current declaration context until it gets popped.
2184  void PushDeclContext(Scope *S, DeclContext *DC);
2185  void PopDeclContext();
2186
2187  /// EnterDeclaratorContext - Used when we must lookup names in the context
2188  /// of a declarator's nested name specifier.
2189  void EnterDeclaratorContext(Scope *S, DeclContext *DC);
2190  void ExitDeclaratorContext(Scope *S);
2191
2192  /// Push the parameters of D, which must be a function, into scope.
2193  void ActOnReenterFunctionContext(Scope* S, Decl* D);
2194  void ActOnExitFunctionContext();
2195
2196  DeclContext *getFunctionLevelDeclContext();
2197
2198  /// getCurFunctionDecl - If inside of a function body, this returns a pointer
2199  /// to the function decl for the function being parsed.  If we're currently
2200  /// in a 'block', this returns the containing context.
2201  FunctionDecl *getCurFunctionDecl();
2202
2203  /// getCurMethodDecl - If inside of a method body, this returns a pointer to
2204  /// the method decl for the method being parsed.  If we're currently
2205  /// in a 'block', this returns the containing context.
2206  ObjCMethodDecl *getCurMethodDecl();
2207
2208  /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
2209  /// or C function we're in, otherwise return null.  If we're currently
2210  /// in a 'block', this returns the containing context.
2211  NamedDecl *getCurFunctionOrMethodDecl();
2212
2213  /// Add this decl to the scope shadowed decl chains.
2214  void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
2215
2216  /// \brief Make the given externally-produced declaration visible at the
2217  /// top level scope.
2218  ///
2219  /// \param D The externally-produced declaration to push.
2220  ///
2221  /// \param Name The name of the externally-produced declaration.
2222  void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
2223
2224  /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
2225  /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
2226  /// true if 'D' belongs to the given declaration context.
2227  ///
2228  /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
2229  ///        enclosing namespace set of the context, rather than contained
2230  ///        directly within it.
2231  bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
2232                     bool AllowInlineNamespace = false);
2233
2234  /// Finds the scope corresponding to the given decl context, if it
2235  /// happens to be an enclosing scope.  Otherwise return NULL.
2236  static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
2237
2238  /// Subroutines of ActOnDeclarator().
2239  TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
2240                                TypeSourceInfo *TInfo);
2241  bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
2242
2243  /// \brief Describes the kind of merge to perform for availability
2244  /// attributes (including "deprecated", "unavailable", and "availability").
2245  enum AvailabilityMergeKind {
2246    /// \brief Don't merge availability attributes at all.
2247    AMK_None,
2248    /// \brief Merge availability attributes for a redeclaration, which requires
2249    /// an exact match.
2250    AMK_Redeclaration,
2251    /// \brief Merge availability attributes for an override, which requires
2252    /// an exact match or a weakening of constraints.
2253    AMK_Override,
2254    /// \brief Merge availability attributes for an implementation of
2255    /// a protocol requirement.
2256    AMK_ProtocolImplementation,
2257  };
2258
2259  /// Attribute merging methods. Return true if a new attribute was added.
2260  AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2261                                          IdentifierInfo *Platform,
2262                                          bool Implicit,
2263                                          VersionTuple Introduced,
2264                                          VersionTuple Deprecated,
2265                                          VersionTuple Obsoleted,
2266                                          bool IsUnavailable,
2267                                          StringRef Message,
2268                                          bool IsStrict, StringRef Replacement,
2269                                          AvailabilityMergeKind AMK,
2270                                          unsigned AttrSpellingListIndex);
2271  TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2272                                       TypeVisibilityAttr::VisibilityType Vis,
2273                                              unsigned AttrSpellingListIndex);
2274  VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
2275                                      VisibilityAttr::VisibilityType Vis,
2276                                      unsigned AttrSpellingListIndex);
2277  UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range,
2278                          unsigned AttrSpellingListIndex, StringRef Uuid);
2279  DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
2280                                    unsigned AttrSpellingListIndex);
2281  DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
2282                                    unsigned AttrSpellingListIndex);
2283  MSInheritanceAttr *
2284  mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
2285                         unsigned AttrSpellingListIndex,
2286                         MSInheritanceAttr::Spelling SemanticSpelling);
2287  FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
2288                              IdentifierInfo *Format, int FormatIdx,
2289                              int FirstArg, unsigned AttrSpellingListIndex);
2290  SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
2291                                unsigned AttrSpellingListIndex);
2292  AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
2293                                          IdentifierInfo *Ident,
2294                                          unsigned AttrSpellingListIndex);
2295  MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
2296                                unsigned AttrSpellingListIndex);
2297  OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
2298                                          unsigned AttrSpellingListIndex);
2299  InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, SourceRange Range,
2300                                                IdentifierInfo *Ident,
2301                                                unsigned AttrSpellingListIndex);
2302  CommonAttr *mergeCommonAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident,
2303                              unsigned AttrSpellingListIndex);
2304
2305  void mergeDeclAttributes(NamedDecl *New, Decl *Old,
2306                           AvailabilityMergeKind AMK = AMK_Redeclaration);
2307  void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2308                            LookupResult &OldDecls);
2309  bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
2310                         bool MergeTypeWithOld);
2311  bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2312                                    Scope *S, bool MergeTypeWithOld);
2313  void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
2314  void MergeVarDecl(VarDecl *New, LookupResult &Previous);
2315  void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
2316  void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
2317  bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
2318  bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
2319
2320  // AssignmentAction - This is used by all the assignment diagnostic functions
2321  // to represent what is actually causing the operation
2322  enum AssignmentAction {
2323    AA_Assigning,
2324    AA_Passing,
2325    AA_Returning,
2326    AA_Converting,
2327    AA_Initializing,
2328    AA_Sending,
2329    AA_Casting,
2330    AA_Passing_CFAudited
2331  };
2332
2333  /// C++ Overloading.
2334  enum OverloadKind {
2335    /// This is a legitimate overload: the existing declarations are
2336    /// functions or function templates with different signatures.
2337    Ovl_Overload,
2338
2339    /// This is not an overload because the signature exactly matches
2340    /// an existing declaration.
2341    Ovl_Match,
2342
2343    /// This is not an overload because the lookup results contain a
2344    /// non-function.
2345    Ovl_NonFunction
2346  };
2347  OverloadKind CheckOverload(Scope *S,
2348                             FunctionDecl *New,
2349                             const LookupResult &OldDecls,
2350                             NamedDecl *&OldDecl,
2351                             bool IsForUsingDecl);
2352  bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
2353                  bool ConsiderCudaAttrs = true);
2354
2355  /// \brief Checks availability of the function depending on the current
2356  /// function context.Inside an unavailable function,unavailability is ignored.
2357  ///
2358  /// \returns true if \p FD is unavailable and current context is inside
2359  /// an available function, false otherwise.
2360  bool isFunctionConsideredUnavailable(FunctionDecl *FD);
2361
2362  ImplicitConversionSequence
2363  TryImplicitConversion(Expr *From, QualType ToType,
2364                        bool SuppressUserConversions,
2365                        bool AllowExplicit,
2366                        bool InOverloadResolution,
2367                        bool CStyle,
2368                        bool AllowObjCWritebackConversion);
2369
2370  bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
2371  bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
2372  bool IsComplexPromotion(QualType FromType, QualType ToType);
2373  bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2374                           bool InOverloadResolution,
2375                           QualType& ConvertedType, bool &IncompatibleObjC);
2376  bool isObjCPointerConversion(QualType FromType, QualType ToType,
2377                               QualType& ConvertedType, bool &IncompatibleObjC);
2378  bool isObjCWritebackConversion(QualType FromType, QualType ToType,
2379                                 QualType &ConvertedType);
2380  bool IsBlockPointerConversion(QualType FromType, QualType ToType,
2381                                QualType& ConvertedType);
2382  bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2383                                  const FunctionProtoType *NewType,
2384                                  unsigned *ArgPos = nullptr);
2385  void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2386                                  QualType FromType, QualType ToType);
2387
2388  void maybeExtendBlockObject(ExprResult &E);
2389  CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
2390  bool CheckPointerConversion(Expr *From, QualType ToType,
2391                              CastKind &Kind,
2392                              CXXCastPath& BasePath,
2393                              bool IgnoreBaseAccess,
2394                              bool Diagnose = true);
2395  bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
2396                                 bool InOverloadResolution,
2397                                 QualType &ConvertedType);
2398  bool CheckMemberPointerConversion(Expr *From, QualType ToType,
2399                                    CastKind &Kind,
2400                                    CXXCastPath &BasePath,
2401                                    bool IgnoreBaseAccess);
2402  bool IsQualificationConversion(QualType FromType, QualType ToType,
2403                                 bool CStyle, bool &ObjCLifetimeConversion);
2404  bool IsFunctionConversion(QualType FromType, QualType ToType,
2405                            QualType &ResultTy);
2406  bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
2407  bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
2408
2409  ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2410                                             const VarDecl *NRVOCandidate,
2411                                             QualType ResultType,
2412                                             Expr *Value,
2413                                             bool AllowNRVO = true);
2414
2415  bool CanPerformCopyInitialization(const InitializedEntity &Entity,
2416                                    ExprResult Init);
2417  ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
2418                                       SourceLocation EqualLoc,
2419                                       ExprResult Init,
2420                                       bool TopLevelOfInitList = false,
2421                                       bool AllowExplicit = false);
2422  ExprResult PerformObjectArgumentInitialization(Expr *From,
2423                                                 NestedNameSpecifier *Qualifier,
2424                                                 NamedDecl *FoundDecl,
2425                                                 CXXMethodDecl *Method);
2426
2427  ExprResult PerformContextuallyConvertToBool(Expr *From);
2428  ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
2429
2430  /// Contexts in which a converted constant expression is required.
2431  enum CCEKind {
2432    CCEK_CaseValue,   ///< Expression in a case label.
2433    CCEK_Enumerator,  ///< Enumerator value with fixed underlying type.
2434    CCEK_TemplateArg, ///< Value of a non-type template parameter.
2435    CCEK_NewExpr,     ///< Constant expression in a noptr-new-declarator.
2436    CCEK_ConstexprIf  ///< Condition in a constexpr if statement.
2437  };
2438  ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2439                                              llvm::APSInt &Value, CCEKind CCE);
2440  ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
2441                                              APValue &Value, CCEKind CCE);
2442
2443  /// \brief Abstract base class used to perform a contextual implicit
2444  /// conversion from an expression to any type passing a filter.
2445  class ContextualImplicitConverter {
2446  public:
2447    bool Suppress;
2448    bool SuppressConversion;
2449
2450    ContextualImplicitConverter(bool Suppress = false,
2451                                bool SuppressConversion = false)
2452        : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
2453
2454    /// \brief Determine whether the specified type is a valid destination type
2455    /// for this conversion.
2456    virtual bool match(QualType T) = 0;
2457
2458    /// \brief Emits a diagnostic complaining that the expression does not have
2459    /// integral or enumeration type.
2460    virtual SemaDiagnosticBuilder
2461    diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
2462
2463    /// \brief Emits a diagnostic when the expression has incomplete class type.
2464    virtual SemaDiagnosticBuilder
2465    diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
2466
2467    /// \brief Emits a diagnostic when the only matching conversion function
2468    /// is explicit.
2469    virtual SemaDiagnosticBuilder diagnoseExplicitConv(
2470        Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2471
2472    /// \brief Emits a note for the explicit conversion function.
2473    virtual SemaDiagnosticBuilder
2474    noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2475
2476    /// \brief Emits a diagnostic when there are multiple possible conversion
2477    /// functions.
2478    virtual SemaDiagnosticBuilder
2479    diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
2480
2481    /// \brief Emits a note for one of the candidate conversions.
2482    virtual SemaDiagnosticBuilder
2483    noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
2484
2485    /// \brief Emits a diagnostic when we picked a conversion function
2486    /// (for cases when we are not allowed to pick a conversion function).
2487    virtual SemaDiagnosticBuilder diagnoseConversion(
2488        Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
2489
2490    virtual ~ContextualImplicitConverter() {}
2491  };
2492
2493  class ICEConvertDiagnoser : public ContextualImplicitConverter {
2494    bool AllowScopedEnumerations;
2495
2496  public:
2497    ICEConvertDiagnoser(bool AllowScopedEnumerations,
2498                        bool Suppress, bool SuppressConversion)
2499        : ContextualImplicitConverter(Suppress, SuppressConversion),
2500          AllowScopedEnumerations(AllowScopedEnumerations) {}
2501
2502    /// Match an integral or (possibly scoped) enumeration type.
2503    bool match(QualType T) override;
2504
2505    SemaDiagnosticBuilder
2506    diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
2507      return diagnoseNotInt(S, Loc, T);
2508    }
2509
2510    /// \brief Emits a diagnostic complaining that the expression does not have
2511    /// integral or enumeration type.
2512    virtual SemaDiagnosticBuilder
2513    diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
2514  };
2515
2516  /// Perform a contextual implicit conversion.
2517  ExprResult PerformContextualImplicitConversion(
2518      SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
2519
2520
2521  enum ObjCSubscriptKind {
2522    OS_Array,
2523    OS_Dictionary,
2524    OS_Error
2525  };
2526  ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
2527
2528  // Note that LK_String is intentionally after the other literals, as
2529  // this is used for diagnostics logic.
2530  enum ObjCLiteralKind {
2531    LK_Array,
2532    LK_Dictionary,
2533    LK_Numeric,
2534    LK_Boxed,
2535    LK_String,
2536    LK_Block,
2537    LK_None
2538  };
2539  ObjCLiteralKind CheckLiteralKind(Expr *FromE);
2540
2541  ExprResult PerformObjectMemberConversion(Expr *From,
2542                                           NestedNameSpecifier *Qualifier,
2543                                           NamedDecl *FoundDecl,
2544                                           NamedDecl *Member);
2545
2546  // Members have to be NamespaceDecl* or TranslationUnitDecl*.
2547  // TODO: make this is a typesafe union.
2548  typedef llvm::SmallSetVector<DeclContext   *, 16> AssociatedNamespaceSet;
2549  typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
2550
2551  void AddOverloadCandidate(FunctionDecl *Function,
2552                            DeclAccessPair FoundDecl,
2553                            ArrayRef<Expr *> Args,
2554                            OverloadCandidateSet &CandidateSet,
2555                            bool SuppressUserConversions = false,
2556                            bool PartialOverloading = false,
2557                            bool AllowExplicit = false,
2558                            ConversionSequenceList EarlyConversions = None);
2559  void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
2560                      ArrayRef<Expr *> Args,
2561                      OverloadCandidateSet &CandidateSet,
2562                      TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
2563                      bool SuppressUserConversions = false,
2564                      bool PartialOverloading = false);
2565  void AddMethodCandidate(DeclAccessPair FoundDecl,
2566                          QualType ObjectType,
2567                          Expr::Classification ObjectClassification,
2568                          ArrayRef<Expr *> Args,
2569                          OverloadCandidateSet& CandidateSet,
2570                          bool SuppressUserConversion = false);
2571  void AddMethodCandidate(CXXMethodDecl *Method,
2572                          DeclAccessPair FoundDecl,
2573                          CXXRecordDecl *ActingContext, QualType ObjectType,
2574                          Expr::Classification ObjectClassification,
2575                          ArrayRef<Expr *> Args,
2576                          OverloadCandidateSet& CandidateSet,
2577                          bool SuppressUserConversions = false,
2578                          bool PartialOverloading = false,
2579                          ConversionSequenceList EarlyConversions = None);
2580  void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2581                                  DeclAccessPair FoundDecl,
2582                                  CXXRecordDecl *ActingContext,
2583                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
2584                                  QualType ObjectType,
2585                                  Expr::Classification ObjectClassification,
2586                                  ArrayRef<Expr *> Args,
2587                                  OverloadCandidateSet& CandidateSet,
2588                                  bool SuppressUserConversions = false,
2589                                  bool PartialOverloading = false);
2590  void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2591                                    DeclAccessPair FoundDecl,
2592                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
2593                                    ArrayRef<Expr *> Args,
2594                                    OverloadCandidateSet& CandidateSet,
2595                                    bool SuppressUserConversions = false,
2596                                    bool PartialOverloading = false);
2597  bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate,
2598                                    ArrayRef<QualType> ParamTypes,
2599                                    ArrayRef<Expr *> Args,
2600                                    OverloadCandidateSet &CandidateSet,
2601                                    ConversionSequenceList &Conversions,
2602                                    bool SuppressUserConversions,
2603                                    CXXRecordDecl *ActingContext = nullptr,
2604                                    QualType ObjectType = QualType(),
2605                                    Expr::Classification
2606                                        ObjectClassification = {});
2607  void AddConversionCandidate(CXXConversionDecl *Conversion,
2608                              DeclAccessPair FoundDecl,
2609                              CXXRecordDecl *ActingContext,
2610                              Expr *From, QualType ToType,
2611                              OverloadCandidateSet& CandidateSet,
2612                              bool AllowObjCConversionOnExplicit);
2613  void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2614                                      DeclAccessPair FoundDecl,
2615                                      CXXRecordDecl *ActingContext,
2616                                      Expr *From, QualType ToType,
2617                                      OverloadCandidateSet &CandidateSet,
2618                                      bool AllowObjCConversionOnExplicit);
2619  void AddSurrogateCandidate(CXXConversionDecl *Conversion,
2620                             DeclAccessPair FoundDecl,
2621                             CXXRecordDecl *ActingContext,
2622                             const FunctionProtoType *Proto,
2623                             Expr *Object, ArrayRef<Expr *> Args,
2624                             OverloadCandidateSet& CandidateSet);
2625  void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2626                                   SourceLocation OpLoc, ArrayRef<Expr *> Args,
2627                                   OverloadCandidateSet& CandidateSet,
2628                                   SourceRange OpRange = SourceRange());
2629  void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2630                           ArrayRef<Expr *> Args,
2631                           OverloadCandidateSet& CandidateSet,
2632                           bool IsAssignmentOperator = false,
2633                           unsigned NumContextualBoolArguments = 0);
2634  void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2635                                    SourceLocation OpLoc, ArrayRef<Expr *> Args,
2636                                    OverloadCandidateSet& CandidateSet);
2637  void AddArgumentDependentLookupCandidates(DeclarationName Name,
2638                                            SourceLocation Loc,
2639                                            ArrayRef<Expr *> Args,
2640                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2641                                            OverloadCandidateSet& CandidateSet,
2642                                            bool PartialOverloading = false);
2643
2644  // Emit as a 'note' the specific overload candidate
2645  void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
2646                             QualType DestType = QualType(),
2647                             bool TakingAddress = false);
2648
2649  // Emit as a series of 'note's all template and non-templates identified by
2650  // the expression Expr
2651  void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
2652                                 bool TakingAddress = false);
2653
2654  /// Check the enable_if expressions on the given function. Returns the first
2655  /// failing attribute, or NULL if they were all successful.
2656  EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
2657                              bool MissingImplicitThis = false);
2658
2659  /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2660  /// non-ArgDependent DiagnoseIfAttrs.
2661  ///
2662  /// Argument-dependent diagnose_if attributes should be checked each time a
2663  /// function is used as a direct callee of a function call.
2664  ///
2665  /// Returns true if any errors were emitted.
2666  bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
2667                                           const Expr *ThisArg,
2668                                           ArrayRef<const Expr *> Args,
2669                                           SourceLocation Loc);
2670
2671  /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
2672  /// ArgDependent DiagnoseIfAttrs.
2673  ///
2674  /// Argument-independent diagnose_if attributes should be checked on every use
2675  /// of a function.
2676  ///
2677  /// Returns true if any errors were emitted.
2678  bool diagnoseArgIndependentDiagnoseIfAttrs(const FunctionDecl *Function,
2679                                             SourceLocation Loc);
2680
2681  /// Returns whether the given function's address can be taken or not,
2682  /// optionally emitting a diagnostic if the address can't be taken.
2683  ///
2684  /// Returns false if taking the address of the function is illegal.
2685  bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
2686                                         bool Complain = false,
2687                                         SourceLocation Loc = SourceLocation());
2688
2689  // [PossiblyAFunctionType]  -->   [Return]
2690  // NonFunctionType --> NonFunctionType
2691  // R (A) --> R(A)
2692  // R (*)(A) --> R (A)
2693  // R (&)(A) --> R (A)
2694  // R (S::*)(A) --> R (A)
2695  QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
2696
2697  FunctionDecl *
2698  ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
2699                                     QualType TargetType,
2700                                     bool Complain,
2701                                     DeclAccessPair &Found,
2702                                     bool *pHadMultipleCandidates = nullptr);
2703
2704  FunctionDecl *
2705  resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
2706                                              DeclAccessPair &FoundResult);
2707
2708  bool resolveAndFixAddressOfOnlyViableOverloadCandidate(
2709      ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
2710
2711  FunctionDecl *
2712  ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
2713                                              bool Complain = false,
2714                                              DeclAccessPair *Found = nullptr);
2715
2716  bool ResolveAndFixSingleFunctionTemplateSpecialization(
2717                      ExprResult &SrcExpr,
2718                      bool DoFunctionPointerConverion = false,
2719                      bool Complain = false,
2720                      SourceRange OpRangeForComplaining = SourceRange(),
2721                      QualType DestTypeForComplaining = QualType(),
2722                      unsigned DiagIDForComplaining = 0);
2723
2724
2725  Expr *FixOverloadedFunctionReference(Expr *E,
2726                                       DeclAccessPair FoundDecl,
2727                                       FunctionDecl *Fn);
2728  ExprResult FixOverloadedFunctionReference(ExprResult,
2729                                            DeclAccessPair FoundDecl,
2730                                            FunctionDecl *Fn);
2731
2732  void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
2733                                   ArrayRef<Expr *> Args,
2734                                   OverloadCandidateSet &CandidateSet,
2735                                   bool PartialOverloading = false);
2736
2737  // An enum used to represent the different possible results of building a
2738  // range-based for loop.
2739  enum ForRangeStatus {
2740    FRS_Success,
2741    FRS_NoViableFunction,
2742    FRS_DiagnosticIssued
2743  };
2744
2745  ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
2746                                           SourceLocation RangeLoc,
2747                                           const DeclarationNameInfo &NameInfo,
2748                                           LookupResult &MemberLookup,
2749                                           OverloadCandidateSet *CandidateSet,
2750                                           Expr *Range, ExprResult *CallExpr);
2751
2752  ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
2753                                     UnresolvedLookupExpr *ULE,
2754                                     SourceLocation LParenLoc,
2755                                     MultiExprArg Args,
2756                                     SourceLocation RParenLoc,
2757                                     Expr *ExecConfig,
2758                                     bool AllowTypoCorrection=true,
2759                                     bool CalleesAddressIsTaken=false);
2760
2761  bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
2762                              MultiExprArg Args, SourceLocation RParenLoc,
2763                              OverloadCandidateSet *CandidateSet,
2764                              ExprResult *Result);
2765
2766  ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
2767                                     UnaryOperatorKind Opc,
2768                                     const UnresolvedSetImpl &Fns,
2769                                     Expr *input);
2770
2771  ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
2772                                   BinaryOperatorKind Opc,
2773                                   const UnresolvedSetImpl &Fns,
2774                                   Expr *LHS, Expr *RHS);
2775
2776  ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
2777                                                SourceLocation RLoc,
2778                                                Expr *Base,Expr *Idx);
2779
2780  ExprResult
2781  BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
2782                            SourceLocation LParenLoc,
2783                            MultiExprArg Args,
2784                            SourceLocation RParenLoc);
2785  ExprResult
2786  BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
2787                               MultiExprArg Args,
2788                               SourceLocation RParenLoc);
2789
2790  ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
2791                                      SourceLocation OpLoc,
2792                                      bool *NoArrowOperatorFound = nullptr);
2793
2794  /// CheckCallReturnType - Checks that a call expression's return type is
2795  /// complete. Returns true on failure. The location passed in is the location
2796  /// that best represents the call.
2797  bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
2798                           CallExpr *CE, FunctionDecl *FD);
2799
2800  /// Helpers for dealing with blocks and functions.
2801  bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
2802                                bool CheckParameterNames);
2803  void CheckCXXDefaultArguments(FunctionDecl *FD);
2804  void CheckExtraCXXDefaultArguments(Declarator &D);
2805  Scope *getNonFieldDeclScope(Scope *S);
2806
2807  /// \name Name lookup
2808  ///
2809  /// These routines provide name lookup that is used during semantic
2810  /// analysis to resolve the various kinds of names (identifiers,
2811  /// overloaded operator names, constructor names, etc.) into zero or
2812  /// more declarations within a particular scope. The major entry
2813  /// points are LookupName, which performs unqualified name lookup,
2814  /// and LookupQualifiedName, which performs qualified name lookup.
2815  ///
2816  /// All name lookup is performed based on some specific criteria,
2817  /// which specify what names will be visible to name lookup and how
2818  /// far name lookup should work. These criteria are important both
2819  /// for capturing language semantics (certain lookups will ignore
2820  /// certain names, for example) and for performance, since name
2821  /// lookup is often a bottleneck in the compilation of C++. Name
2822  /// lookup criteria is specified via the LookupCriteria enumeration.
2823  ///
2824  /// The results of name lookup can vary based on the kind of name
2825  /// lookup performed, the current language, and the translation
2826  /// unit. In C, for example, name lookup will either return nothing
2827  /// (no entity found) or a single declaration. In C++, name lookup
2828  /// can additionally refer to a set of overloaded functions or
2829  /// result in an ambiguity. All of the possible results of name
2830  /// lookup are captured by the LookupResult class, which provides
2831  /// the ability to distinguish among them.
2832  //@{
2833
2834  /// @brief Describes the kind of name lookup to perform.
2835  enum LookupNameKind {
2836    /// Ordinary name lookup, which finds ordinary names (functions,
2837    /// variables, typedefs, etc.) in C and most kinds of names
2838    /// (functions, variables, members, types, etc.) in C++.
2839    LookupOrdinaryName = 0,
2840    /// Tag name lookup, which finds the names of enums, classes,
2841    /// structs, and unions.
2842    LookupTagName,
2843    /// Label name lookup.
2844    LookupLabel,
2845    /// Member name lookup, which finds the names of
2846    /// class/struct/union members.
2847    LookupMemberName,
2848    /// Look up of an operator name (e.g., operator+) for use with
2849    /// operator overloading. This lookup is similar to ordinary name
2850    /// lookup, but will ignore any declarations that are class members.
2851    LookupOperatorName,
2852    /// Look up of a name that precedes the '::' scope resolution
2853    /// operator in C++. This lookup completely ignores operator, object,
2854    /// function, and enumerator names (C++ [basic.lookup.qual]p1).
2855    LookupNestedNameSpecifierName,
2856    /// Look up a namespace name within a C++ using directive or
2857    /// namespace alias definition, ignoring non-namespace names (C++
2858    /// [basic.lookup.udir]p1).
2859    LookupNamespaceName,
2860    /// Look up all declarations in a scope with the given name,
2861    /// including resolved using declarations.  This is appropriate
2862    /// for checking redeclarations for a using declaration.
2863    LookupUsingDeclName,
2864    /// Look up an ordinary name that is going to be redeclared as a
2865    /// name with linkage. This lookup ignores any declarations that
2866    /// are outside of the current scope unless they have linkage. See
2867    /// C99 6.2.2p4-5 and C++ [basic.link]p6.
2868    LookupRedeclarationWithLinkage,
2869    /// Look up a friend of a local class. This lookup does not look
2870    /// outside the innermost non-class scope. See C++11 [class.friend]p11.
2871    LookupLocalFriendName,
2872    /// Look up the name of an Objective-C protocol.
2873    LookupObjCProtocolName,
2874    /// Look up implicit 'self' parameter of an objective-c method.
2875    LookupObjCImplicitSelfParam,
2876    /// \brief Look up the name of an OpenMP user-defined reduction operation.
2877    LookupOMPReductionName,
2878    /// \brief Look up any declaration with any name.
2879    LookupAnyName
2880  };
2881
2882  /// \brief Specifies whether (or how) name lookup is being performed for a
2883  /// redeclaration (vs. a reference).
2884  enum RedeclarationKind {
2885    /// \brief The lookup is a reference to this name that is not for the
2886    /// purpose of redeclaring the name.
2887    NotForRedeclaration = 0,
2888    /// \brief The lookup results will be used for redeclaration of a name,
2889    /// if an entity by that name already exists.
2890    ForRedeclaration
2891  };
2892
2893  /// \brief The possible outcomes of name lookup for a literal operator.
2894  enum LiteralOperatorLookupResult {
2895    /// \brief The lookup resulted in an error.
2896    LOLR_Error,
2897    /// \brief The lookup found a single 'cooked' literal operator, which
2898    /// expects a normal literal to be built and passed to it.
2899    LOLR_Cooked,
2900    /// \brief The lookup found a single 'raw' literal operator, which expects
2901    /// a string literal containing the spelling of the literal token.
2902    LOLR_Raw,
2903    /// \brief The lookup found an overload set of literal operator templates,
2904    /// which expect the characters of the spelling of the literal token to be
2905    /// passed as a non-type template argument pack.
2906    LOLR_Template,
2907    /// \brief The lookup found an overload set of literal operator templates,
2908    /// which expect the character type and characters of the spelling of the
2909    /// string literal token to be passed as template arguments.
2910    LOLR_StringTemplate
2911  };
2912
2913  SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
2914                                                  CXXSpecialMember SM,
2915                                                  bool ConstArg,
2916                                                  bool VolatileArg,
2917                                                  bool RValueThis,
2918                                                  bool ConstThis,
2919                                                  bool VolatileThis);
2920
2921  typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
2922  typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
2923      TypoRecoveryCallback;
2924
2925private:
2926  bool CppLookupName(LookupResult &R, Scope *S);
2927
2928  struct TypoExprState {
2929    std::unique_ptr<TypoCorrectionConsumer> Consumer;
2930    TypoDiagnosticGenerator DiagHandler;
2931    TypoRecoveryCallback RecoveryHandler;
2932    TypoExprState();
2933    TypoExprState(TypoExprState &&other) noexcept;
2934    TypoExprState &operator=(TypoExprState &&other) noexcept;
2935  };
2936
2937  /// \brief The set of unhandled TypoExprs and their associated state.
2938  llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
2939
2940  /// \brief Creates a new TypoExpr AST node.
2941  TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
2942                              TypoDiagnosticGenerator TDG,
2943                              TypoRecoveryCallback TRC);
2944
2945  // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
2946  //
2947  // The boolean value will be true to indicate that the namespace was loaded
2948  // from an AST/PCH file, or false otherwise.
2949  llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
2950
2951  /// \brief Whether we have already loaded known namespaces from an extenal
2952  /// source.
2953  bool LoadedExternalKnownNamespaces;
2954
2955  /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
2956  /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
2957  /// should be skipped entirely.
2958  std::unique_ptr<TypoCorrectionConsumer>
2959  makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
2960                             Sema::LookupNameKind LookupKind, Scope *S,
2961                             CXXScopeSpec *SS,
2962                             std::unique_ptr<CorrectionCandidateCallback> CCC,
2963                             DeclContext *MemberContext, bool EnteringContext,
2964                             const ObjCObjectPointerType *OPT,
2965                             bool ErrorRecovery);
2966
2967public:
2968  const TypoExprState &getTypoExprState(TypoExpr *TE) const;
2969
2970  /// \brief Clears the state of the given TypoExpr.
2971  void clearDelayedTypo(TypoExpr *TE);
2972
2973  /// \brief Look up a name, looking for a single declaration.  Return
2974  /// null if the results were absent, ambiguous, or overloaded.
2975  ///
2976  /// It is preferable to use the elaborated form and explicitly handle
2977  /// ambiguity and overloaded.
2978  NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
2979                              SourceLocation Loc,
2980                              LookupNameKind NameKind,
2981                              RedeclarationKind Redecl
2982                                = NotForRedeclaration);
2983  bool LookupName(LookupResult &R, Scope *S,
2984                  bool AllowBuiltinCreation = false);
2985  bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2986                           bool InUnqualifiedLookup = false);
2987  bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2988                           CXXScopeSpec &SS);
2989  bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2990                        bool AllowBuiltinCreation = false,
2991                        bool EnteringContext = false);
2992  ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
2993                                   RedeclarationKind Redecl
2994                                     = NotForRedeclaration);
2995  bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
2996
2997  void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2998                                    QualType T1, QualType T2,
2999                                    UnresolvedSetImpl &Functions);
3000
3001  LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
3002                                 SourceLocation GnuLabelLoc = SourceLocation());
3003
3004  DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
3005  CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
3006  CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
3007                                               unsigned Quals);
3008  CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
3009                                         bool RValueThis, unsigned ThisQuals);
3010  CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
3011                                              unsigned Quals);
3012  CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
3013                                        bool RValueThis, unsigned ThisQuals);
3014  CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
3015
3016  bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
3017  LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
3018                                                    ArrayRef<QualType> ArgTys,
3019                                                    bool AllowRaw,
3020                                                    bool AllowTemplate,
3021                                                    bool AllowStringTemplate);
3022  bool isKnownName(StringRef name);
3023
3024  void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3025                               ArrayRef<Expr *> Args, ADLResult &Functions);
3026
3027  void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3028                          VisibleDeclConsumer &Consumer,
3029                          bool IncludeGlobalScope = true);
3030  void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3031                          VisibleDeclConsumer &Consumer,
3032                          bool IncludeGlobalScope = true);
3033
3034  enum CorrectTypoKind {
3035    CTK_NonError,     // CorrectTypo used in a non error recovery situation.
3036    CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
3037  };
3038
3039  TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
3040                             Sema::LookupNameKind LookupKind,
3041                             Scope *S, CXXScopeSpec *SS,
3042                             std::unique_ptr<CorrectionCandidateCallback> CCC,
3043                             CorrectTypoKind Mode,
3044                             DeclContext *MemberContext = nullptr,
3045                             bool EnteringContext = false,
3046                             const ObjCObjectPointerType *OPT = nullptr,
3047                             bool RecordFailure = true);
3048
3049  TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
3050                               Sema::LookupNameKind LookupKind, Scope *S,
3051                               CXXScopeSpec *SS,
3052                               std::unique_ptr<CorrectionCandidateCallback> CCC,
3053                               TypoDiagnosticGenerator TDG,
3054                               TypoRecoveryCallback TRC, CorrectTypoKind Mode,
3055                               DeclContext *MemberContext = nullptr,
3056                               bool EnteringContext = false,
3057                               const ObjCObjectPointerType *OPT = nullptr);
3058
3059  /// \brief Process any TypoExprs in the given Expr and its children,
3060  /// generating diagnostics as appropriate and returning a new Expr if there
3061  /// were typos that were all successfully corrected and ExprError if one or
3062  /// more typos could not be corrected.
3063  ///
3064  /// \param E The Expr to check for TypoExprs.
3065  ///
3066  /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
3067  /// initializer.
3068  ///
3069  /// \param Filter A function applied to a newly rebuilt Expr to determine if
3070  /// it is an acceptable/usable result from a single combination of typo
3071  /// corrections. As long as the filter returns ExprError, different
3072  /// combinations of corrections will be tried until all are exhausted.
3073  ExprResult
3074  CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
3075                            llvm::function_ref<ExprResult(Expr *)> Filter =
3076                                [](Expr *E) -> ExprResult { return E; });
3077
3078  ExprResult
3079  CorrectDelayedTyposInExpr(Expr *E,
3080                            llvm::function_ref<ExprResult(Expr *)> Filter) {
3081    return CorrectDelayedTyposInExpr(E, nullptr, Filter);
3082  }
3083
3084  ExprResult
3085  CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
3086                            llvm::function_ref<ExprResult(Expr *)> Filter =
3087                                [](Expr *E) -> ExprResult { return E; }) {
3088    return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
3089  }
3090
3091  ExprResult
3092  CorrectDelayedTyposInExpr(ExprResult ER,
3093                            llvm::function_ref<ExprResult(Expr *)> Filter) {
3094    return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
3095  }
3096
3097  void diagnoseTypo(const TypoCorrection &Correction,
3098                    const PartialDiagnostic &TypoDiag,
3099                    bool ErrorRecovery = true);
3100
3101  void diagnoseTypo(const TypoCorrection &Correction,
3102                    const PartialDiagnostic &TypoDiag,
3103                    const PartialDiagnostic &PrevNote,
3104                    bool ErrorRecovery = true);
3105
3106  void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
3107                                          ArrayRef<Expr *> Args,
3108                                   AssociatedNamespaceSet &AssociatedNamespaces,
3109                                   AssociatedClassSet &AssociatedClasses);
3110
3111  void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
3112                            bool ConsiderLinkage, bool AllowInlineNamespace);
3113
3114  void DiagnoseAmbiguousLookup(LookupResult &Result);
3115  //@}
3116
3117  ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
3118                                          SourceLocation IdLoc,
3119                                          bool TypoCorrection = false);
3120  NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
3121                                 Scope *S, bool ForRedeclaration,
3122                                 SourceLocation Loc);
3123  NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
3124                                      Scope *S);
3125  void AddKnownFunctionAttributes(FunctionDecl *FD);
3126
3127  // More parsing and symbol table subroutines.
3128
3129  void ProcessPragmaWeak(Scope *S, Decl *D);
3130  // Decl attributes - this routine is the top level dispatcher.
3131  void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
3132  // Helper for delayed proccessing of attributes.
3133  void ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList);
3134  void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
3135                                bool IncludeCXX11Attributes = true);
3136  bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
3137                                      const AttributeList *AttrList);
3138
3139  void checkUnusedDeclAttributes(Declarator &D);
3140
3141  /// Determine if type T is a valid subject for a nonnull and similar
3142  /// attributes. By default, we look through references (the behavior used by
3143  /// nonnull), but if the second parameter is true, then we treat a reference
3144  /// type as valid.
3145  bool isValidPointerAttrType(QualType T, bool RefOkay = false);
3146
3147  bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
3148  bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3149                            const FunctionDecl *FD = nullptr);
3150  bool CheckNoReturnAttr(const AttributeList &attr);
3151  bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
3152                                      unsigned ArgNum, StringRef &Str,
3153                                      SourceLocation *ArgLocation = nullptr);
3154  bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
3155  void checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
3156  bool checkMSInheritanceAttrOnDefinition(
3157      CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3158      MSInheritanceAttr::Spelling SemanticSpelling);
3159
3160  void CheckAlignasUnderalignment(Decl *D);
3161
3162  /// Adjust the calling convention of a method to be the ABI default if it
3163  /// wasn't specified explicitly.  This handles method types formed from
3164  /// function type typedefs and typename template arguments.
3165  void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
3166                              SourceLocation Loc);
3167
3168  // Check if there is an explicit attribute, but only look through parens.
3169  // The intent is to look for an attribute on the current declarator, but not
3170  // one that came from a typedef.
3171  bool hasExplicitCallingConv(QualType &T);
3172
3173  /// Get the outermost AttributedType node that sets a calling convention.
3174  /// Valid types should not have multiple attributes with different CCs.
3175  const AttributedType *getCallingConvAttributedType(QualType T) const;
3176
3177  /// Check whether a nullability type specifier can be added to the given
3178  /// type.
3179  ///
3180  /// \param type The type to which the nullability specifier will be
3181  /// added. On success, this type will be updated appropriately.
3182  ///
3183  /// \param nullability The nullability specifier to add.
3184  ///
3185  /// \param nullabilityLoc The location of the nullability specifier.
3186  ///
3187  /// \param isContextSensitive Whether this nullability specifier was
3188  /// written as a context-sensitive keyword (in an Objective-C
3189  /// method) or an Objective-C property attribute, rather than as an
3190  /// underscored type specifier.
3191  ///
3192  /// \param allowArrayTypes Whether to accept nullability specifiers on an
3193  /// array type (e.g., because it will decay to a pointer).
3194  ///
3195  /// \returns true if nullability cannot be applied, false otherwise.
3196  bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
3197                                     SourceLocation nullabilityLoc,
3198                                     bool isContextSensitive,
3199                                     bool allowArrayTypes);
3200
3201  /// \brief Stmt attributes - this routine is the top level dispatcher.
3202  StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
3203                                   SourceRange Range);
3204
3205  void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
3206                                   ObjCMethodDecl *MethodDecl,
3207                                   bool IsProtocolMethodDecl);
3208
3209  void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
3210                                   ObjCMethodDecl *Overridden,
3211                                   bool IsProtocolMethodDecl);
3212
3213  /// WarnExactTypedMethods - This routine issues a warning if method
3214  /// implementation declaration matches exactly that of its declaration.
3215  void WarnExactTypedMethods(ObjCMethodDecl *Method,
3216                             ObjCMethodDecl *MethodDecl,
3217                             bool IsProtocolMethodDecl);
3218
3219  typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
3220
3221  /// CheckImplementationIvars - This routine checks if the instance variables
3222  /// listed in the implelementation match those listed in the interface.
3223  void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
3224                                ObjCIvarDecl **Fields, unsigned nIvars,
3225                                SourceLocation Loc);
3226
3227  /// ImplMethodsVsClassMethods - This is main routine to warn if any method
3228  /// remains unimplemented in the class or category \@implementation.
3229  void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
3230                                 ObjCContainerDecl* IDecl,
3231                                 bool IncompleteImpl = false);
3232
3233  /// DiagnoseUnimplementedProperties - This routine warns on those properties
3234  /// which must be implemented by this implementation.
3235  void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
3236                                       ObjCContainerDecl *CDecl,
3237                                       bool SynthesizeProperties);
3238
3239  /// Diagnose any null-resettable synthesized setters.
3240  void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
3241
3242  /// DefaultSynthesizeProperties - This routine default synthesizes all
3243  /// properties which must be synthesized in the class's \@implementation.
3244  void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
3245                                    ObjCInterfaceDecl *IDecl);
3246  void DefaultSynthesizeProperties(Scope *S, Decl *D);
3247
3248  /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
3249  /// an ivar synthesized for 'Method' and 'Method' is a property accessor
3250  /// declared in class 'IFace'.
3251  bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
3252                                      ObjCMethodDecl *Method, ObjCIvarDecl *IV);
3253
3254  /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
3255  /// backs the property is not used in the property's accessor.
3256  void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3257                                           const ObjCImplementationDecl *ImplD);
3258
3259  /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
3260  /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
3261  /// It also returns ivar's property on success.
3262  ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3263                                               const ObjCPropertyDecl *&PDecl) const;
3264
3265  /// Called by ActOnProperty to handle \@property declarations in
3266  /// class extensions.
3267  ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
3268                      SourceLocation AtLoc,
3269                      SourceLocation LParenLoc,
3270                      FieldDeclarator &FD,
3271                      Selector GetterSel,
3272                      SourceLocation GetterNameLoc,
3273                      Selector SetterSel,
3274                      SourceLocation SetterNameLoc,
3275                      const bool isReadWrite,
3276                      unsigned &Attributes,
3277                      const unsigned AttributesAsWritten,
3278                      QualType T,
3279                      TypeSourceInfo *TSI,
3280                      tok::ObjCKeywordKind MethodImplKind);
3281
3282  /// Called by ActOnProperty and HandlePropertyInClassExtension to
3283  /// handle creating the ObjcPropertyDecl for a category or \@interface.
3284  ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
3285                                       ObjCContainerDecl *CDecl,
3286                                       SourceLocation AtLoc,
3287                                       SourceLocation LParenLoc,
3288                                       FieldDeclarator &FD,
3289                                       Selector GetterSel,
3290                                       SourceLocation GetterNameLoc,
3291                                       Selector SetterSel,
3292                                       SourceLocation SetterNameLoc,
3293                                       const bool isReadWrite,
3294                                       const unsigned Attributes,
3295                                       const unsigned AttributesAsWritten,
3296                                       QualType T,
3297                                       TypeSourceInfo *TSI,
3298                                       tok::ObjCKeywordKind MethodImplKind,
3299                                       DeclContext *lexicalDC = nullptr);
3300
3301  /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
3302  /// warning) when atomic property has one but not the other user-declared
3303  /// setter or getter.
3304  void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
3305                                       ObjCInterfaceDecl* IDecl);
3306
3307  void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
3308
3309  void DiagnoseMissingDesignatedInitOverrides(
3310                                          const ObjCImplementationDecl *ImplD,
3311                                          const ObjCInterfaceDecl *IFD);
3312
3313  void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
3314
3315  enum MethodMatchStrategy {
3316    MMS_loose,
3317    MMS_strict
3318  };
3319
3320  /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
3321  /// true, or false, accordingly.
3322  bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
3323                                  const ObjCMethodDecl *PrevMethod,
3324                                  MethodMatchStrategy strategy = MMS_strict);
3325
3326  /// MatchAllMethodDeclarations - Check methods declaraed in interface or
3327  /// or protocol against those declared in their implementations.
3328  void MatchAllMethodDeclarations(const SelectorSet &InsMap,
3329                                  const SelectorSet &ClsMap,
3330                                  SelectorSet &InsMapSeen,
3331                                  SelectorSet &ClsMapSeen,
3332                                  ObjCImplDecl* IMPDecl,
3333                                  ObjCContainerDecl* IDecl,
3334                                  bool &IncompleteImpl,
3335                                  bool ImmediateClass,
3336                                  bool WarnCategoryMethodImpl=false);
3337
3338  /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
3339  /// category matches with those implemented in its primary class and
3340  /// warns each time an exact match is found.
3341  void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
3342
3343  /// \brief Add the given method to the list of globally-known methods.
3344  void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
3345
3346private:
3347  /// AddMethodToGlobalPool - Add an instance or factory method to the global
3348  /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
3349  void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
3350
3351  /// LookupMethodInGlobalPool - Returns the instance or factory method and
3352  /// optionally warns if there are multiple signatures.
3353  ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3354                                           bool receiverIdOrClass,
3355                                           bool instance);
3356
3357public:
3358  /// \brief - Returns instance or factory methods in global method pool for
3359  /// given selector. It checks the desired kind first, if none is found, and
3360  /// parameter checkTheOther is set, it then checks the other kind. If no such
3361  /// method or only one method is found, function returns false; otherwise, it
3362  /// returns true.
3363  bool
3364  CollectMultipleMethodsInGlobalPool(Selector Sel,
3365                                     SmallVectorImpl<ObjCMethodDecl*>& Methods,
3366                                     bool InstanceFirst, bool CheckTheOther,
3367                                     const ObjCObjectType *TypeBound = nullptr);
3368
3369  bool
3370  AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3371                                 SourceRange R, bool receiverIdOrClass,
3372                                 SmallVectorImpl<ObjCMethodDecl*>& Methods);
3373
3374  void
3375  DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3376                                     Selector Sel, SourceRange R,
3377                                     bool receiverIdOrClass);
3378
3379private:
3380  /// \brief - Returns a selector which best matches given argument list or
3381  /// nullptr if none could be found
3382  ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
3383                                   bool IsInstance,
3384                                   SmallVectorImpl<ObjCMethodDecl*>& Methods);
3385
3386
3387  /// \brief Record the typo correction failure and return an empty correction.
3388  TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
3389                                  bool RecordFailure = true) {
3390    if (RecordFailure)
3391      TypoCorrectionFailures[Typo].insert(TypoLoc);
3392    return TypoCorrection();
3393  }
3394
3395public:
3396  /// AddInstanceMethodToGlobalPool - All instance methods in a translation
3397  /// unit are added to a global pool. This allows us to efficiently associate
3398  /// a selector with a method declaraation for purposes of typechecking
3399  /// messages sent to "id" (where the class of the object is unknown).
3400  void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3401    AddMethodToGlobalPool(Method, impl, /*instance*/true);
3402  }
3403
3404  /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
3405  void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
3406    AddMethodToGlobalPool(Method, impl, /*instance*/false);
3407  }
3408
3409  /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
3410  /// pool.
3411  void AddAnyMethodToGlobalPool(Decl *D);
3412
3413  /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
3414  /// there are multiple signatures.
3415  ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
3416                                                   bool receiverIdOrClass=false) {
3417    return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3418                                    /*instance*/true);
3419  }
3420
3421  /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
3422  /// there are multiple signatures.
3423  ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
3424                                                  bool receiverIdOrClass=false) {
3425    return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
3426                                    /*instance*/false);
3427  }
3428
3429  const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
3430                              QualType ObjectType=QualType());
3431  /// LookupImplementedMethodInGlobalPool - Returns the method which has an
3432  /// implementation.
3433  ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
3434
3435  /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3436  /// initialization.
3437  void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3438                                  SmallVectorImpl<ObjCIvarDecl*> &Ivars);
3439
3440  //===--------------------------------------------------------------------===//
3441  // Statement Parsing Callbacks: SemaStmt.cpp.
3442public:
3443  class FullExprArg {
3444  public:
3445    FullExprArg() : E(nullptr) { }
3446    FullExprArg(Sema &actions) : E(nullptr) { }
3447
3448    ExprResult release() {
3449      return E;
3450    }
3451
3452    Expr *get() const { return E; }
3453
3454    Expr *operator->() {
3455      return E;
3456    }
3457
3458  private:
3459    // FIXME: No need to make the entire Sema class a friend when it's just
3460    // Sema::MakeFullExpr that needs access to the constructor below.
3461    friend class Sema;
3462
3463    explicit FullExprArg(Expr *expr) : E(expr) {}
3464
3465    Expr *E;
3466  };
3467
3468  FullExprArg MakeFullExpr(Expr *Arg) {
3469    return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
3470  }
3471  FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
3472    return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
3473  }
3474  FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
3475    ExprResult FE =
3476      ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
3477                          /*DiscardedValue*/ true);
3478    return FullExprArg(FE.get());
3479  }
3480
3481  StmtResult ActOnExprStmt(ExprResult Arg);
3482  StmtResult ActOnExprStmtError();
3483
3484  StmtResult ActOnNullStmt(SourceLocation SemiLoc,
3485                           bool HasLeadingEmptyMacro = false);
3486
3487  void ActOnStartOfCompoundStmt();
3488  void ActOnFinishOfCompoundStmt();
3489  StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
3490                               ArrayRef<Stmt *> Elts, bool isStmtExpr);
3491
3492  /// \brief A RAII object to enter scope of a compound statement.
3493  class CompoundScopeRAII {
3494  public:
3495    CompoundScopeRAII(Sema &S): S(S) {
3496      S.ActOnStartOfCompoundStmt();
3497    }
3498
3499    ~CompoundScopeRAII() {
3500      S.ActOnFinishOfCompoundStmt();
3501    }
3502
3503  private:
3504    Sema &S;
3505  };
3506
3507  /// An RAII helper that pops function a function scope on exit.
3508  struct FunctionScopeRAII {
3509    Sema &S;
3510    bool Active;
3511    FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
3512    ~FunctionScopeRAII() {
3513      if (Active)
3514        S.PopFunctionScopeInfo();
3515    }
3516    void disable() { Active = false; }
3517  };
3518
3519  StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
3520                                   SourceLocation StartLoc,
3521                                   SourceLocation EndLoc);
3522  void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
3523  StmtResult ActOnForEachLValueExpr(Expr *E);
3524  StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
3525                                   SourceLocation DotDotDotLoc, Expr *RHSVal,
3526                                   SourceLocation ColonLoc);
3527  void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
3528
3529  StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
3530                                      SourceLocation ColonLoc,
3531                                      Stmt *SubStmt, Scope *CurScope);
3532  StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
3533                            SourceLocation ColonLoc, Stmt *SubStmt);
3534
3535  StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
3536                                 ArrayRef<const Attr*> Attrs,
3537                                 Stmt *SubStmt);
3538
3539  class ConditionResult;
3540  StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3541                         Stmt *InitStmt,
3542                         ConditionResult Cond, Stmt *ThenVal,
3543                         SourceLocation ElseLoc, Stmt *ElseVal);
3544  StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
3545                         Stmt *InitStmt,
3546                         ConditionResult Cond, Stmt *ThenVal,
3547                         SourceLocation ElseLoc, Stmt *ElseVal);
3548  StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
3549                                    Stmt *InitStmt,
3550                                    ConditionResult Cond);
3551  StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
3552                                           Stmt *Switch, Stmt *Body);
3553  StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
3554                            Stmt *Body);
3555  StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
3556                         SourceLocation WhileLoc, SourceLocation CondLParen,
3557                         Expr *Cond, SourceLocation CondRParen);
3558
3559  StmtResult ActOnForStmt(SourceLocation ForLoc,
3560                          SourceLocation LParenLoc,
3561                          Stmt *First,
3562                          ConditionResult Second,
3563                          FullExprArg Third,
3564                          SourceLocation RParenLoc,
3565                          Stmt *Body);
3566  ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
3567                                           Expr *collection);
3568  StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
3569                                        Stmt *First, Expr *collection,
3570                                        SourceLocation RParenLoc);
3571  StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
3572
3573  enum BuildForRangeKind {
3574    /// Initial building of a for-range statement.
3575    BFRK_Build,
3576    /// Instantiation or recovery rebuild of a for-range statement. Don't
3577    /// attempt any typo-correction.
3578    BFRK_Rebuild,
3579    /// Determining whether a for-range statement could be built. Avoid any
3580    /// unnecessary or irreversible actions.
3581    BFRK_Check
3582  };
3583
3584  StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
3585                                  SourceLocation CoawaitLoc,
3586                                  Stmt *LoopVar,
3587                                  SourceLocation ColonLoc, Expr *Collection,
3588                                  SourceLocation RParenLoc,
3589                                  BuildForRangeKind Kind);
3590  StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
3591                                  SourceLocation CoawaitLoc,
3592                                  SourceLocation ColonLoc,
3593                                  Stmt *RangeDecl, Stmt *Begin, Stmt *End,
3594                                  Expr *Cond, Expr *Inc,
3595                                  Stmt *LoopVarDecl,
3596                                  SourceLocation RParenLoc,
3597                                  BuildForRangeKind Kind);
3598  StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
3599
3600  StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
3601                           SourceLocation LabelLoc,
3602                           LabelDecl *TheDecl);
3603  StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
3604                                   SourceLocation StarLoc,
3605                                   Expr *DestExp);
3606  StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
3607  StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
3608
3609  void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3610                                CapturedRegionKind Kind, unsigned NumParams);
3611  typedef std::pair<StringRef, QualType> CapturedParamNameType;
3612  void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3613                                CapturedRegionKind Kind,
3614                                ArrayRef<CapturedParamNameType> Params);
3615  StmtResult ActOnCapturedRegionEnd(Stmt *S);
3616  void ActOnCapturedRegionError();
3617  RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
3618                                           SourceLocation Loc,
3619                                           unsigned NumParams);
3620  VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
3621                                   bool AllowParamOrMoveConstructible);
3622  bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
3623                              bool AllowParamOrMoveConstructible);
3624
3625  StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3626                             Scope *CurScope);
3627  StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3628  StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
3629
3630  StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
3631                             bool IsVolatile, unsigned NumOutputs,
3632                             unsigned NumInputs, IdentifierInfo **Names,
3633                             MultiExprArg Constraints, MultiExprArg Exprs,
3634                             Expr *AsmString, MultiExprArg Clobbers,
3635                             SourceLocation RParenLoc);
3636
3637  ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
3638                                       SourceLocation TemplateKWLoc,
3639                                       UnqualifiedId &Id,
3640                                       llvm::InlineAsmIdentifierInfo &Info,
3641                                       bool IsUnevaluatedContext);
3642  bool LookupInlineAsmField(StringRef Base, StringRef Member,
3643                            unsigned &Offset, SourceLocation AsmLoc);
3644  ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
3645                                         llvm::InlineAsmIdentifierInfo &Info,
3646                                         SourceLocation AsmLoc);
3647  StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
3648                            ArrayRef<Token> AsmToks,
3649                            StringRef AsmString,
3650                            unsigned NumOutputs, unsigned NumInputs,
3651                            ArrayRef<StringRef> Constraints,
3652                            ArrayRef<StringRef> Clobbers,
3653                            ArrayRef<Expr*> Exprs,
3654                            SourceLocation EndLoc);
3655  LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
3656                                   SourceLocation Location,
3657                                   bool AlwaysCreate);
3658
3659  VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
3660                                  SourceLocation StartLoc,
3661                                  SourceLocation IdLoc, IdentifierInfo *Id,
3662                                  bool Invalid = false);
3663
3664  Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
3665
3666  StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
3667                                  Decl *Parm, Stmt *Body);
3668
3669  StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
3670
3671  StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3672                                MultiStmtArg Catch, Stmt *Finally);
3673
3674  StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
3675  StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3676                                  Scope *CurScope);
3677  ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
3678                                            Expr *operand);
3679  StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
3680                                         Expr *SynchExpr,
3681                                         Stmt *SynchBody);
3682
3683  StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
3684
3685  VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
3686                                     SourceLocation StartLoc,
3687                                     SourceLocation IdLoc,
3688                                     IdentifierInfo *Id);
3689
3690  Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
3691
3692  StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
3693                                Decl *ExDecl, Stmt *HandlerBlock);
3694  StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3695                              ArrayRef<Stmt *> Handlers);
3696
3697  StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
3698                              SourceLocation TryLoc, Stmt *TryBlock,
3699                              Stmt *Handler);
3700  StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
3701                                 Expr *FilterExpr,
3702                                 Stmt *Block);
3703  void ActOnStartSEHFinallyBlock();
3704  void ActOnAbortSEHFinallyBlock();
3705  StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
3706  StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
3707
3708  void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
3709
3710  bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
3711
3712  /// \brief If it's a file scoped decl that must warn if not used, keep track
3713  /// of it.
3714  void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
3715
3716  /// DiagnoseUnusedExprResult - If the statement passed in is an expression
3717  /// whose result is unused, warn.
3718  void DiagnoseUnusedExprResult(const Stmt *S);
3719  void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
3720  void DiagnoseUnusedDecl(const NamedDecl *ND);
3721
3722  /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
3723  /// statement as a \p Body, and it is located on the same line.
3724  ///
3725  /// This helps prevent bugs due to typos, such as:
3726  ///     if (condition);
3727  ///       do_stuff();
3728  void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
3729                             const Stmt *Body,
3730                             unsigned DiagID);
3731
3732  /// Warn if a for/while loop statement \p S, which is followed by
3733  /// \p PossibleBody, has a suspicious null statement as a body.
3734  void DiagnoseEmptyLoopBody(const Stmt *S,
3735                             const Stmt *PossibleBody);
3736
3737  /// Warn if a value is moved to itself.
3738  void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
3739                        SourceLocation OpLoc);
3740
3741  /// \brief Warn if we're implicitly casting from a _Nullable pointer type to a
3742  /// _Nonnull one.
3743  void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
3744                                           SourceLocation Loc);
3745
3746  ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
3747    return DelayedDiagnostics.push(pool);
3748  }
3749  void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
3750
3751  typedef ProcessingContextState ParsingClassState;
3752  ParsingClassState PushParsingClass() {
3753    return DelayedDiagnostics.pushUndelayed();
3754  }
3755  void PopParsingClass(ParsingClassState state) {
3756    DelayedDiagnostics.popUndelayed(state);
3757  }
3758
3759  void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
3760
3761  void EmitAvailabilityWarning(AvailabilityResult AR, NamedDecl *D,
3762                               StringRef Message, SourceLocation Loc,
3763                               const ObjCInterfaceDecl *UnknownObjCClass,
3764                               const ObjCPropertyDecl *ObjCProperty,
3765                               bool ObjCPropertyAccess);
3766
3767  bool makeUnavailableInSystemHeader(SourceLocation loc,
3768                                     UnavailableAttr::ImplicitReason reason);
3769
3770  /// \brief Issue any -Wunguarded-availability warnings in \c FD
3771  void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
3772
3773  //===--------------------------------------------------------------------===//
3774  // Expression Parsing Callbacks: SemaExpr.cpp.
3775
3776  bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
3777  bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3778                         const ObjCInterfaceDecl *UnknownObjCClass=nullptr,
3779                         bool ObjCPropertyAccess=false);
3780  void NoteDeletedFunction(FunctionDecl *FD);
3781  void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
3782  std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3783  bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3784                                        ObjCMethodDecl *Getter,
3785                                        SourceLocation Loc);
3786  void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3787                             ArrayRef<Expr *> Args);
3788
3789  void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3790                                       Decl *LambdaContextDecl = nullptr,
3791                                       bool IsDecltype = false);
3792  enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3793  void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3794                                       ReuseLambdaContextDecl_t,
3795                                       bool IsDecltype = false);
3796  void PopExpressionEvaluationContext();
3797
3798  void DiscardCleanupsInEvaluationContext();
3799
3800  ExprResult TransformToPotentiallyEvaluated(Expr *E);
3801  ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3802
3803  ExprResult ActOnConstantExpression(ExprResult Res);
3804
3805  // Functions for marking a declaration referenced.  These functions also
3806  // contain the relevant logic for marking if a reference to a function or
3807  // variable is an odr-use (in the C++11 sense).  There are separate variants
3808  // for expressions referring to a decl; these exist because odr-use marking
3809  // needs to be delayed for some constant variables when we build one of the
3810  // named expressions.
3811  //
3812  // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
3813  // should usually be true. This only needs to be set to false if the lack of
3814  // odr-use cannot be determined from the current context (for instance,
3815  // because the name denotes a virtual function and was written without an
3816  // explicit nested-name-specifier).
3817  void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
3818  void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
3819                              bool MightBeOdrUse = true);
3820  void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
3821  void MarkDeclRefReferenced(DeclRefExpr *E);
3822  void MarkMemberReferenced(MemberExpr *E);
3823
3824  void UpdateMarkingForLValueToRValue(Expr *E);
3825  void CleanupVarDeclMarking();
3826
3827  enum TryCaptureKind {
3828    TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
3829  };
3830
3831  /// \brief Try to capture the given variable.
3832  ///
3833  /// \param Var The variable to capture.
3834  ///
3835  /// \param Loc The location at which the capture occurs.
3836  ///
3837  /// \param Kind The kind of capture, which may be implicit (for either a
3838  /// block or a lambda), or explicit by-value or by-reference (for a lambda).
3839  ///
3840  /// \param EllipsisLoc The location of the ellipsis, if one is provided in
3841  /// an explicit lambda capture.
3842  ///
3843  /// \param BuildAndDiagnose Whether we are actually supposed to add the
3844  /// captures or diagnose errors. If false, this routine merely check whether
3845  /// the capture can occur without performing the capture itself or complaining
3846  /// if the variable cannot be captured.
3847  ///
3848  /// \param CaptureType Will be set to the type of the field used to capture
3849  /// this variable in the innermost block or lambda. Only valid when the
3850  /// variable can be captured.
3851  ///
3852  /// \param DeclRefType Will be set to the type of a reference to the capture
3853  /// from within the current scope. Only valid when the variable can be
3854  /// captured.
3855  ///
3856  /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
3857  /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
3858  /// This is useful when enclosing lambdas must speculatively capture
3859  /// variables that may or may not be used in certain specializations of
3860  /// a nested generic lambda.
3861  ///
3862  /// \returns true if an error occurred (i.e., the variable cannot be
3863  /// captured) and false if the capture succeeded.
3864  bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3865                          SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3866                          QualType &CaptureType,
3867                          QualType &DeclRefType,
3868                          const unsigned *const FunctionScopeIndexToStopAt);
3869
3870  /// \brief Try to capture the given variable.
3871  bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3872                          TryCaptureKind Kind = TryCapture_Implicit,
3873                          SourceLocation EllipsisLoc = SourceLocation());
3874
3875  /// \brief Checks if the variable must be captured.
3876  bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
3877
3878  /// \brief Given a variable, determine the type that a reference to that
3879  /// variable will have in the given scope.
3880  QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
3881
3882  /// Mark all of the declarations referenced within a particular AST node as
3883  /// referenced. Used when template instantiation instantiates a non-dependent
3884  /// type -- entities referenced by the type are now referenced.
3885  void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
3886  void MarkDeclarationsReferencedInExpr(Expr *E,
3887                                        bool SkipLocalVariables = false);
3888
3889  /// \brief Try to recover by turning the given expression into a
3890  /// call.  Returns true if recovery was attempted or an error was
3891  /// emitted; this may also leave the ExprResult invalid.
3892  bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
3893                            bool ForceComplain = false,
3894                            bool (*IsPlausibleResult)(QualType) = nullptr);
3895
3896  /// \brief Figure out if an expression could be turned into a call.
3897  bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
3898                     UnresolvedSetImpl &NonTemplateOverloads);
3899
3900  /// \brief Conditionally issue a diagnostic based on the current
3901  /// evaluation context.
3902  ///
3903  /// \param Statement If Statement is non-null, delay reporting the
3904  /// diagnostic until the function body is parsed, and then do a basic
3905  /// reachability analysis to determine if the statement is reachable.
3906  /// If it is unreachable, the diagnostic will not be emitted.
3907  bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
3908                           const PartialDiagnostic &PD);
3909
3910  // Primary Expressions.
3911  SourceRange getExprRange(Expr *E) const;
3912
3913  ExprResult ActOnIdExpression(
3914      Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3915      UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
3916      std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
3917      bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
3918
3919  void DecomposeUnqualifiedId(const UnqualifiedId &Id,
3920                              TemplateArgumentListInfo &Buffer,
3921                              DeclarationNameInfo &NameInfo,
3922                              const TemplateArgumentListInfo *&TemplateArgs);
3923
3924  bool
3925  DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
3926                      std::unique_ptr<CorrectionCandidateCallback> CCC,
3927                      TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3928                      ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
3929
3930  ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
3931                                IdentifierInfo *II,
3932                                bool AllowBuiltinCreation=false);
3933
3934  ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
3935                                        SourceLocation TemplateKWLoc,
3936                                        const DeclarationNameInfo &NameInfo,
3937                                        bool isAddressOfOperand,
3938                                const TemplateArgumentListInfo *TemplateArgs);
3939
3940  ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
3941                              ExprValueKind VK,
3942                              SourceLocation Loc,
3943                              const CXXScopeSpec *SS = nullptr);
3944  ExprResult
3945  BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
3946                   const DeclarationNameInfo &NameInfo,
3947                   const CXXScopeSpec *SS = nullptr,
3948                   NamedDecl *FoundD = nullptr,
3949                   const TemplateArgumentListInfo *TemplateArgs = nullptr);
3950  ExprResult
3951  BuildAnonymousStructUnionMemberReference(
3952      const CXXScopeSpec &SS,
3953      SourceLocation nameLoc,
3954      IndirectFieldDecl *indirectField,
3955      DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
3956      Expr *baseObjectExpr = nullptr,
3957      SourceLocation opLoc = SourceLocation());
3958
3959  ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
3960                                             SourceLocation TemplateKWLoc,
3961                                             LookupResult &R,
3962                                const TemplateArgumentListInfo *TemplateArgs,
3963                                             const Scope *S);
3964  ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
3965                                     SourceLocation TemplateKWLoc,
3966                                     LookupResult &R,
3967                                const TemplateArgumentListInfo *TemplateArgs,
3968                                     bool IsDefiniteInstance,
3969                                     const Scope *S);
3970  bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
3971                                  const LookupResult &R,
3972                                  bool HasTrailingLParen);
3973
3974  ExprResult
3975  BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
3976                                    const DeclarationNameInfo &NameInfo,
3977                                    bool IsAddressOfOperand, const Scope *S,
3978                                    TypeSourceInfo **RecoveryTSI = nullptr);
3979
3980  ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
3981                                       SourceLocation TemplateKWLoc,
3982                                const DeclarationNameInfo &NameInfo,
3983                                const TemplateArgumentListInfo *TemplateArgs);
3984
3985  ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3986                                      LookupResult &R,
3987                                      bool NeedsADL,
3988                                      bool AcceptInvalidDecl = false);
3989  ExprResult BuildDeclarationNameExpr(
3990      const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3991      NamedDecl *FoundD = nullptr,
3992      const TemplateArgumentListInfo *TemplateArgs = nullptr,
3993      bool AcceptInvalidDecl = false);
3994
3995  ExprResult BuildLiteralOperatorCall(LookupResult &R,
3996                      DeclarationNameInfo &SuffixInfo,
3997                      ArrayRef<Expr *> Args,
3998                      SourceLocation LitEndLoc,
3999                      TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4000
4001  ExprResult BuildPredefinedExpr(SourceLocation Loc,
4002                                 PredefinedExpr::IdentType IT);
4003  ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4004  ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4005
4006  bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4007
4008  ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4009  ExprResult ActOnCharacterConstant(const Token &Tok,
4010                                    Scope *UDLScope = nullptr);
4011  ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4012  ExprResult ActOnParenListExpr(SourceLocation L,
4013                                SourceLocation R,
4014                                MultiExprArg Val);
4015
4016  /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4017  /// fragments (e.g. "foo" "bar" L"baz").
4018  ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4019                                Scope *UDLScope = nullptr);
4020
4021  ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4022                                       SourceLocation DefaultLoc,
4023                                       SourceLocation RParenLoc,
4024                                       Expr *ControllingExpr,
4025                                       ArrayRef<ParsedType> ArgTypes,
4026                                       ArrayRef<Expr *> ArgExprs);
4027  ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4028                                        SourceLocation DefaultLoc,
4029                                        SourceLocation RParenLoc,
4030                                        Expr *ControllingExpr,
4031                                        ArrayRef<TypeSourceInfo *> Types,
4032                                        ArrayRef<Expr *> Exprs);
4033
4034  // Binary/Unary Operators.  'Tok' is the token for the operator.
4035  ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4036                                  Expr *InputExpr);
4037  ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4038                          UnaryOperatorKind Opc, Expr *Input);
4039  ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4040                          tok::TokenKind Op, Expr *Input);
4041
4042  QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4043
4044  ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4045                                            SourceLocation OpLoc,
4046                                            UnaryExprOrTypeTrait ExprKind,
4047                                            SourceRange R);
4048  ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4049                                            UnaryExprOrTypeTrait ExprKind);
4050  ExprResult
4051    ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4052                                  UnaryExprOrTypeTrait ExprKind,
4053                                  bool IsType, void *TyOrEx,
4054                                  SourceRange ArgRange);
4055
4056  ExprResult CheckPlaceholderExpr(Expr *E);
4057  bool CheckVecStepExpr(Expr *E);
4058
4059  bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4060  bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4061                                        SourceRange ExprRange,
4062                                        UnaryExprOrTypeTrait ExprKind);
4063  ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4064                                          SourceLocation OpLoc,
4065                                          IdentifierInfo &Name,
4066                                          SourceLocation NameLoc,
4067                                          SourceLocation RParenLoc);
4068  ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4069                                 tok::TokenKind Kind, Expr *Input);
4070
4071  ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4072                                     Expr *Idx, SourceLocation RLoc);
4073  ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4074                                             Expr *Idx, SourceLocation RLoc);
4075  ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4076                                      Expr *LowerBound, SourceLocation ColonLoc,
4077                                      Expr *Length, SourceLocation RBLoc);
4078
4079  // This struct is for use by ActOnMemberAccess to allow
4080  // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4081  // changing the access operator from a '.' to a '->' (to see if that is the
4082  // change needed to fix an error about an unknown member, e.g. when the class
4083  // defines a custom operator->).
4084  struct ActOnMemberAccessExtraArgs {
4085    Scope *S;
4086    UnqualifiedId &Id;
4087    Decl *ObjCImpDecl;
4088  };
4089
4090  ExprResult BuildMemberReferenceExpr(
4091      Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4092      CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4093      NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4094      const TemplateArgumentListInfo *TemplateArgs,
4095      const Scope *S,
4096      ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4097
4098  ExprResult
4099  BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4100                           bool IsArrow, const CXXScopeSpec &SS,
4101                           SourceLocation TemplateKWLoc,
4102                           NamedDecl *FirstQualifierInScope, LookupResult &R,
4103                           const TemplateArgumentListInfo *TemplateArgs,
4104                           const Scope *S,
4105                           bool SuppressQualifierCheck = false,
4106                           ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4107
4108  ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4109                                     SourceLocation OpLoc,
4110                                     const CXXScopeSpec &SS, FieldDecl *Field,
4111                                     DeclAccessPair FoundDecl,
4112                                     const DeclarationNameInfo &MemberNameInfo);
4113
4114  ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4115
4116  bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4117                                     const CXXScopeSpec &SS,
4118                                     const LookupResult &R);
4119
4120  ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4121                                      bool IsArrow, SourceLocation OpLoc,
4122                                      const CXXScopeSpec &SS,
4123                                      SourceLocation TemplateKWLoc,
4124                                      NamedDecl *FirstQualifierInScope,
4125                               const DeclarationNameInfo &NameInfo,
4126                               const TemplateArgumentListInfo *TemplateArgs);
4127
4128  ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4129                                   SourceLocation OpLoc,
4130                                   tok::TokenKind OpKind,
4131                                   CXXScopeSpec &SS,
4132                                   SourceLocation TemplateKWLoc,
4133                                   UnqualifiedId &Member,
4134                                   Decl *ObjCImpDecl);
4135
4136  void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4137  bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4138                               FunctionDecl *FDecl,
4139                               const FunctionProtoType *Proto,
4140                               ArrayRef<Expr *> Args,
4141                               SourceLocation RParenLoc,
4142                               bool ExecConfig = false);
4143  void CheckStaticArrayArgument(SourceLocation CallLoc,
4144                                ParmVarDecl *Param,
4145                                const Expr *ArgExpr);
4146
4147  /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4148  /// This provides the location of the left/right parens and a list of comma
4149  /// locations.
4150  ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4151                           MultiExprArg ArgExprs, SourceLocation RParenLoc,
4152                           Expr *ExecConfig = nullptr,
4153                           bool IsExecConfig = false);
4154  ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4155                                   SourceLocation LParenLoc,
4156                                   ArrayRef<Expr *> Arg,
4157                                   SourceLocation RParenLoc,
4158                                   Expr *Config = nullptr,
4159                                   bool IsExecConfig = false);
4160
4161  ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4162                                     MultiExprArg ExecConfig,
4163                                     SourceLocation GGGLoc);
4164
4165  ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4166                           Declarator &D, ParsedType &Ty,
4167                           SourceLocation RParenLoc, Expr *CastExpr);
4168  ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4169                                 TypeSourceInfo *Ty,
4170                                 SourceLocation RParenLoc,
4171                                 Expr *Op);
4172  CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4173
4174  /// \brief Build an altivec or OpenCL literal.
4175  ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4176                                SourceLocation RParenLoc, Expr *E,
4177                                TypeSourceInfo *TInfo);
4178
4179  ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4180
4181  ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4182                                  ParsedType Ty,
4183                                  SourceLocation RParenLoc,
4184                                  Expr *InitExpr);
4185
4186  ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4187                                      TypeSourceInfo *TInfo,
4188                                      SourceLocation RParenLoc,
4189                                      Expr *LiteralExpr);
4190
4191  ExprResult ActOnInitList(SourceLocation LBraceLoc,
4192                           MultiExprArg InitArgList,
4193                           SourceLocation RBraceLoc);
4194
4195  ExprResult ActOnDesignatedInitializer(Designation &Desig,
4196                                        SourceLocation Loc,
4197                                        bool GNUSyntax,
4198                                        ExprResult Init);
4199
4200private:
4201  static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4202
4203public:
4204  ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4205                        tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4206  ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4207                        BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4208  ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4209                                Expr *LHSExpr, Expr *RHSExpr);
4210
4211  void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4212
4213  /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
4214  /// in the case of a the GNU conditional expr extension.
4215  ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4216                                SourceLocation ColonLoc,
4217                                Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4218
4219  /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4220  ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4221                            LabelDecl *TheDecl);
4222
4223  void ActOnStartStmtExpr();
4224  ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4225                           SourceLocation RPLoc); // "({..})"
4226  void ActOnStmtExprError();
4227
4228  // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4229  struct OffsetOfComponent {
4230    SourceLocation LocStart, LocEnd;
4231    bool isBrackets;  // true if [expr], false if .ident
4232    union {
4233      IdentifierInfo *IdentInfo;
4234      Expr *E;
4235    } U;
4236  };
4237
4238  /// __builtin_offsetof(type, a.b[123][456].c)
4239  ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4240                                  TypeSourceInfo *TInfo,
4241                                  ArrayRef<OffsetOfComponent> Components,
4242                                  SourceLocation RParenLoc);
4243  ExprResult ActOnBuiltinOffsetOf(Scope *S,
4244                                  SourceLocation BuiltinLoc,
4245                                  SourceLocation TypeLoc,
4246                                  ParsedType ParsedArgTy,
4247                                  ArrayRef<OffsetOfComponent> Components,
4248                                  SourceLocation RParenLoc);
4249
4250  // __builtin_choose_expr(constExpr, expr1, expr2)
4251  ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4252                             Expr *CondExpr, Expr *LHSExpr,
4253                             Expr *RHSExpr, SourceLocation RPLoc);
4254
4255  // __builtin_va_arg(expr, type)
4256  ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4257                        SourceLocation RPLoc);
4258  ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4259                            TypeSourceInfo *TInfo, SourceLocation RPLoc);
4260
4261  // __null
4262  ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4263
4264  bool CheckCaseExpression(Expr *E);
4265
4266  /// \brief Describes the result of an "if-exists" condition check.
4267  enum IfExistsResult {
4268    /// \brief The symbol exists.
4269    IER_Exists,
4270
4271    /// \brief The symbol does not exist.
4272    IER_DoesNotExist,
4273
4274    /// \brief The name is a dependent name, so the results will differ
4275    /// from one instantiation to the next.
4276    IER_Dependent,
4277
4278    /// \brief An error occurred.
4279    IER_Error
4280  };
4281
4282  IfExistsResult
4283  CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4284                               const DeclarationNameInfo &TargetNameInfo);
4285
4286  IfExistsResult
4287  CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4288                               bool IsIfExists, CXXScopeSpec &SS,
4289                               UnqualifiedId &Name);
4290
4291  StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4292                                        bool IsIfExists,
4293                                        NestedNameSpecifierLoc QualifierLoc,
4294                                        DeclarationNameInfo NameInfo,
4295                                        Stmt *Nested);
4296  StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4297                                        bool IsIfExists,
4298                                        CXXScopeSpec &SS, UnqualifiedId &Name,
4299                                        Stmt *Nested);
4300
4301  //===------------------------- "Block" Extension ------------------------===//
4302
4303  /// ActOnBlockStart - This callback is invoked when a block literal is
4304  /// started.
4305  void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4306
4307  /// ActOnBlockArguments - This callback allows processing of block arguments.
4308  /// If there are no arguments, this is still invoked.
4309  void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4310                           Scope *CurScope);
4311
4312  /// ActOnBlockError - If there is an error parsing a block, this callback
4313  /// is invoked to pop the information about the block from the action impl.
4314  void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4315
4316  /// ActOnBlockStmtExpr - This is called when the body of a block statement
4317  /// literal was successfully completed.  ^(int x){...}
4318  ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4319                                Scope *CurScope);
4320
4321  //===---------------------------- Clang Extensions ----------------------===//
4322
4323  /// __builtin_convertvector(...)
4324  ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4325                                    SourceLocation BuiltinLoc,
4326                                    SourceLocation RParenLoc);
4327
4328  //===---------------------------- OpenCL Features -----------------------===//
4329
4330  /// __builtin_astype(...)
4331  ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4332                             SourceLocation BuiltinLoc,
4333                             SourceLocation RParenLoc);
4334
4335  //===---------------------------- C++ Features --------------------------===//
4336
4337  // Act on C++ namespaces
4338  Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4339                               SourceLocation NamespaceLoc,
4340                               SourceLocation IdentLoc,
4341                               IdentifierInfo *Ident,
4342                               SourceLocation LBrace,
4343                               AttributeList *AttrList,
4344                               UsingDirectiveDecl * &UsingDecl);
4345  void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4346
4347  NamespaceDecl *getStdNamespace() const;
4348  NamespaceDecl *getOrCreateStdNamespace();
4349
4350  NamespaceDecl *lookupStdExperimentalNamespace();
4351
4352  CXXRecordDecl *getStdBadAlloc() const;
4353  EnumDecl *getStdAlignValT() const;
4354
4355  /// \brief Tests whether Ty is an instance of std::initializer_list and, if
4356  /// it is and Element is not NULL, assigns the element type to Element.
4357  bool isStdInitializerList(QualType Ty, QualType *Element);
4358
4359  /// \brief Looks for the std::initializer_list template and instantiates it
4360  /// with Element, or emits an error if it's not found.
4361  ///
4362  /// \returns The instantiated template, or null on error.
4363  QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4364
4365  /// \brief Determine whether Ctor is an initializer-list constructor, as
4366  /// defined in [dcl.init.list]p2.
4367  bool isInitListConstructor(const FunctionDecl *Ctor);
4368
4369  Decl *ActOnUsingDirective(Scope *CurScope,
4370                            SourceLocation UsingLoc,
4371                            SourceLocation NamespcLoc,
4372                            CXXScopeSpec &SS,
4373                            SourceLocation IdentLoc,
4374                            IdentifierInfo *NamespcName,
4375                            AttributeList *AttrList);
4376
4377  void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4378
4379  Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4380                               SourceLocation NamespaceLoc,
4381                               SourceLocation AliasLoc,
4382                               IdentifierInfo *Alias,
4383                               CXXScopeSpec &SS,
4384                               SourceLocation IdentLoc,
4385                               IdentifierInfo *Ident);
4386
4387  void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4388  bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4389                            const LookupResult &PreviousDecls,
4390                            UsingShadowDecl *&PrevShadow);
4391  UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4392                                        NamedDecl *Target,
4393                                        UsingShadowDecl *PrevDecl);
4394
4395  bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4396                                   bool HasTypenameKeyword,
4397                                   const CXXScopeSpec &SS,
4398                                   SourceLocation NameLoc,
4399                                   const LookupResult &Previous);
4400  bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4401                               bool HasTypename,
4402                               const CXXScopeSpec &SS,
4403                               const DeclarationNameInfo &NameInfo,
4404                               SourceLocation NameLoc);
4405
4406  NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4407                                   SourceLocation UsingLoc,
4408                                   bool HasTypenameKeyword,
4409                                   SourceLocation TypenameLoc,
4410                                   CXXScopeSpec &SS,
4411                                   DeclarationNameInfo NameInfo,
4412                                   SourceLocation EllipsisLoc,
4413                                   AttributeList *AttrList,
4414                                   bool IsInstantiation);
4415  NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
4416                                ArrayRef<NamedDecl *> Expansions);
4417
4418  bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4419
4420  /// Given a derived-class using shadow declaration for a constructor and the
4421  /// correspnding base class constructor, find or create the implicit
4422  /// synthesized derived class constructor to use for this initialization.
4423  CXXConstructorDecl *
4424  findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
4425                            ConstructorUsingShadowDecl *DerivedShadow);
4426
4427  Decl *ActOnUsingDeclaration(Scope *CurScope,
4428                              AccessSpecifier AS,
4429                              SourceLocation UsingLoc,
4430                              SourceLocation TypenameLoc,
4431                              CXXScopeSpec &SS,
4432                              UnqualifiedId &Name,
4433                              SourceLocation EllipsisLoc,
4434                              AttributeList *AttrList);
4435  Decl *ActOnAliasDeclaration(Scope *CurScope,
4436                              AccessSpecifier AS,
4437                              MultiTemplateParamsArg TemplateParams,
4438                              SourceLocation UsingLoc,
4439                              UnqualifiedId &Name,
4440                              AttributeList *AttrList,
4441                              TypeResult Type,
4442                              Decl *DeclFromDeclSpec);
4443
4444  /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4445  /// including handling of its default argument expressions.
4446  ///
4447  /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4448  ExprResult
4449  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4450                        NamedDecl *FoundDecl,
4451                        CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4452                        bool HadMultipleCandidates, bool IsListInitialization,
4453                        bool IsStdInitListInitialization,
4454                        bool RequiresZeroInit, unsigned ConstructKind,
4455                        SourceRange ParenRange);
4456
4457  /// Build a CXXConstructExpr whose constructor has already been resolved if
4458  /// it denotes an inherited constructor.
4459  ExprResult
4460  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4461                        CXXConstructorDecl *Constructor, bool Elidable,
4462                        MultiExprArg Exprs,
4463                        bool HadMultipleCandidates, bool IsListInitialization,
4464                        bool IsStdInitListInitialization,
4465                        bool RequiresZeroInit, unsigned ConstructKind,
4466                        SourceRange ParenRange);
4467
4468  // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4469  // the constructor can be elidable?
4470  ExprResult
4471  BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4472                        NamedDecl *FoundDecl,
4473                        CXXConstructorDecl *Constructor, bool Elidable,
4474                        MultiExprArg Exprs, bool HadMultipleCandidates,
4475                        bool IsListInitialization,
4476                        bool IsStdInitListInitialization, bool RequiresZeroInit,
4477                        unsigned ConstructKind, SourceRange ParenRange);
4478
4479  ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4480
4481
4482  /// Instantiate or parse a C++ default argument expression as necessary.
4483  /// Return true on error.
4484  bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4485                              ParmVarDecl *Param);
4486
4487  /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4488  /// the default expr if needed.
4489  ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4490                                    FunctionDecl *FD,
4491                                    ParmVarDecl *Param);
4492
4493  /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4494  /// constructed variable.
4495  void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4496
4497  /// \brief Helper class that collects exception specifications for
4498  /// implicitly-declared special member functions.
4499  class ImplicitExceptionSpecification {
4500    // Pointer to allow copying
4501    Sema *Self;
4502    // We order exception specifications thus:
4503    // noexcept is the most restrictive, but is only used in C++11.
4504    // throw() comes next.
4505    // Then a throw(collected exceptions)
4506    // Finally no specification, which is expressed as noexcept(false).
4507    // throw(...) is used instead if any called function uses it.
4508    ExceptionSpecificationType ComputedEST;
4509    llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4510    SmallVector<QualType, 4> Exceptions;
4511
4512    void ClearExceptions() {
4513      ExceptionsSeen.clear();
4514      Exceptions.clear();
4515    }
4516
4517  public:
4518    explicit ImplicitExceptionSpecification(Sema &Self)
4519      : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4520      if (!Self.getLangOpts().CPlusPlus11)
4521        ComputedEST = EST_DynamicNone;
4522    }
4523
4524    /// \brief Get the computed exception specification type.
4525    ExceptionSpecificationType getExceptionSpecType() const {
4526      assert(ComputedEST != EST_ComputedNoexcept &&
4527             "noexcept(expr) should not be a possible result");
4528      return ComputedEST;
4529    }
4530
4531    /// \brief The number of exceptions in the exception specification.
4532    unsigned size() const { return Exceptions.size(); }
4533
4534    /// \brief The set of exceptions in the exception specification.
4535    const QualType *data() const { return Exceptions.data(); }
4536
4537    /// \brief Integrate another called method into the collected data.
4538    void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4539
4540    /// \brief Integrate an invoked expression into the collected data.
4541    void CalledExpr(Expr *E);
4542
4543    /// \brief Overwrite an EPI's exception specification with this
4544    /// computed exception specification.
4545    FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4546      FunctionProtoType::ExceptionSpecInfo ESI;
4547      ESI.Type = getExceptionSpecType();
4548      if (ESI.Type == EST_Dynamic) {
4549        ESI.Exceptions = Exceptions;
4550      } else if (ESI.Type == EST_None) {
4551        /// C++11 [except.spec]p14:
4552        ///   The exception-specification is noexcept(false) if the set of
4553        ///   potential exceptions of the special member function contains "any"
4554        ESI.Type = EST_ComputedNoexcept;
4555        ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4556                                                     tok::kw_false).get();
4557      }
4558      return ESI;
4559    }
4560  };
4561
4562  /// \brief Determine what sort of exception specification a defaulted
4563  /// copy constructor of a class will have.
4564  ImplicitExceptionSpecification
4565  ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4566                                           CXXMethodDecl *MD);
4567
4568  /// \brief Determine what sort of exception specification a defaulted
4569  /// default constructor of a class will have, and whether the parameter
4570  /// will be const.
4571  ImplicitExceptionSpecification
4572  ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4573
4574  /// \brief Determine what sort of exception specification a defautled
4575  /// copy assignment operator of a class will have, and whether the
4576  /// parameter will be const.
4577  ImplicitExceptionSpecification
4578  ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4579
4580  /// \brief Determine what sort of exception specification a defaulted move
4581  /// constructor of a class will have.
4582  ImplicitExceptionSpecification
4583  ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4584
4585  /// \brief Determine what sort of exception specification a defaulted move
4586  /// assignment operator of a class will have.
4587  ImplicitExceptionSpecification
4588  ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4589
4590  /// \brief Determine what sort of exception specification a defaulted
4591  /// destructor of a class will have.
4592  ImplicitExceptionSpecification
4593  ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4594
4595  /// \brief Determine what sort of exception specification an inheriting
4596  /// constructor of a class will have.
4597  ImplicitExceptionSpecification
4598  ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
4599                                     CXXConstructorDecl *CD);
4600
4601  /// \brief Evaluate the implicit exception specification for a defaulted
4602  /// special member function.
4603  void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4604
4605  /// \brief Check the given exception-specification and update the
4606  /// exception specification information with the results.
4607  void checkExceptionSpecification(bool IsTopLevel,
4608                                   ExceptionSpecificationType EST,
4609                                   ArrayRef<ParsedType> DynamicExceptions,
4610                                   ArrayRef<SourceRange> DynamicExceptionRanges,
4611                                   Expr *NoexceptExpr,
4612                                   SmallVectorImpl<QualType> &Exceptions,
4613                                   FunctionProtoType::ExceptionSpecInfo &ESI);
4614
4615  /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
4616  /// parse an exception specification to work around a libstdc++ bug.
4617  bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4618
4619  /// \brief Add an exception-specification to the given member function
4620  /// (or member function template). The exception-specification was parsed
4621  /// after the method itself was declared.
4622  void actOnDelayedExceptionSpecification(Decl *Method,
4623         ExceptionSpecificationType EST,
4624         SourceRange SpecificationRange,
4625         ArrayRef<ParsedType> DynamicExceptions,
4626         ArrayRef<SourceRange> DynamicExceptionRanges,
4627         Expr *NoexceptExpr);
4628
4629  class InheritedConstructorInfo;
4630
4631  /// \brief Determine if a special member function should have a deleted
4632  /// definition when it is defaulted.
4633  bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4634                                 InheritedConstructorInfo *ICI = nullptr,
4635                                 bool Diagnose = false);
4636
4637  /// \brief Declare the implicit default constructor for the given class.
4638  ///
4639  /// \param ClassDecl The class declaration into which the implicit
4640  /// default constructor will be added.
4641  ///
4642  /// \returns The implicitly-declared default constructor.
4643  CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4644                                                     CXXRecordDecl *ClassDecl);
4645
4646  /// DefineImplicitDefaultConstructor - Checks for feasibility of
4647  /// defining this constructor as the default constructor.
4648  void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4649                                        CXXConstructorDecl *Constructor);
4650
4651  /// \brief Declare the implicit destructor for the given class.
4652  ///
4653  /// \param ClassDecl The class declaration into which the implicit
4654  /// destructor will be added.
4655  ///
4656  /// \returns The implicitly-declared destructor.
4657  CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4658
4659  /// DefineImplicitDestructor - Checks for feasibility of
4660  /// defining this destructor as the default destructor.
4661  void DefineImplicitDestructor(SourceLocation CurrentLocation,
4662                                CXXDestructorDecl *Destructor);
4663
4664  /// \brief Build an exception spec for destructors that don't have one.
4665  ///
4666  /// C++11 says that user-defined destructors with no exception spec get one
4667  /// that looks as if the destructor was implicitly declared.
4668  void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4669                                     CXXDestructorDecl *Destructor);
4670
4671  /// \brief Define the specified inheriting constructor.
4672  void DefineInheritingConstructor(SourceLocation UseLoc,
4673                                   CXXConstructorDecl *Constructor);
4674
4675  /// \brief Declare the implicit copy constructor for the given class.
4676  ///
4677  /// \param ClassDecl The class declaration into which the implicit
4678  /// copy constructor will be added.
4679  ///
4680  /// \returns The implicitly-declared copy constructor.
4681  CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4682
4683  /// DefineImplicitCopyConstructor - Checks for feasibility of
4684  /// defining this constructor as the copy constructor.
4685  void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4686                                     CXXConstructorDecl *Constructor);
4687
4688  /// \brief Declare the implicit move constructor for the given class.
4689  ///
4690  /// \param ClassDecl The Class declaration into which the implicit
4691  /// move constructor will be added.
4692  ///
4693  /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4694  /// declared.
4695  CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4696
4697  /// DefineImplicitMoveConstructor - Checks for feasibility of
4698  /// defining this constructor as the move constructor.
4699  void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4700                                     CXXConstructorDecl *Constructor);
4701
4702  /// \brief Declare the implicit copy assignment operator for the given class.
4703  ///
4704  /// \param ClassDecl The class declaration into which the implicit
4705  /// copy assignment operator will be added.
4706  ///
4707  /// \returns The implicitly-declared copy assignment operator.
4708  CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4709
4710  /// \brief Defines an implicitly-declared copy assignment operator.
4711  void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4712                                    CXXMethodDecl *MethodDecl);
4713
4714  /// \brief Declare the implicit move assignment operator for the given class.
4715  ///
4716  /// \param ClassDecl The Class declaration into which the implicit
4717  /// move assignment operator will be added.
4718  ///
4719  /// \returns The implicitly-declared move assignment operator, or NULL if it
4720  /// wasn't declared.
4721  CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4722
4723  /// \brief Defines an implicitly-declared move assignment operator.
4724  void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4725                                    CXXMethodDecl *MethodDecl);
4726
4727  /// \brief Force the declaration of any implicitly-declared members of this
4728  /// class.
4729  void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4730
4731  /// \brief Check a completed declaration of an implicit special member.
4732  void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
4733
4734  /// \brief Determine whether the given function is an implicitly-deleted
4735  /// special member function.
4736  bool isImplicitlyDeleted(FunctionDecl *FD);
4737
4738  /// \brief Check whether 'this' shows up in the type of a static member
4739  /// function after the (naturally empty) cv-qualifier-seq would be.
4740  ///
4741  /// \returns true if an error occurred.
4742  bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4743
4744  /// \brief Whether this' shows up in the exception specification of a static
4745  /// member function.
4746  bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4747
4748  /// \brief Check whether 'this' shows up in the attributes of the given
4749  /// static member function.
4750  ///
4751  /// \returns true if an error occurred.
4752  bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4753
4754  /// MaybeBindToTemporary - If the passed in expression has a record type with
4755  /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4756  /// it simply returns the passed in expression.
4757  ExprResult MaybeBindToTemporary(Expr *E);
4758
4759  bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4760                               MultiExprArg ArgsPtr,
4761                               SourceLocation Loc,
4762                               SmallVectorImpl<Expr*> &ConvertedArgs,
4763                               bool AllowExplicit = false,
4764                               bool IsListInitialization = false);
4765
4766  ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4767                                          SourceLocation NameLoc,
4768                                          IdentifierInfo &Name);
4769
4770  ParsedType getDestructorName(SourceLocation TildeLoc,
4771                               IdentifierInfo &II, SourceLocation NameLoc,
4772                               Scope *S, CXXScopeSpec &SS,
4773                               ParsedType ObjectType,
4774                               bool EnteringContext);
4775
4776  ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
4777                                          ParsedType ObjectType);
4778
4779  // Checks that reinterpret casts don't have undefined behavior.
4780  void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4781                                      bool IsDereference, SourceRange Range);
4782
4783  /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4784  ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4785                               tok::TokenKind Kind,
4786                               SourceLocation LAngleBracketLoc,
4787                               Declarator &D,
4788                               SourceLocation RAngleBracketLoc,
4789                               SourceLocation LParenLoc,
4790                               Expr *E,
4791                               SourceLocation RParenLoc);
4792
4793  ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4794                               tok::TokenKind Kind,
4795                               TypeSourceInfo *Ty,
4796                               Expr *E,
4797                               SourceRange AngleBrackets,
4798                               SourceRange Parens);
4799
4800  ExprResult BuildCXXTypeId(QualType TypeInfoType,
4801                            SourceLocation TypeidLoc,
4802                            TypeSourceInfo *Operand,
4803                            SourceLocation RParenLoc);
4804  ExprResult BuildCXXTypeId(QualType TypeInfoType,
4805                            SourceLocation TypeidLoc,
4806                            Expr *Operand,
4807                            SourceLocation RParenLoc);
4808
4809  /// ActOnCXXTypeid - Parse typeid( something ).
4810  ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
4811                            SourceLocation LParenLoc, bool isType,
4812                            void *TyOrExpr,
4813                            SourceLocation RParenLoc);
4814
4815  ExprResult BuildCXXUuidof(QualType TypeInfoType,
4816                            SourceLocation TypeidLoc,
4817                            TypeSourceInfo *Operand,
4818                            SourceLocation RParenLoc);
4819  ExprResult BuildCXXUuidof(QualType TypeInfoType,
4820                            SourceLocation TypeidLoc,
4821                            Expr *Operand,
4822                            SourceLocation RParenLoc);
4823
4824  /// ActOnCXXUuidof - Parse __uuidof( something ).
4825  ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
4826                            SourceLocation LParenLoc, bool isType,
4827                            void *TyOrExpr,
4828                            SourceLocation RParenLoc);
4829
4830  /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
4831  ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4832                              tok::TokenKind Operator,
4833                              SourceLocation EllipsisLoc, Expr *RHS,
4834                              SourceLocation RParenLoc);
4835  ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4836                              BinaryOperatorKind Operator,
4837                              SourceLocation EllipsisLoc, Expr *RHS,
4838                              SourceLocation RParenLoc);
4839  ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
4840                                   BinaryOperatorKind Operator);
4841
4842  //// ActOnCXXThis -  Parse 'this' pointer.
4843  ExprResult ActOnCXXThis(SourceLocation loc);
4844
4845  /// \brief Try to retrieve the type of the 'this' pointer.
4846  ///
4847  /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
4848  QualType getCurrentThisType();
4849
4850  /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
4851  /// current context not being a non-static member function. In such cases,
4852  /// this provides the type used for 'this'.
4853  QualType CXXThisTypeOverride;
4854
4855  /// \brief RAII object used to temporarily allow the C++ 'this' expression
4856  /// to be used, with the given qualifiers on the current class type.
4857  class CXXThisScopeRAII {
4858    Sema &S;
4859    QualType OldCXXThisTypeOverride;
4860    bool Enabled;
4861
4862  public:
4863    /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
4864    /// using the given declaration (which is either a class template or a
4865    /// class) along with the given qualifiers.
4866    /// along with the qualifiers placed on '*this'.
4867    CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
4868                     bool Enabled = true);
4869
4870    ~CXXThisScopeRAII();
4871  };
4872
4873  /// \brief Make sure the value of 'this' is actually available in the current
4874  /// context, if it is a potentially evaluated context.
4875  ///
4876  /// \param Loc The location at which the capture of 'this' occurs.
4877  ///
4878  /// \param Explicit Whether 'this' is explicitly captured in a lambda
4879  /// capture list.
4880  ///
4881  /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
4882  /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
4883  /// This is useful when enclosing lambdas must speculatively capture
4884  /// 'this' that may or may not be used in certain specializations of
4885  /// a nested generic lambda (depending on whether the name resolves to
4886  /// a non-static member function or a static function).
4887  /// \return returns 'true' if failed, 'false' if success.
4888  bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
4889      bool BuildAndDiagnose = true,
4890      const unsigned *const FunctionScopeIndexToStopAt = nullptr,
4891      bool ByCopy = false);
4892
4893  /// \brief Determine whether the given type is the type of *this that is used
4894  /// outside of the body of a member function for a type that is currently
4895  /// being defined.
4896  bool isThisOutsideMemberFunctionBody(QualType BaseType);
4897
4898  /// ActOnCXXBoolLiteral - Parse {true,false} literals.
4899  ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4900
4901
4902  /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
4903  ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
4904
4905  ExprResult
4906  ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
4907                                 SourceLocation AtLoc, SourceLocation RParen);
4908
4909  /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
4910  ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
4911
4912  //// ActOnCXXThrow -  Parse throw expressions.
4913  ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
4914  ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
4915                           bool IsThrownVarInScope);
4916  bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
4917
4918  /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
4919  /// Can be interpreted either as function-style casting ("int(x)")
4920  /// or class type construction ("ClassType(x,y,z)")
4921  /// or creation of a value-initialized type ("int()").
4922  ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
4923                                       SourceLocation LParenLoc,
4924                                       MultiExprArg Exprs,
4925                                       SourceLocation RParenLoc);
4926
4927  ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
4928                                       SourceLocation LParenLoc,
4929                                       MultiExprArg Exprs,
4930                                       SourceLocation RParenLoc);
4931
4932  /// ActOnCXXNew - Parsed a C++ 'new' expression.
4933  ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
4934                         SourceLocation PlacementLParen,
4935                         MultiExprArg PlacementArgs,
4936                         SourceLocation PlacementRParen,
4937                         SourceRange TypeIdParens, Declarator &D,
4938                         Expr *Initializer);
4939  ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
4940                         SourceLocation PlacementLParen,
4941                         MultiExprArg PlacementArgs,
4942                         SourceLocation PlacementRParen,
4943                         SourceRange TypeIdParens,
4944                         QualType AllocType,
4945                         TypeSourceInfo *AllocTypeInfo,
4946                         Expr *ArraySize,
4947                         SourceRange DirectInitRange,
4948                         Expr *Initializer);
4949
4950  bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
4951                          SourceRange R);
4952  bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
4953                               bool UseGlobal, QualType AllocType, bool IsArray,
4954                               bool &PassAlignment, MultiExprArg PlaceArgs,
4955                               FunctionDecl *&OperatorNew,
4956                               FunctionDecl *&OperatorDelete);
4957  void DeclareGlobalNewDelete();
4958  void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
4959                                       ArrayRef<QualType> Params);
4960
4961  bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
4962                                DeclarationName Name, FunctionDecl* &Operator,
4963                                bool Diagnose = true);
4964  FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
4965                                              bool CanProvideSize,
4966                                              bool Overaligned,
4967                                              DeclarationName Name);
4968  FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
4969                                                      CXXRecordDecl *RD);
4970
4971  /// ActOnCXXDelete - Parsed a C++ 'delete' expression
4972  ExprResult ActOnCXXDelete(SourceLocation StartLoc,
4973                            bool UseGlobal, bool ArrayForm,
4974                            Expr *Operand);
4975  void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
4976                            bool IsDelete, bool CallCanBeVirtual,
4977                            bool WarnOnNonAbstractTypes,
4978                            SourceLocation DtorLoc);
4979
4980  ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
4981                               Expr *Operand, SourceLocation RParen);
4982  ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
4983                                  SourceLocation RParen);
4984
4985  /// \brief Parsed one of the type trait support pseudo-functions.
4986  ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4987                            ArrayRef<ParsedType> Args,
4988                            SourceLocation RParenLoc);
4989  ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4990                            ArrayRef<TypeSourceInfo *> Args,
4991                            SourceLocation RParenLoc);
4992
4993  /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
4994  /// pseudo-functions.
4995  ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4996                                 SourceLocation KWLoc,
4997                                 ParsedType LhsTy,
4998                                 Expr *DimExpr,
4999                                 SourceLocation RParen);
5000
5001  ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
5002                                 SourceLocation KWLoc,
5003                                 TypeSourceInfo *TSInfo,
5004                                 Expr *DimExpr,
5005                                 SourceLocation RParen);
5006
5007  /// ActOnExpressionTrait - Parsed one of the unary type trait support
5008  /// pseudo-functions.
5009  ExprResult ActOnExpressionTrait(ExpressionTrait OET,
5010                                  SourceLocation KWLoc,
5011                                  Expr *Queried,
5012                                  SourceLocation RParen);
5013
5014  ExprResult BuildExpressionTrait(ExpressionTrait OET,
5015                                  SourceLocation KWLoc,
5016                                  Expr *Queried,
5017                                  SourceLocation RParen);
5018
5019  ExprResult ActOnStartCXXMemberReference(Scope *S,
5020                                          Expr *Base,
5021                                          SourceLocation OpLoc,
5022                                          tok::TokenKind OpKind,
5023                                          ParsedType &ObjectType,
5024                                          bool &MayBePseudoDestructor);
5025
5026  ExprResult BuildPseudoDestructorExpr(Expr *Base,
5027                                       SourceLocation OpLoc,
5028                                       tok::TokenKind OpKind,
5029                                       const CXXScopeSpec &SS,
5030                                       TypeSourceInfo *ScopeType,
5031                                       SourceLocation CCLoc,
5032                                       SourceLocation TildeLoc,
5033                                     PseudoDestructorTypeStorage DestroyedType);
5034
5035  ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5036                                       SourceLocation OpLoc,
5037                                       tok::TokenKind OpKind,
5038                                       CXXScopeSpec &SS,
5039                                       UnqualifiedId &FirstTypeName,
5040                                       SourceLocation CCLoc,
5041                                       SourceLocation TildeLoc,
5042                                       UnqualifiedId &SecondTypeName);
5043
5044  ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5045                                       SourceLocation OpLoc,
5046                                       tok::TokenKind OpKind,
5047                                       SourceLocation TildeLoc,
5048                                       const DeclSpec& DS);
5049
5050  /// MaybeCreateExprWithCleanups - If the current full-expression
5051  /// requires any cleanups, surround it with a ExprWithCleanups node.
5052  /// Otherwise, just returns the passed-in expression.
5053  Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
5054  Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
5055  ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
5056
5057  MaterializeTemporaryExpr *
5058  CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
5059                                 bool BoundToLvalueReference);
5060
5061  ExprResult ActOnFinishFullExpr(Expr *Expr) {
5062    return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
5063                                          : SourceLocation());
5064  }
5065  ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
5066                                 bool DiscardedValue = false,
5067                                 bool IsConstexpr = false,
5068                                 bool IsLambdaInitCaptureInitializer = false);
5069  StmtResult ActOnFinishFullStmt(Stmt *Stmt);
5070
5071  // Marks SS invalid if it represents an incomplete type.
5072  bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
5073
5074  DeclContext *computeDeclContext(QualType T);
5075  DeclContext *computeDeclContext(const CXXScopeSpec &SS,
5076                                  bool EnteringContext = false);
5077  bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
5078  CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
5079
5080  /// \brief The parser has parsed a global nested-name-specifier '::'.
5081  ///
5082  /// \param CCLoc The location of the '::'.
5083  ///
5084  /// \param SS The nested-name-specifier, which will be updated in-place
5085  /// to reflect the parsed nested-name-specifier.
5086  ///
5087  /// \returns true if an error occurred, false otherwise.
5088  bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
5089
5090  /// \brief The parser has parsed a '__super' nested-name-specifier.
5091  ///
5092  /// \param SuperLoc The location of the '__super' keyword.
5093  ///
5094  /// \param ColonColonLoc The location of the '::'.
5095  ///
5096  /// \param SS The nested-name-specifier, which will be updated in-place
5097  /// to reflect the parsed nested-name-specifier.
5098  ///
5099  /// \returns true if an error occurred, false otherwise.
5100  bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
5101                                SourceLocation ColonColonLoc, CXXScopeSpec &SS);
5102
5103  bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
5104                                       bool *CanCorrect = nullptr);
5105  NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
5106
5107  /// \brief Keeps information about an identifier in a nested-name-spec.
5108  ///
5109  struct NestedNameSpecInfo {
5110    /// \brief The type of the object, if we're parsing nested-name-specifier in
5111    /// a member access expression.
5112    ParsedType ObjectType;
5113
5114    /// \brief The identifier preceding the '::'.
5115    IdentifierInfo *Identifier;
5116
5117    /// \brief The location of the identifier.
5118    SourceLocation IdentifierLoc;
5119
5120    /// \brief The location of the '::'.
5121    SourceLocation CCLoc;
5122
5123    /// \brief Creates info object for the most typical case.
5124    NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5125             SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
5126      : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
5127        CCLoc(ColonColonLoc) {
5128    }
5129
5130    NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5131                       SourceLocation ColonColonLoc, QualType ObjectType)
5132      : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
5133        IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
5134    }
5135  };
5136
5137  bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
5138                                    NestedNameSpecInfo &IdInfo);
5139
5140  bool BuildCXXNestedNameSpecifier(Scope *S,
5141                                   NestedNameSpecInfo &IdInfo,
5142                                   bool EnteringContext,
5143                                   CXXScopeSpec &SS,
5144                                   NamedDecl *ScopeLookupResult,
5145                                   bool ErrorRecoveryLookup,
5146                                   bool *IsCorrectedToColon = nullptr,
5147                                   bool OnlyNamespace = false);
5148
5149  /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
5150  ///
5151  /// \param S The scope in which this nested-name-specifier occurs.
5152  ///
5153  /// \param IdInfo Parser information about an identifier in the
5154  /// nested-name-spec.
5155  ///
5156  /// \param EnteringContext Whether we're entering the context nominated by
5157  /// this nested-name-specifier.
5158  ///
5159  /// \param SS The nested-name-specifier, which is both an input
5160  /// parameter (the nested-name-specifier before this type) and an
5161  /// output parameter (containing the full nested-name-specifier,
5162  /// including this new type).
5163  ///
5164  /// \param ErrorRecoveryLookup If true, then this method is called to improve
5165  /// error recovery. In this case do not emit error message.
5166  ///
5167  /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
5168  /// are allowed.  The bool value pointed by this parameter is set to 'true'
5169  /// if the identifier is treated as if it was followed by ':', not '::'.
5170  ///
5171  /// \param OnlyNamespace If true, only considers namespaces in lookup.
5172  ///
5173  /// \returns true if an error occurred, false otherwise.
5174  bool ActOnCXXNestedNameSpecifier(Scope *S,
5175                                   NestedNameSpecInfo &IdInfo,
5176                                   bool EnteringContext,
5177                                   CXXScopeSpec &SS,
5178                                   bool ErrorRecoveryLookup = false,
5179                                   bool *IsCorrectedToColon = nullptr,
5180                                   bool OnlyNamespace = false);
5181
5182  ExprResult ActOnDecltypeExpression(Expr *E);
5183
5184  bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
5185                                           const DeclSpec &DS,
5186                                           SourceLocation ColonColonLoc);
5187
5188  bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
5189                                 NestedNameSpecInfo &IdInfo,
5190                                 bool EnteringContext);
5191
5192  /// \brief The parser has parsed a nested-name-specifier
5193  /// 'template[opt] template-name < template-args >::'.
5194  ///
5195  /// \param S The scope in which this nested-name-specifier occurs.
5196  ///
5197  /// \param SS The nested-name-specifier, which is both an input
5198  /// parameter (the nested-name-specifier before this type) and an
5199  /// output parameter (containing the full nested-name-specifier,
5200  /// including this new type).
5201  ///
5202  /// \param TemplateKWLoc the location of the 'template' keyword, if any.
5203  /// \param TemplateName the template name.
5204  /// \param TemplateNameLoc The location of the template name.
5205  /// \param LAngleLoc The location of the opening angle bracket  ('<').
5206  /// \param TemplateArgs The template arguments.
5207  /// \param RAngleLoc The location of the closing angle bracket  ('>').
5208  /// \param CCLoc The location of the '::'.
5209  ///
5210  /// \param EnteringContext Whether we're entering the context of the
5211  /// nested-name-specifier.
5212  ///
5213  ///
5214  /// \returns true if an error occurred, false otherwise.
5215  bool ActOnCXXNestedNameSpecifier(Scope *S,
5216                                   CXXScopeSpec &SS,
5217                                   SourceLocation TemplateKWLoc,
5218                                   TemplateTy TemplateName,
5219                                   SourceLocation TemplateNameLoc,
5220                                   SourceLocation LAngleLoc,
5221                                   ASTTemplateArgsPtr TemplateArgs,
5222                                   SourceLocation RAngleLoc,
5223                                   SourceLocation CCLoc,
5224                                   bool EnteringContext);
5225
5226  /// \brief Given a C++ nested-name-specifier, produce an annotation value
5227  /// that the parser can use later to reconstruct the given
5228  /// nested-name-specifier.
5229  ///
5230  /// \param SS A nested-name-specifier.
5231  ///
5232  /// \returns A pointer containing all of the information in the
5233  /// nested-name-specifier \p SS.
5234  void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
5235
5236  /// \brief Given an annotation pointer for a nested-name-specifier, restore
5237  /// the nested-name-specifier structure.
5238  ///
5239  /// \param Annotation The annotation pointer, produced by
5240  /// \c SaveNestedNameSpecifierAnnotation().
5241  ///
5242  /// \param AnnotationRange The source range corresponding to the annotation.
5243  ///
5244  /// \param SS The nested-name-specifier that will be updated with the contents
5245  /// of the annotation pointer.
5246  void RestoreNestedNameSpecifierAnnotation(void *Annotation,
5247                                            SourceRange AnnotationRange,
5248                                            CXXScopeSpec &SS);
5249
5250  bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5251
5252  /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
5253  /// scope or nested-name-specifier) is parsed, part of a declarator-id.
5254  /// After this method is called, according to [C++ 3.4.3p3], names should be
5255  /// looked up in the declarator-id's scope, until the declarator is parsed and
5256  /// ActOnCXXExitDeclaratorScope is called.
5257  /// The 'SS' should be a non-empty valid CXXScopeSpec.
5258  bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
5259
5260  /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
5261  /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
5262  /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
5263  /// Used to indicate that names should revert to being looked up in the
5264  /// defining scope.
5265  void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5266
5267  /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5268  /// initializer for the declaration 'Dcl'.
5269  /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5270  /// static data member of class X, names should be looked up in the scope of
5271  /// class X.
5272  void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5273
5274  /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5275  /// initializer for the declaration 'Dcl'.
5276  void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5277
5278  /// \brief Create a new lambda closure type.
5279  CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
5280                                         TypeSourceInfo *Info,
5281                                         bool KnownDependent,
5282                                         LambdaCaptureDefault CaptureDefault);
5283
5284  /// \brief Start the definition of a lambda expression.
5285  CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
5286                                       SourceRange IntroducerRange,
5287                                       TypeSourceInfo *MethodType,
5288                                       SourceLocation EndLoc,
5289                                       ArrayRef<ParmVarDecl *> Params,
5290                                       bool IsConstexprSpecified);
5291
5292  /// \brief Endow the lambda scope info with the relevant properties.
5293  void buildLambdaScope(sema::LambdaScopeInfo *LSI,
5294                        CXXMethodDecl *CallOperator,
5295                        SourceRange IntroducerRange,
5296                        LambdaCaptureDefault CaptureDefault,
5297                        SourceLocation CaptureDefaultLoc,
5298                        bool ExplicitParams,
5299                        bool ExplicitResultType,
5300                        bool Mutable);
5301
5302  /// \brief Perform initialization analysis of the init-capture and perform
5303  /// any implicit conversions such as an lvalue-to-rvalue conversion if
5304  /// not being used to initialize a reference.
5305  ParsedType actOnLambdaInitCaptureInitialization(
5306      SourceLocation Loc, bool ByRef, IdentifierInfo *Id,
5307      LambdaCaptureInitKind InitKind, Expr *&Init) {
5308    return ParsedType::make(buildLambdaInitCaptureInitialization(
5309        Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init));
5310  }
5311  QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
5312                                                IdentifierInfo *Id,
5313                                                bool DirectInit, Expr *&Init);
5314
5315  /// \brief Create a dummy variable within the declcontext of the lambda's
5316  ///  call operator, for name lookup purposes for a lambda init capture.
5317  ///
5318  ///  CodeGen handles emission of lambda captures, ignoring these dummy
5319  ///  variables appropriately.
5320  VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
5321                                          QualType InitCaptureType,
5322                                          IdentifierInfo *Id,
5323                                          unsigned InitStyle, Expr *Init);
5324
5325  /// \brief Build the implicit field for an init-capture.
5326  FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
5327
5328  /// \brief Note that we have finished the explicit captures for the
5329  /// given lambda.
5330  void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
5331
5332  /// \brief Introduce the lambda parameters into scope.
5333  void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
5334
5335  /// \brief Deduce a block or lambda's return type based on the return
5336  /// statements present in the body.
5337  void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
5338
5339  /// ActOnStartOfLambdaDefinition - This is called just before we start
5340  /// parsing the body of a lambda; it analyzes the explicit captures and
5341  /// arguments, and sets up various data-structures for the body of the
5342  /// lambda.
5343  void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
5344                                    Declarator &ParamInfo, Scope *CurScope);
5345
5346  /// ActOnLambdaError - If there is an error parsing a lambda, this callback
5347  /// is invoked to pop the information about the lambda.
5348  void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
5349                        bool IsInstantiation = false);
5350
5351  /// ActOnLambdaExpr - This is called when the body of a lambda expression
5352  /// was successfully completed.
5353  ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
5354                             Scope *CurScope);
5355
5356  /// \brief Does copying/destroying the captured variable have side effects?
5357  bool CaptureHasSideEffects(const sema::LambdaScopeInfo::Capture &From);
5358
5359  /// \brief Diagnose if an explicit lambda capture is unused.
5360  void DiagnoseUnusedLambdaCapture(const sema::LambdaScopeInfo::Capture &From);
5361
5362  /// \brief Complete a lambda-expression having processed and attached the
5363  /// lambda body.
5364  ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
5365                             sema::LambdaScopeInfo *LSI);
5366
5367  /// \brief Define the "body" of the conversion from a lambda object to a
5368  /// function pointer.
5369  ///
5370  /// This routine doesn't actually define a sensible body; rather, it fills
5371  /// in the initialization expression needed to copy the lambda object into
5372  /// the block, and IR generation actually generates the real body of the
5373  /// block pointer conversion.
5374  void DefineImplicitLambdaToFunctionPointerConversion(
5375         SourceLocation CurrentLoc, CXXConversionDecl *Conv);
5376
5377  /// \brief Define the "body" of the conversion from a lambda object to a
5378  /// block pointer.
5379  ///
5380  /// This routine doesn't actually define a sensible body; rather, it fills
5381  /// in the initialization expression needed to copy the lambda object into
5382  /// the block, and IR generation actually generates the real body of the
5383  /// block pointer conversion.
5384  void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5385                                                    CXXConversionDecl *Conv);
5386
5387  ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5388                                           SourceLocation ConvLocation,
5389                                           CXXConversionDecl *Conv,
5390                                           Expr *Src);
5391
5392  // ParseObjCStringLiteral - Parse Objective-C string literals.
5393  ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5394                                    ArrayRef<Expr *> Strings);
5395
5396  ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5397
5398  /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5399  /// numeric literal expression. Type of the expression will be "NSNumber *"
5400  /// or "id" if NSNumber is unavailable.
5401  ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5402  ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5403                                  bool Value);
5404  ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5405
5406  /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5407  /// '@' prefixed parenthesized expression. The type of the expression will
5408  /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
5409  /// of ValueType, which is allowed to be a built-in numeric type, "char *",
5410  /// "const char *" or C structure with attribute 'objc_boxable'.
5411  ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5412
5413  ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5414                                          Expr *IndexExpr,
5415                                          ObjCMethodDecl *getterMethod,
5416                                          ObjCMethodDecl *setterMethod);
5417
5418  ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5419                               MutableArrayRef<ObjCDictionaryElement> Elements);
5420
5421  ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5422                                  TypeSourceInfo *EncodedTypeInfo,
5423                                  SourceLocation RParenLoc);
5424  ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5425                                    CXXConversionDecl *Method,
5426                                    bool HadMultipleCandidates);
5427
5428  ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5429                                       SourceLocation EncodeLoc,
5430                                       SourceLocation LParenLoc,
5431                                       ParsedType Ty,
5432                                       SourceLocation RParenLoc);
5433
5434  /// ParseObjCSelectorExpression - Build selector expression for \@selector
5435  ExprResult ParseObjCSelectorExpression(Selector Sel,
5436                                         SourceLocation AtLoc,
5437                                         SourceLocation SelLoc,
5438                                         SourceLocation LParenLoc,
5439                                         SourceLocation RParenLoc,
5440                                         bool WarnMultipleSelectors);
5441
5442  /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5443  ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5444                                         SourceLocation AtLoc,
5445                                         SourceLocation ProtoLoc,
5446                                         SourceLocation LParenLoc,
5447                                         SourceLocation ProtoIdLoc,
5448                                         SourceLocation RParenLoc);
5449
5450  //===--------------------------------------------------------------------===//
5451  // C++ Declarations
5452  //
5453  Decl *ActOnStartLinkageSpecification(Scope *S,
5454                                       SourceLocation ExternLoc,
5455                                       Expr *LangStr,
5456                                       SourceLocation LBraceLoc);
5457  Decl *ActOnFinishLinkageSpecification(Scope *S,
5458                                        Decl *LinkageSpec,
5459                                        SourceLocation RBraceLoc);
5460
5461
5462  //===--------------------------------------------------------------------===//
5463  // C++ Classes
5464  //
5465  bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5466                          const CXXScopeSpec *SS = nullptr);
5467  bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5468
5469  bool ActOnAccessSpecifier(AccessSpecifier Access,
5470                            SourceLocation ASLoc,
5471                            SourceLocation ColonLoc,
5472                            AttributeList *Attrs = nullptr);
5473
5474  NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5475                                 Declarator &D,
5476                                 MultiTemplateParamsArg TemplateParameterLists,
5477                                 Expr *BitfieldWidth, const VirtSpecifiers &VS,
5478                                 InClassInitStyle InitStyle);
5479
5480  void ActOnStartCXXInClassMemberInitializer();
5481  void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5482                                              SourceLocation EqualLoc,
5483                                              Expr *Init);
5484
5485  MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5486                                    Scope *S,
5487                                    CXXScopeSpec &SS,
5488                                    IdentifierInfo *MemberOrBase,
5489                                    ParsedType TemplateTypeTy,
5490                                    const DeclSpec &DS,
5491                                    SourceLocation IdLoc,
5492                                    SourceLocation LParenLoc,
5493                                    ArrayRef<Expr *> Args,
5494                                    SourceLocation RParenLoc,
5495                                    SourceLocation EllipsisLoc);
5496
5497  MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5498                                    Scope *S,
5499                                    CXXScopeSpec &SS,
5500                                    IdentifierInfo *MemberOrBase,
5501                                    ParsedType TemplateTypeTy,
5502                                    const DeclSpec &DS,
5503                                    SourceLocation IdLoc,
5504                                    Expr *InitList,
5505                                    SourceLocation EllipsisLoc);
5506
5507  MemInitResult BuildMemInitializer(Decl *ConstructorD,
5508                                    Scope *S,
5509                                    CXXScopeSpec &SS,
5510                                    IdentifierInfo *MemberOrBase,
5511                                    ParsedType TemplateTypeTy,
5512                                    const DeclSpec &DS,
5513                                    SourceLocation IdLoc,
5514                                    Expr *Init,
5515                                    SourceLocation EllipsisLoc);
5516
5517  MemInitResult BuildMemberInitializer(ValueDecl *Member,
5518                                       Expr *Init,
5519                                       SourceLocation IdLoc);
5520
5521  MemInitResult BuildBaseInitializer(QualType BaseType,
5522                                     TypeSourceInfo *BaseTInfo,
5523                                     Expr *Init,
5524                                     CXXRecordDecl *ClassDecl,
5525                                     SourceLocation EllipsisLoc);
5526
5527  MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5528                                           Expr *Init,
5529                                           CXXRecordDecl *ClassDecl);
5530
5531  bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5532                                CXXCtorInitializer *Initializer);
5533
5534  bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5535                           ArrayRef<CXXCtorInitializer *> Initializers = None);
5536
5537  void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5538
5539
5540  /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5541  /// mark all the non-trivial destructors of its members and bases as
5542  /// referenced.
5543  void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5544                                              CXXRecordDecl *Record);
5545
5546  /// \brief The list of classes whose vtables have been used within
5547  /// this translation unit, and the source locations at which the
5548  /// first use occurred.
5549  typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5550
5551  /// \brief The list of vtables that are required but have not yet been
5552  /// materialized.
5553  SmallVector<VTableUse, 16> VTableUses;
5554
5555  /// \brief The set of classes whose vtables have been used within
5556  /// this translation unit, and a bit that will be true if the vtable is
5557  /// required to be emitted (otherwise, it should be emitted only if needed
5558  /// by code generation).
5559  llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5560
5561  /// \brief Load any externally-stored vtable uses.
5562  void LoadExternalVTableUses();
5563
5564  /// \brief Note that the vtable for the given class was used at the
5565  /// given location.
5566  void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5567                      bool DefinitionRequired = false);
5568
5569  /// \brief Mark the exception specifications of all virtual member functions
5570  /// in the given class as needed.
5571  void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5572                                             const CXXRecordDecl *RD);
5573
5574  /// MarkVirtualMembersReferenced - Will mark all members of the given
5575  /// CXXRecordDecl referenced.
5576  void MarkVirtualMembersReferenced(SourceLocation Loc,
5577                                    const CXXRecordDecl *RD);
5578
5579  /// \brief Define all of the vtables that have been used in this
5580  /// translation unit and reference any virtual members used by those
5581  /// vtables.
5582  ///
5583  /// \returns true if any work was done, false otherwise.
5584  bool DefineUsedVTables();
5585
5586  void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5587
5588  void ActOnMemInitializers(Decl *ConstructorDecl,
5589                            SourceLocation ColonLoc,
5590                            ArrayRef<CXXCtorInitializer*> MemInits,
5591                            bool AnyErrors);
5592
5593  /// \brief Check class-level dllimport/dllexport attribute. The caller must
5594  /// ensure that referenceDLLExportedClassMethods is called some point later
5595  /// when all outer classes of Class are complete.
5596  void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5597
5598  void referenceDLLExportedClassMethods();
5599
5600  void propagateDLLAttrToBaseClassTemplate(
5601      CXXRecordDecl *Class, Attr *ClassAttr,
5602      ClassTemplateSpecializationDecl *BaseTemplateSpec,
5603      SourceLocation BaseLoc);
5604
5605  void CheckCompletedCXXClass(CXXRecordDecl *Record);
5606  void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5607                                         Decl *TagDecl,
5608                                         SourceLocation LBrac,
5609                                         SourceLocation RBrac,
5610                                         AttributeList *AttrList);
5611  void ActOnFinishCXXMemberDecls();
5612  void ActOnFinishCXXNonNestedClass(Decl *D);
5613
5614  void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5615  unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5616  void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5617  void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5618  void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5619  void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5620  void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5621  void ActOnFinishDelayedMemberInitializers(Decl *Record);
5622  void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5623                                CachedTokens &Toks);
5624  void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5625  bool IsInsideALocalClassWithinATemplateFunction();
5626
5627  Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5628                                     Expr *AssertExpr,
5629                                     Expr *AssertMessageExpr,
5630                                     SourceLocation RParenLoc);
5631  Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5632                                     Expr *AssertExpr,
5633                                     StringLiteral *AssertMessageExpr,
5634                                     SourceLocation RParenLoc,
5635                                     bool Failed);
5636
5637  FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5638                                  SourceLocation FriendLoc,
5639                                  TypeSourceInfo *TSInfo);
5640  Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5641                            MultiTemplateParamsArg TemplateParams);
5642  NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5643                                     MultiTemplateParamsArg TemplateParams);
5644
5645  QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5646                                      StorageClass& SC);
5647  void CheckConstructor(CXXConstructorDecl *Constructor);
5648  QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5649                                     StorageClass& SC);
5650  bool CheckDestructor(CXXDestructorDecl *Destructor);
5651  void CheckConversionDeclarator(Declarator &D, QualType &R,
5652                                 StorageClass& SC);
5653  Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5654  void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
5655                                     StorageClass &SC);
5656  void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
5657
5658  void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5659  void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5660                                                   const FunctionProtoType *T);
5661  void CheckDelayedMemberExceptionSpecs();
5662
5663  //===--------------------------------------------------------------------===//
5664  // C++ Derived Classes
5665  //
5666
5667  /// ActOnBaseSpecifier - Parsed a base specifier
5668  CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5669                                       SourceRange SpecifierRange,
5670                                       bool Virtual, AccessSpecifier Access,
5671                                       TypeSourceInfo *TInfo,
5672                                       SourceLocation EllipsisLoc);
5673
5674  BaseResult ActOnBaseSpecifier(Decl *classdecl,
5675                                SourceRange SpecifierRange,
5676                                ParsedAttributes &Attrs,
5677                                bool Virtual, AccessSpecifier Access,
5678                                ParsedType basetype,
5679                                SourceLocation BaseLoc,
5680                                SourceLocation EllipsisLoc);
5681
5682  bool AttachBaseSpecifiers(CXXRecordDecl *Class,
5683                            MutableArrayRef<CXXBaseSpecifier *> Bases);
5684  void ActOnBaseSpecifiers(Decl *ClassDecl,
5685                           MutableArrayRef<CXXBaseSpecifier *> Bases);
5686
5687  bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
5688  bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
5689                     CXXBasePaths &Paths);
5690
5691  // FIXME: I don't like this name.
5692  void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5693
5694  bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5695                                    SourceLocation Loc, SourceRange Range,
5696                                    CXXCastPath *BasePath = nullptr,
5697                                    bool IgnoreAccess = false);
5698  bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5699                                    unsigned InaccessibleBaseID,
5700                                    unsigned AmbigiousBaseConvID,
5701                                    SourceLocation Loc, SourceRange Range,
5702                                    DeclarationName Name,
5703                                    CXXCastPath *BasePath,
5704                                    bool IgnoreAccess = false);
5705
5706  std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5707
5708  bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5709                                         const CXXMethodDecl *Old);
5710
5711  /// CheckOverridingFunctionReturnType - Checks whether the return types are
5712  /// covariant, according to C++ [class.virtual]p5.
5713  bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5714                                         const CXXMethodDecl *Old);
5715
5716  /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5717  /// spec is a subset of base spec.
5718  bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5719                                            const CXXMethodDecl *Old);
5720
5721  bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5722
5723  /// CheckOverrideControl - Check C++11 override control semantics.
5724  void CheckOverrideControl(NamedDecl *D);
5725
5726  /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5727  /// not used in the declaration of an overriding method.
5728  void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5729
5730  /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5731  /// overrides a virtual member function marked 'final', according to
5732  /// C++11 [class.virtual]p4.
5733  bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5734                                              const CXXMethodDecl *Old);
5735
5736
5737  //===--------------------------------------------------------------------===//
5738  // C++ Access Control
5739  //
5740
5741  enum AccessResult {
5742    AR_accessible,
5743    AR_inaccessible,
5744    AR_dependent,
5745    AR_delayed
5746  };
5747
5748  bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5749                                NamedDecl *PrevMemberDecl,
5750                                AccessSpecifier LexicalAS);
5751
5752  AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5753                                           DeclAccessPair FoundDecl);
5754  AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5755                                           DeclAccessPair FoundDecl);
5756  AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5757                                     SourceRange PlacementRange,
5758                                     CXXRecordDecl *NamingClass,
5759                                     DeclAccessPair FoundDecl,
5760                                     bool Diagnose = true);
5761  AccessResult CheckConstructorAccess(SourceLocation Loc,
5762                                      CXXConstructorDecl *D,
5763                                      DeclAccessPair FoundDecl,
5764                                      const InitializedEntity &Entity,
5765                                      bool IsCopyBindingRefToTemp = false);
5766  AccessResult CheckConstructorAccess(SourceLocation Loc,
5767                                      CXXConstructorDecl *D,
5768                                      DeclAccessPair FoundDecl,
5769                                      const InitializedEntity &Entity,
5770                                      const PartialDiagnostic &PDiag);
5771  AccessResult CheckDestructorAccess(SourceLocation Loc,
5772                                     CXXDestructorDecl *Dtor,
5773                                     const PartialDiagnostic &PDiag,
5774                                     QualType objectType = QualType());
5775  AccessResult CheckFriendAccess(NamedDecl *D);
5776  AccessResult CheckMemberAccess(SourceLocation UseLoc,
5777                                 CXXRecordDecl *NamingClass,
5778                                 DeclAccessPair Found);
5779  AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5780                                         Expr *ObjectExpr,
5781                                         Expr *ArgExpr,
5782                                         DeclAccessPair FoundDecl);
5783  AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
5784                                          DeclAccessPair FoundDecl);
5785  AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
5786                                    QualType Base, QualType Derived,
5787                                    const CXXBasePath &Path,
5788                                    unsigned DiagID,
5789                                    bool ForceCheck = false,
5790                                    bool ForceUnprivileged = false);
5791  void CheckLookupAccess(const LookupResult &R);
5792  bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
5793  bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
5794                                            AccessSpecifier access,
5795                                            QualType objectType);
5796
5797  void HandleDependentAccessCheck(const DependentDiagnostic &DD,
5798                         const MultiLevelTemplateArgumentList &TemplateArgs);
5799  void PerformDependentDiagnostics(const DeclContext *Pattern,
5800                        const MultiLevelTemplateArgumentList &TemplateArgs);
5801
5802  void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5803
5804  /// \brief When true, access checking violations are treated as SFINAE
5805  /// failures rather than hard errors.
5806  bool AccessCheckingSFINAE;
5807
5808  enum AbstractDiagSelID {
5809    AbstractNone = -1,
5810    AbstractReturnType,
5811    AbstractParamType,
5812    AbstractVariableType,
5813    AbstractFieldType,
5814    AbstractIvarType,
5815    AbstractSynthesizedIvarType,
5816    AbstractArrayType
5817  };
5818
5819  bool isAbstractType(SourceLocation Loc, QualType T);
5820  bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5821                              TypeDiagnoser &Diagnoser);
5822  template <typename... Ts>
5823  bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5824                              const Ts &...Args) {
5825    BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
5826    return RequireNonAbstractType(Loc, T, Diagnoser);
5827  }
5828
5829  void DiagnoseAbstractType(const CXXRecordDecl *RD);
5830
5831  //===--------------------------------------------------------------------===//
5832  // C++ Overloaded Operators [C++ 13.5]
5833  //
5834
5835  bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
5836
5837  bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
5838
5839  //===--------------------------------------------------------------------===//
5840  // C++ Templates [C++ 14]
5841  //
5842  void FilterAcceptableTemplateNames(LookupResult &R,
5843                                     bool AllowFunctionTemplates = true);
5844  bool hasAnyAcceptableTemplateNames(LookupResult &R,
5845                                     bool AllowFunctionTemplates = true);
5846
5847  void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
5848                          QualType ObjectType, bool EnteringContext,
5849                          bool &MemberOfUnknownSpecialization);
5850
5851  TemplateNameKind isTemplateName(Scope *S,
5852                                  CXXScopeSpec &SS,
5853                                  bool hasTemplateKeyword,
5854                                  UnqualifiedId &Name,
5855                                  ParsedType ObjectType,
5856                                  bool EnteringContext,
5857                                  TemplateTy &Template,
5858                                  bool &MemberOfUnknownSpecialization);
5859
5860  /// Determine whether a particular identifier might be the name in a C++1z
5861  /// deduction-guide declaration.
5862  bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
5863                            SourceLocation NameLoc,
5864                            ParsedTemplateTy *Template = nullptr);
5865
5866  bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
5867                                   SourceLocation IILoc,
5868                                   Scope *S,
5869                                   const CXXScopeSpec *SS,
5870                                   TemplateTy &SuggestedTemplate,
5871                                   TemplateNameKind &SuggestedKind);
5872
5873  bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
5874                                      NamedDecl *Instantiation,
5875                                      bool InstantiatedFromMember,
5876                                      const NamedDecl *Pattern,
5877                                      const NamedDecl *PatternDef,
5878                                      TemplateSpecializationKind TSK,
5879                                      bool Complain = true);
5880
5881  void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
5882  TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
5883
5884  Decl *ActOnTypeParameter(Scope *S, bool Typename,
5885                           SourceLocation EllipsisLoc,
5886                           SourceLocation KeyLoc,
5887                           IdentifierInfo *ParamName,
5888                           SourceLocation ParamNameLoc,
5889                           unsigned Depth, unsigned Position,
5890                           SourceLocation EqualLoc,
5891                           ParsedType DefaultArg);
5892
5893  QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
5894                                             SourceLocation Loc);
5895  QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
5896
5897  Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
5898                                      unsigned Depth,
5899                                      unsigned Position,
5900                                      SourceLocation EqualLoc,
5901                                      Expr *DefaultArg);
5902  Decl *ActOnTemplateTemplateParameter(Scope *S,
5903                                       SourceLocation TmpLoc,
5904                                       TemplateParameterList *Params,
5905                                       SourceLocation EllipsisLoc,
5906                                       IdentifierInfo *ParamName,
5907                                       SourceLocation ParamNameLoc,
5908                                       unsigned Depth,
5909                                       unsigned Position,
5910                                       SourceLocation EqualLoc,
5911                                       ParsedTemplateArgument DefaultArg);
5912
5913  TemplateParameterList *
5914  ActOnTemplateParameterList(unsigned Depth,
5915                             SourceLocation ExportLoc,
5916                             SourceLocation TemplateLoc,
5917                             SourceLocation LAngleLoc,
5918                             ArrayRef<Decl *> Params,
5919                             SourceLocation RAngleLoc,
5920                             Expr *RequiresClause);
5921
5922  /// \brief The context in which we are checking a template parameter list.
5923  enum TemplateParamListContext {
5924    TPC_ClassTemplate,
5925    TPC_VarTemplate,
5926    TPC_FunctionTemplate,
5927    TPC_ClassTemplateMember,
5928    TPC_FriendClassTemplate,
5929    TPC_FriendFunctionTemplate,
5930    TPC_FriendFunctionTemplateDefinition,
5931    TPC_TypeAliasTemplate
5932  };
5933
5934  bool CheckTemplateParameterList(TemplateParameterList *NewParams,
5935                                  TemplateParameterList *OldParams,
5936                                  TemplateParamListContext TPC);
5937  TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
5938      SourceLocation DeclStartLoc, SourceLocation DeclLoc,
5939      const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
5940      ArrayRef<TemplateParameterList *> ParamLists,
5941      bool IsFriend, bool &IsMemberSpecialization, bool &Invalid);
5942
5943  DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
5944                                SourceLocation KWLoc, CXXScopeSpec &SS,
5945                                IdentifierInfo *Name, SourceLocation NameLoc,
5946                                AttributeList *Attr,
5947                                TemplateParameterList *TemplateParams,
5948                                AccessSpecifier AS,
5949                                SourceLocation ModulePrivateLoc,
5950                                SourceLocation FriendLoc,
5951                                unsigned NumOuterTemplateParamLists,
5952                            TemplateParameterList **OuterTemplateParamLists,
5953                                SkipBodyInfo *SkipBody = nullptr);
5954
5955  TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
5956                                                    QualType NTTPType,
5957                                                    SourceLocation Loc);
5958
5959  void translateTemplateArguments(const ASTTemplateArgsPtr &In,
5960                                  TemplateArgumentListInfo &Out);
5961
5962  void NoteAllFoundTemplates(TemplateName Name);
5963
5964  QualType CheckTemplateIdType(TemplateName Template,
5965                               SourceLocation TemplateLoc,
5966                              TemplateArgumentListInfo &TemplateArgs);
5967
5968  TypeResult
5969  ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5970                      TemplateTy Template, IdentifierInfo *TemplateII,
5971                      SourceLocation TemplateIILoc,
5972                      SourceLocation LAngleLoc,
5973                      ASTTemplateArgsPtr TemplateArgs,
5974                      SourceLocation RAngleLoc,
5975                      bool IsCtorOrDtorName = false,
5976                      bool IsClassName = false);
5977
5978  /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
5979  /// such as \c class T::template apply<U>.
5980  TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
5981                                    TypeSpecifierType TagSpec,
5982                                    SourceLocation TagLoc,
5983                                    CXXScopeSpec &SS,
5984                                    SourceLocation TemplateKWLoc,
5985                                    TemplateTy TemplateD,
5986                                    SourceLocation TemplateLoc,
5987                                    SourceLocation LAngleLoc,
5988                                    ASTTemplateArgsPtr TemplateArgsIn,
5989                                    SourceLocation RAngleLoc);
5990
5991  DeclResult ActOnVarTemplateSpecialization(
5992      Scope *S, Declarator &D, TypeSourceInfo *DI,
5993      SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
5994      StorageClass SC, bool IsPartialSpecialization);
5995
5996  DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
5997                                SourceLocation TemplateLoc,
5998                                SourceLocation TemplateNameLoc,
5999                                const TemplateArgumentListInfo &TemplateArgs);
6000
6001  ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
6002                                const DeclarationNameInfo &NameInfo,
6003                                VarTemplateDecl *Template,
6004                                SourceLocation TemplateLoc,
6005                                const TemplateArgumentListInfo *TemplateArgs);
6006
6007  ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
6008                                 SourceLocation TemplateKWLoc,
6009                                 LookupResult &R,
6010                                 bool RequiresADL,
6011                               const TemplateArgumentListInfo *TemplateArgs);
6012
6013  ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
6014                                          SourceLocation TemplateKWLoc,
6015                               const DeclarationNameInfo &NameInfo,
6016                               const TemplateArgumentListInfo *TemplateArgs);
6017
6018  TemplateNameKind ActOnDependentTemplateName(
6019      Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6020      UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
6021      TemplateTy &Template, bool AllowInjectedClassName = false);
6022
6023  DeclResult
6024  ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
6025                                   SourceLocation KWLoc,
6026                                   SourceLocation ModulePrivateLoc,
6027                                   TemplateIdAnnotation &TemplateId,
6028                                   AttributeList *Attr,
6029                                 MultiTemplateParamsArg TemplateParameterLists,
6030                                   SkipBodyInfo *SkipBody = nullptr);
6031
6032  bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
6033                                              TemplateDecl *PrimaryTemplate,
6034                                              unsigned NumExplicitArgs,
6035                                              ArrayRef<TemplateArgument> Args);
6036  void CheckTemplatePartialSpecialization(
6037      ClassTemplatePartialSpecializationDecl *Partial);
6038  void CheckTemplatePartialSpecialization(
6039      VarTemplatePartialSpecializationDecl *Partial);
6040
6041  Decl *ActOnTemplateDeclarator(Scope *S,
6042                                MultiTemplateParamsArg TemplateParameterLists,
6043                                Declarator &D);
6044
6045  bool
6046  CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6047                                         TemplateSpecializationKind NewTSK,
6048                                         NamedDecl *PrevDecl,
6049                                         TemplateSpecializationKind PrevTSK,
6050                                         SourceLocation PrevPtOfInstantiation,
6051                                         bool &SuppressNew);
6052
6053  bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6054                    const TemplateArgumentListInfo &ExplicitTemplateArgs,
6055                                                    LookupResult &Previous);
6056
6057  bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
6058                         TemplateArgumentListInfo *ExplicitTemplateArgs,
6059                                           LookupResult &Previous);
6060  bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6061
6062  DeclResult
6063  ActOnExplicitInstantiation(Scope *S,
6064                             SourceLocation ExternLoc,
6065                             SourceLocation TemplateLoc,
6066                             unsigned TagSpec,
6067                             SourceLocation KWLoc,
6068                             const CXXScopeSpec &SS,
6069                             TemplateTy Template,
6070                             SourceLocation TemplateNameLoc,
6071                             SourceLocation LAngleLoc,
6072                             ASTTemplateArgsPtr TemplateArgs,
6073                             SourceLocation RAngleLoc,
6074                             AttributeList *Attr);
6075
6076  DeclResult
6077  ActOnExplicitInstantiation(Scope *S,
6078                             SourceLocation ExternLoc,
6079                             SourceLocation TemplateLoc,
6080                             unsigned TagSpec,
6081                             SourceLocation KWLoc,
6082                             CXXScopeSpec &SS,
6083                             IdentifierInfo *Name,
6084                             SourceLocation NameLoc,
6085                             AttributeList *Attr);
6086
6087  DeclResult ActOnExplicitInstantiation(Scope *S,
6088                                        SourceLocation ExternLoc,
6089                                        SourceLocation TemplateLoc,
6090                                        Declarator &D);
6091
6092  TemplateArgumentLoc
6093  SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
6094                                          SourceLocation TemplateLoc,
6095                                          SourceLocation RAngleLoc,
6096                                          Decl *Param,
6097                                          SmallVectorImpl<TemplateArgument>
6098                                            &Converted,
6099                                          bool &HasDefaultArg);
6100
6101  /// \brief Specifies the context in which a particular template
6102  /// argument is being checked.
6103  enum CheckTemplateArgumentKind {
6104    /// \brief The template argument was specified in the code or was
6105    /// instantiated with some deduced template arguments.
6106    CTAK_Specified,
6107
6108    /// \brief The template argument was deduced via template argument
6109    /// deduction.
6110    CTAK_Deduced,
6111
6112    /// \brief The template argument was deduced from an array bound
6113    /// via template argument deduction.
6114    CTAK_DeducedFromArrayBound
6115  };
6116
6117  bool CheckTemplateArgument(NamedDecl *Param,
6118                             TemplateArgumentLoc &Arg,
6119                             NamedDecl *Template,
6120                             SourceLocation TemplateLoc,
6121                             SourceLocation RAngleLoc,
6122                             unsigned ArgumentPackIndex,
6123                           SmallVectorImpl<TemplateArgument> &Converted,
6124                             CheckTemplateArgumentKind CTAK = CTAK_Specified);
6125
6126  /// \brief Check that the given template arguments can be be provided to
6127  /// the given template, converting the arguments along the way.
6128  ///
6129  /// \param Template The template to which the template arguments are being
6130  /// provided.
6131  ///
6132  /// \param TemplateLoc The location of the template name in the source.
6133  ///
6134  /// \param TemplateArgs The list of template arguments. If the template is
6135  /// a template template parameter, this function may extend the set of
6136  /// template arguments to also include substituted, defaulted template
6137  /// arguments.
6138  ///
6139  /// \param PartialTemplateArgs True if the list of template arguments is
6140  /// intentionally partial, e.g., because we're checking just the initial
6141  /// set of template arguments.
6142  ///
6143  /// \param Converted Will receive the converted, canonicalized template
6144  /// arguments.
6145  ///
6146  /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
6147  /// contain the converted forms of the template arguments as written.
6148  /// Otherwise, \p TemplateArgs will not be modified.
6149  ///
6150  /// \returns true if an error occurred, false otherwise.
6151  bool CheckTemplateArgumentList(TemplateDecl *Template,
6152                                 SourceLocation TemplateLoc,
6153                                 TemplateArgumentListInfo &TemplateArgs,
6154                                 bool PartialTemplateArgs,
6155                                 SmallVectorImpl<TemplateArgument> &Converted,
6156                                 bool UpdateArgsWithConversions = true);
6157
6158  bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
6159                                 TemplateArgumentLoc &Arg,
6160                           SmallVectorImpl<TemplateArgument> &Converted);
6161
6162  bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
6163                             TypeSourceInfo *Arg);
6164  ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6165                                   QualType InstantiatedParamType, Expr *Arg,
6166                                   TemplateArgument &Converted,
6167                               CheckTemplateArgumentKind CTAK = CTAK_Specified);
6168  bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
6169                             TemplateArgumentLoc &Arg,
6170                             unsigned ArgumentPackIndex);
6171
6172  ExprResult
6173  BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6174                                          QualType ParamType,
6175                                          SourceLocation Loc);
6176  ExprResult
6177  BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6178                                              SourceLocation Loc);
6179
6180  /// \brief Enumeration describing how template parameter lists are compared
6181  /// for equality.
6182  enum TemplateParameterListEqualKind {
6183    /// \brief We are matching the template parameter lists of two templates
6184    /// that might be redeclarations.
6185    ///
6186    /// \code
6187    /// template<typename T> struct X;
6188    /// template<typename T> struct X;
6189    /// \endcode
6190    TPL_TemplateMatch,
6191
6192    /// \brief We are matching the template parameter lists of two template
6193    /// template parameters as part of matching the template parameter lists
6194    /// of two templates that might be redeclarations.
6195    ///
6196    /// \code
6197    /// template<template<int I> class TT> struct X;
6198    /// template<template<int Value> class Other> struct X;
6199    /// \endcode
6200    TPL_TemplateTemplateParmMatch,
6201
6202    /// \brief We are matching the template parameter lists of a template
6203    /// template argument against the template parameter lists of a template
6204    /// template parameter.
6205    ///
6206    /// \code
6207    /// template<template<int Value> class Metafun> struct X;
6208    /// template<int Value> struct integer_c;
6209    /// X<integer_c> xic;
6210    /// \endcode
6211    TPL_TemplateTemplateArgumentMatch
6212  };
6213
6214  bool TemplateParameterListsAreEqual(TemplateParameterList *New,
6215                                      TemplateParameterList *Old,
6216                                      bool Complain,
6217                                      TemplateParameterListEqualKind Kind,
6218                                      SourceLocation TemplateArgLoc
6219                                        = SourceLocation());
6220
6221  bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
6222
6223  /// \brief Called when the parser has parsed a C++ typename
6224  /// specifier, e.g., "typename T::type".
6225  ///
6226  /// \param S The scope in which this typename type occurs.
6227  /// \param TypenameLoc the location of the 'typename' keyword
6228  /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6229  /// \param II the identifier we're retrieving (e.g., 'type' in the example).
6230  /// \param IdLoc the location of the identifier.
6231  TypeResult
6232  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6233                    const CXXScopeSpec &SS, const IdentifierInfo &II,
6234                    SourceLocation IdLoc);
6235
6236  /// \brief Called when the parser has parsed a C++ typename
6237  /// specifier that ends in a template-id, e.g.,
6238  /// "typename MetaFun::template apply<T1, T2>".
6239  ///
6240  /// \param S The scope in which this typename type occurs.
6241  /// \param TypenameLoc the location of the 'typename' keyword
6242  /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6243  /// \param TemplateLoc the location of the 'template' keyword, if any.
6244  /// \param TemplateName The template name.
6245  /// \param TemplateII The identifier used to name the template.
6246  /// \param TemplateIILoc The location of the template name.
6247  /// \param LAngleLoc The location of the opening angle bracket  ('<').
6248  /// \param TemplateArgs The template arguments.
6249  /// \param RAngleLoc The location of the closing angle bracket  ('>').
6250  TypeResult
6251  ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6252                    const CXXScopeSpec &SS,
6253                    SourceLocation TemplateLoc,
6254                    TemplateTy TemplateName,
6255                    IdentifierInfo *TemplateII,
6256                    SourceLocation TemplateIILoc,
6257                    SourceLocation LAngleLoc,
6258                    ASTTemplateArgsPtr TemplateArgs,
6259                    SourceLocation RAngleLoc);
6260
6261  QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
6262                             SourceLocation KeywordLoc,
6263                             NestedNameSpecifierLoc QualifierLoc,
6264                             const IdentifierInfo &II,
6265                             SourceLocation IILoc);
6266
6267  TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6268                                                    SourceLocation Loc,
6269                                                    DeclarationName Name);
6270  bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
6271
6272  ExprResult RebuildExprInCurrentInstantiation(Expr *E);
6273  bool RebuildTemplateParamsInCurrentInstantiation(
6274                                                TemplateParameterList *Params);
6275
6276  std::string
6277  getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6278                                  const TemplateArgumentList &Args);
6279
6280  std::string
6281  getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6282                                  const TemplateArgument *Args,
6283                                  unsigned NumArgs);
6284
6285  //===--------------------------------------------------------------------===//
6286  // C++ Variadic Templates (C++0x [temp.variadic])
6287  //===--------------------------------------------------------------------===//
6288
6289  /// Determine whether an unexpanded parameter pack might be permitted in this
6290  /// location. Useful for error recovery.
6291  bool isUnexpandedParameterPackPermitted();
6292
6293  /// \brief The context in which an unexpanded parameter pack is
6294  /// being diagnosed.
6295  ///
6296  /// Note that the values of this enumeration line up with the first
6297  /// argument to the \c err_unexpanded_parameter_pack diagnostic.
6298  enum UnexpandedParameterPackContext {
6299    /// \brief An arbitrary expression.
6300    UPPC_Expression = 0,
6301
6302    /// \brief The base type of a class type.
6303    UPPC_BaseType,
6304
6305    /// \brief The type of an arbitrary declaration.
6306    UPPC_DeclarationType,
6307
6308    /// \brief The type of a data member.
6309    UPPC_DataMemberType,
6310
6311    /// \brief The size of a bit-field.
6312    UPPC_BitFieldWidth,
6313
6314    /// \brief The expression in a static assertion.
6315    UPPC_StaticAssertExpression,
6316
6317    /// \brief The fixed underlying type of an enumeration.
6318    UPPC_FixedUnderlyingType,
6319
6320    /// \brief The enumerator value.
6321    UPPC_EnumeratorValue,
6322
6323    /// \brief A using declaration.
6324    UPPC_UsingDeclaration,
6325
6326    /// \brief A friend declaration.
6327    UPPC_FriendDeclaration,
6328
6329    /// \brief A declaration qualifier.
6330    UPPC_DeclarationQualifier,
6331
6332    /// \brief An initializer.
6333    UPPC_Initializer,
6334
6335    /// \brief A default argument.
6336    UPPC_DefaultArgument,
6337
6338    /// \brief The type of a non-type template parameter.
6339    UPPC_NonTypeTemplateParameterType,
6340
6341    /// \brief The type of an exception.
6342    UPPC_ExceptionType,
6343
6344    /// \brief Partial specialization.
6345    UPPC_PartialSpecialization,
6346
6347    /// \brief Microsoft __if_exists.
6348    UPPC_IfExists,
6349
6350    /// \brief Microsoft __if_not_exists.
6351    UPPC_IfNotExists,
6352
6353    /// \brief Lambda expression.
6354    UPPC_Lambda,
6355
6356    /// \brief Block expression,
6357    UPPC_Block
6358  };
6359
6360  /// \brief Diagnose unexpanded parameter packs.
6361  ///
6362  /// \param Loc The location at which we should emit the diagnostic.
6363  ///
6364  /// \param UPPC The context in which we are diagnosing unexpanded
6365  /// parameter packs.
6366  ///
6367  /// \param Unexpanded the set of unexpanded parameter packs.
6368  ///
6369  /// \returns true if an error occurred, false otherwise.
6370  bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
6371                                        UnexpandedParameterPackContext UPPC,
6372                                  ArrayRef<UnexpandedParameterPack> Unexpanded);
6373
6374  /// \brief If the given type contains an unexpanded parameter pack,
6375  /// diagnose the error.
6376  ///
6377  /// \param Loc The source location where a diagnostc should be emitted.
6378  ///
6379  /// \param T The type that is being checked for unexpanded parameter
6380  /// packs.
6381  ///
6382  /// \returns true if an error occurred, false otherwise.
6383  bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
6384                                       UnexpandedParameterPackContext UPPC);
6385
6386  /// \brief If the given expression contains an unexpanded parameter
6387  /// pack, diagnose the error.
6388  ///
6389  /// \param E The expression that is being checked for unexpanded
6390  /// parameter packs.
6391  ///
6392  /// \returns true if an error occurred, false otherwise.
6393  bool DiagnoseUnexpandedParameterPack(Expr *E,
6394                       UnexpandedParameterPackContext UPPC = UPPC_Expression);
6395
6396  /// \brief If the given nested-name-specifier contains an unexpanded
6397  /// parameter pack, diagnose the error.
6398  ///
6399  /// \param SS The nested-name-specifier that is being checked for
6400  /// unexpanded parameter packs.
6401  ///
6402  /// \returns true if an error occurred, false otherwise.
6403  bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
6404                                       UnexpandedParameterPackContext UPPC);
6405
6406  /// \brief If the given name contains an unexpanded parameter pack,
6407  /// diagnose the error.
6408  ///
6409  /// \param NameInfo The name (with source location information) that
6410  /// is being checked for unexpanded parameter packs.
6411  ///
6412  /// \returns true if an error occurred, false otherwise.
6413  bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6414                                       UnexpandedParameterPackContext UPPC);
6415
6416  /// \brief If the given template name contains an unexpanded parameter pack,
6417  /// diagnose the error.
6418  ///
6419  /// \param Loc The location of the template name.
6420  ///
6421  /// \param Template The template name that is being checked for unexpanded
6422  /// parameter packs.
6423  ///
6424  /// \returns true if an error occurred, false otherwise.
6425  bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6426                                       TemplateName Template,
6427                                       UnexpandedParameterPackContext UPPC);
6428
6429  /// \brief If the given template argument contains an unexpanded parameter
6430  /// pack, diagnose the error.
6431  ///
6432  /// \param Arg The template argument that is being checked for unexpanded
6433  /// parameter packs.
6434  ///
6435  /// \returns true if an error occurred, false otherwise.
6436  bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6437                                       UnexpandedParameterPackContext UPPC);
6438
6439  /// \brief Collect the set of unexpanded parameter packs within the given
6440  /// template argument.
6441  ///
6442  /// \param Arg The template argument that will be traversed to find
6443  /// unexpanded parameter packs.
6444  void collectUnexpandedParameterPacks(TemplateArgument Arg,
6445                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6446
6447  /// \brief Collect the set of unexpanded parameter packs within the given
6448  /// template argument.
6449  ///
6450  /// \param Arg The template argument that will be traversed to find
6451  /// unexpanded parameter packs.
6452  void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6453                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6454
6455  /// \brief Collect the set of unexpanded parameter packs within the given
6456  /// type.
6457  ///
6458  /// \param T The type that will be traversed to find
6459  /// unexpanded parameter packs.
6460  void collectUnexpandedParameterPacks(QualType T,
6461                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6462
6463  /// \brief Collect the set of unexpanded parameter packs within the given
6464  /// type.
6465  ///
6466  /// \param TL The type that will be traversed to find
6467  /// unexpanded parameter packs.
6468  void collectUnexpandedParameterPacks(TypeLoc TL,
6469                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6470
6471  /// \brief Collect the set of unexpanded parameter packs within the given
6472  /// nested-name-specifier.
6473  ///
6474  /// \param NNS The nested-name-specifier that will be traversed to find
6475  /// unexpanded parameter packs.
6476  void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
6477                         SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6478
6479  /// \brief Collect the set of unexpanded parameter packs within the given
6480  /// name.
6481  ///
6482  /// \param NameInfo The name that will be traversed to find
6483  /// unexpanded parameter packs.
6484  void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6485                         SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6486
6487  /// \brief Invoked when parsing a template argument followed by an
6488  /// ellipsis, which creates a pack expansion.
6489  ///
6490  /// \param Arg The template argument preceding the ellipsis, which
6491  /// may already be invalid.
6492  ///
6493  /// \param EllipsisLoc The location of the ellipsis.
6494  ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6495                                            SourceLocation EllipsisLoc);
6496
6497  /// \brief Invoked when parsing a type followed by an ellipsis, which
6498  /// creates a pack expansion.
6499  ///
6500  /// \param Type The type preceding the ellipsis, which will become
6501  /// the pattern of the pack expansion.
6502  ///
6503  /// \param EllipsisLoc The location of the ellipsis.
6504  TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6505
6506  /// \brief Construct a pack expansion type from the pattern of the pack
6507  /// expansion.
6508  TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6509                                     SourceLocation EllipsisLoc,
6510                                     Optional<unsigned> NumExpansions);
6511
6512  /// \brief Construct a pack expansion type from the pattern of the pack
6513  /// expansion.
6514  QualType CheckPackExpansion(QualType Pattern,
6515                              SourceRange PatternRange,
6516                              SourceLocation EllipsisLoc,
6517                              Optional<unsigned> NumExpansions);
6518
6519  /// \brief Invoked when parsing an expression followed by an ellipsis, which
6520  /// creates a pack expansion.
6521  ///
6522  /// \param Pattern The expression preceding the ellipsis, which will become
6523  /// the pattern of the pack expansion.
6524  ///
6525  /// \param EllipsisLoc The location of the ellipsis.
6526  ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6527
6528  /// \brief Invoked when parsing an expression followed by an ellipsis, which
6529  /// creates a pack expansion.
6530  ///
6531  /// \param Pattern The expression preceding the ellipsis, which will become
6532  /// the pattern of the pack expansion.
6533  ///
6534  /// \param EllipsisLoc The location of the ellipsis.
6535  ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6536                                Optional<unsigned> NumExpansions);
6537
6538  /// \brief Determine whether we could expand a pack expansion with the
6539  /// given set of parameter packs into separate arguments by repeatedly
6540  /// transforming the pattern.
6541  ///
6542  /// \param EllipsisLoc The location of the ellipsis that identifies the
6543  /// pack expansion.
6544  ///
6545  /// \param PatternRange The source range that covers the entire pattern of
6546  /// the pack expansion.
6547  ///
6548  /// \param Unexpanded The set of unexpanded parameter packs within the
6549  /// pattern.
6550  ///
6551  /// \param ShouldExpand Will be set to \c true if the transformer should
6552  /// expand the corresponding pack expansions into separate arguments. When
6553  /// set, \c NumExpansions must also be set.
6554  ///
6555  /// \param RetainExpansion Whether the caller should add an unexpanded
6556  /// pack expansion after all of the expanded arguments. This is used
6557  /// when extending explicitly-specified template argument packs per
6558  /// C++0x [temp.arg.explicit]p9.
6559  ///
6560  /// \param NumExpansions The number of separate arguments that will be in
6561  /// the expanded form of the corresponding pack expansion. This is both an
6562  /// input and an output parameter, which can be set by the caller if the
6563  /// number of expansions is known a priori (e.g., due to a prior substitution)
6564  /// and will be set by the callee when the number of expansions is known.
6565  /// The callee must set this value when \c ShouldExpand is \c true; it may
6566  /// set this value in other cases.
6567  ///
6568  /// \returns true if an error occurred (e.g., because the parameter packs
6569  /// are to be instantiated with arguments of different lengths), false
6570  /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6571  /// must be set.
6572  bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6573                                       SourceRange PatternRange,
6574                             ArrayRef<UnexpandedParameterPack> Unexpanded,
6575                             const MultiLevelTemplateArgumentList &TemplateArgs,
6576                                       bool &ShouldExpand,
6577                                       bool &RetainExpansion,
6578                                       Optional<unsigned> &NumExpansions);
6579
6580  /// \brief Determine the number of arguments in the given pack expansion
6581  /// type.
6582  ///
6583  /// This routine assumes that the number of arguments in the expansion is
6584  /// consistent across all of the unexpanded parameter packs in its pattern.
6585  ///
6586  /// Returns an empty Optional if the type can't be expanded.
6587  Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6588      const MultiLevelTemplateArgumentList &TemplateArgs);
6589
6590  /// \brief Determine whether the given declarator contains any unexpanded
6591  /// parameter packs.
6592  ///
6593  /// This routine is used by the parser to disambiguate function declarators
6594  /// with an ellipsis prior to the ')', e.g.,
6595  ///
6596  /// \code
6597  ///   void f(T...);
6598  /// \endcode
6599  ///
6600  /// To determine whether we have an (unnamed) function parameter pack or
6601  /// a variadic function.
6602  ///
6603  /// \returns true if the declarator contains any unexpanded parameter packs,
6604  /// false otherwise.
6605  bool containsUnexpandedParameterPacks(Declarator &D);
6606
6607  /// \brief Returns the pattern of the pack expansion for a template argument.
6608  ///
6609  /// \param OrigLoc The template argument to expand.
6610  ///
6611  /// \param Ellipsis Will be set to the location of the ellipsis.
6612  ///
6613  /// \param NumExpansions Will be set to the number of expansions that will
6614  /// be generated from this pack expansion, if known a priori.
6615  TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6616      TemplateArgumentLoc OrigLoc,
6617      SourceLocation &Ellipsis,
6618      Optional<unsigned> &NumExpansions) const;
6619
6620  /// Given a template argument that contains an unexpanded parameter pack, but
6621  /// which has already been substituted, attempt to determine the number of
6622  /// elements that will be produced once this argument is fully-expanded.
6623  ///
6624  /// This is intended for use when transforming 'sizeof...(Arg)' in order to
6625  /// avoid actually expanding the pack where possible.
6626  Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
6627
6628  //===--------------------------------------------------------------------===//
6629  // C++ Template Argument Deduction (C++ [temp.deduct])
6630  //===--------------------------------------------------------------------===//
6631
6632  /// Adjust the type \p ArgFunctionType to match the calling convention,
6633  /// noreturn, and optionally the exception specification of \p FunctionType.
6634  /// Deduction often wants to ignore these properties when matching function
6635  /// types.
6636  QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
6637                               bool AdjustExceptionSpec = false);
6638
6639  /// \brief Describes the result of template argument deduction.
6640  ///
6641  /// The TemplateDeductionResult enumeration describes the result of
6642  /// template argument deduction, as returned from
6643  /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6644  /// structure provides additional information about the results of
6645  /// template argument deduction, e.g., the deduced template argument
6646  /// list (if successful) or the specific template parameters or
6647  /// deduced arguments that were involved in the failure.
6648  enum TemplateDeductionResult {
6649    /// \brief Template argument deduction was successful.
6650    TDK_Success = 0,
6651    /// \brief The declaration was invalid; do nothing.
6652    TDK_Invalid,
6653    /// \brief Template argument deduction exceeded the maximum template
6654    /// instantiation depth (which has already been diagnosed).
6655    TDK_InstantiationDepth,
6656    /// \brief Template argument deduction did not deduce a value
6657    /// for every template parameter.
6658    TDK_Incomplete,
6659    /// \brief Template argument deduction produced inconsistent
6660    /// deduced values for the given template parameter.
6661    TDK_Inconsistent,
6662    /// \brief Template argument deduction failed due to inconsistent
6663    /// cv-qualifiers on a template parameter type that would
6664    /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6665    /// but were given a non-const "X".
6666    TDK_Underqualified,
6667    /// \brief Substitution of the deduced template argument values
6668    /// resulted in an error.
6669    TDK_SubstitutionFailure,
6670    /// \brief After substituting deduced template arguments, a dependent
6671    /// parameter type did not match the corresponding argument.
6672    TDK_DeducedMismatch,
6673    /// \brief After substituting deduced template arguments, an element of
6674    /// a dependent parameter type did not match the corresponding element
6675    /// of the corresponding argument (when deducing from an initializer list).
6676    TDK_DeducedMismatchNested,
6677    /// \brief A non-depnedent component of the parameter did not match the
6678    /// corresponding component of the argument.
6679    TDK_NonDeducedMismatch,
6680    /// \brief When performing template argument deduction for a function
6681    /// template, there were too many call arguments.
6682    TDK_TooManyArguments,
6683    /// \brief When performing template argument deduction for a function
6684    /// template, there were too few call arguments.
6685    TDK_TooFewArguments,
6686    /// \brief The explicitly-specified template arguments were not valid
6687    /// template arguments for the given template.
6688    TDK_InvalidExplicitArguments,
6689    /// \brief Checking non-dependent argument conversions failed.
6690    TDK_NonDependentConversionFailure,
6691    /// \brief Deduction failed; that's all we know.
6692    TDK_MiscellaneousDeductionFailure,
6693    /// \brief CUDA Target attributes do not match.
6694    TDK_CUDATargetMismatch
6695  };
6696
6697  TemplateDeductionResult
6698  DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6699                          const TemplateArgumentList &TemplateArgs,
6700                          sema::TemplateDeductionInfo &Info);
6701
6702  TemplateDeductionResult
6703  DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6704                          const TemplateArgumentList &TemplateArgs,
6705                          sema::TemplateDeductionInfo &Info);
6706
6707  TemplateDeductionResult SubstituteExplicitTemplateArguments(
6708      FunctionTemplateDecl *FunctionTemplate,
6709      TemplateArgumentListInfo &ExplicitTemplateArgs,
6710      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6711      SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6712      sema::TemplateDeductionInfo &Info);
6713
6714  /// brief A function argument from which we performed template argument
6715  // deduction for a call.
6716  struct OriginalCallArg {
6717    OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
6718                    unsigned ArgIdx, QualType OriginalArgType)
6719        : OriginalParamType(OriginalParamType),
6720          DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
6721          OriginalArgType(OriginalArgType) {}
6722
6723    QualType OriginalParamType;
6724    bool DecomposedParam;
6725    unsigned ArgIdx;
6726    QualType OriginalArgType;
6727  };
6728
6729  TemplateDeductionResult FinishTemplateArgumentDeduction(
6730      FunctionTemplateDecl *FunctionTemplate,
6731      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6732      unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
6733      sema::TemplateDeductionInfo &Info,
6734      SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
6735      bool PartialOverloading = false,
6736      llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
6737
6738  TemplateDeductionResult DeduceTemplateArguments(
6739      FunctionTemplateDecl *FunctionTemplate,
6740      TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6741      FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
6742      bool PartialOverloading,
6743      llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
6744
6745  TemplateDeductionResult
6746  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6747                          TemplateArgumentListInfo *ExplicitTemplateArgs,
6748                          QualType ArgFunctionType,
6749                          FunctionDecl *&Specialization,
6750                          sema::TemplateDeductionInfo &Info,
6751                          bool IsAddressOfFunction = false);
6752
6753  TemplateDeductionResult
6754  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6755                          QualType ToType,
6756                          CXXConversionDecl *&Specialization,
6757                          sema::TemplateDeductionInfo &Info);
6758
6759  TemplateDeductionResult
6760  DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6761                          TemplateArgumentListInfo *ExplicitTemplateArgs,
6762                          FunctionDecl *&Specialization,
6763                          sema::TemplateDeductionInfo &Info,
6764                          bool IsAddressOfFunction = false);
6765
6766  /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
6767  QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
6768  /// \brief Substitute Replacement for auto in TypeWithAuto
6769  TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
6770                                          QualType Replacement);
6771  /// \brief Completely replace the \c auto in \p TypeWithAuto by
6772  /// \p Replacement. This does not retain any \c auto type sugar.
6773  QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
6774
6775  /// \brief Result type of DeduceAutoType.
6776  enum DeduceAutoResult {
6777    DAR_Succeeded,
6778    DAR_Failed,
6779    DAR_FailedAlreadyDiagnosed
6780  };
6781
6782  DeduceAutoResult
6783  DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
6784                 Optional<unsigned> DependentDeductionDepth = None);
6785  DeduceAutoResult
6786  DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
6787                 Optional<unsigned> DependentDeductionDepth = None);
6788  void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
6789  bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
6790                        bool Diagnose = true);
6791
6792  /// \brief Declare implicit deduction guides for a class template if we've
6793  /// not already done so.
6794  void DeclareImplicitDeductionGuides(TemplateDecl *Template,
6795                                      SourceLocation Loc);
6796
6797  QualType DeduceTemplateSpecializationFromInitializer(
6798      TypeSourceInfo *TInfo, const InitializedEntity &Entity,
6799      const InitializationKind &Kind, MultiExprArg Init);
6800
6801  QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
6802                                        QualType Type, TypeSourceInfo *TSI,
6803                                        SourceRange Range, bool DirectInit,
6804                                        Expr *Init);
6805
6806  TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
6807
6808  bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
6809                                        SourceLocation ReturnLoc,
6810                                        Expr *&RetExpr, AutoType *AT);
6811
6812  FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
6813                                                   FunctionTemplateDecl *FT2,
6814                                                   SourceLocation Loc,
6815                                           TemplatePartialOrderingContext TPOC,
6816                                                   unsigned NumCallArguments1,
6817                                                   unsigned NumCallArguments2);
6818  UnresolvedSetIterator
6819  getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
6820                     TemplateSpecCandidateSet &FailedCandidates,
6821                     SourceLocation Loc,
6822                     const PartialDiagnostic &NoneDiag,
6823                     const PartialDiagnostic &AmbigDiag,
6824                     const PartialDiagnostic &CandidateDiag,
6825                     bool Complain = true, QualType TargetType = QualType());
6826
6827  ClassTemplatePartialSpecializationDecl *
6828  getMoreSpecializedPartialSpecialization(
6829                                  ClassTemplatePartialSpecializationDecl *PS1,
6830                                  ClassTemplatePartialSpecializationDecl *PS2,
6831                                  SourceLocation Loc);
6832
6833  bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
6834                                    sema::TemplateDeductionInfo &Info);
6835
6836  VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
6837      VarTemplatePartialSpecializationDecl *PS1,
6838      VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
6839
6840  bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
6841                                    sema::TemplateDeductionInfo &Info);
6842
6843  bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
6844      TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc);
6845
6846  void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
6847                                  bool OnlyDeduced,
6848                                  unsigned Depth,
6849                                  llvm::SmallBitVector &Used);
6850  void MarkDeducedTemplateParameters(
6851                                  const FunctionTemplateDecl *FunctionTemplate,
6852                                  llvm::SmallBitVector &Deduced) {
6853    return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
6854  }
6855  static void MarkDeducedTemplateParameters(ASTContext &Ctx,
6856                                  const FunctionTemplateDecl *FunctionTemplate,
6857                                  llvm::SmallBitVector &Deduced);
6858
6859  //===--------------------------------------------------------------------===//
6860  // C++ Template Instantiation
6861  //
6862
6863  MultiLevelTemplateArgumentList
6864  getTemplateInstantiationArgs(NamedDecl *D,
6865                               const TemplateArgumentList *Innermost = nullptr,
6866                               bool RelativeToPrimary = false,
6867                               const FunctionDecl *Pattern = nullptr);
6868
6869  /// A context in which code is being synthesized (where a source location
6870  /// alone is not sufficient to identify the context). This covers template
6871  /// instantiation and various forms of implicitly-generated functions.
6872  struct CodeSynthesisContext {
6873    /// \brief The kind of template instantiation we are performing
6874    enum SynthesisKind {
6875      /// We are instantiating a template declaration. The entity is
6876      /// the declaration we're instantiating (e.g., a CXXRecordDecl).
6877      TemplateInstantiation,
6878
6879      /// We are instantiating a default argument for a template
6880      /// parameter. The Entity is the template parameter whose argument is
6881      /// being instantiated, the Template is the template, and the
6882      /// TemplateArgs/NumTemplateArguments provide the template arguments as
6883      /// specified.
6884      DefaultTemplateArgumentInstantiation,
6885
6886      /// We are instantiating a default argument for a function.
6887      /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
6888      /// provides the template arguments as specified.
6889      DefaultFunctionArgumentInstantiation,
6890
6891      /// We are substituting explicit template arguments provided for
6892      /// a function template. The entity is a FunctionTemplateDecl.
6893      ExplicitTemplateArgumentSubstitution,
6894
6895      /// We are substituting template argument determined as part of
6896      /// template argument deduction for either a class template
6897      /// partial specialization or a function template. The
6898      /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
6899      /// a TemplateDecl.
6900      DeducedTemplateArgumentSubstitution,
6901
6902      /// We are substituting prior template arguments into a new
6903      /// template parameter. The template parameter itself is either a
6904      /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
6905      PriorTemplateArgumentSubstitution,
6906
6907      /// We are checking the validity of a default template argument that
6908      /// has been used when naming a template-id.
6909      DefaultTemplateArgumentChecking,
6910
6911      /// We are instantiating the exception specification for a function
6912      /// template which was deferred until it was needed.
6913      ExceptionSpecInstantiation,
6914
6915      /// We are declaring an implicit special member function.
6916      DeclaringSpecialMember,
6917    } Kind;
6918
6919    /// \brief Was the enclosing context a non-instantiation SFINAE context?
6920    bool SavedInNonInstantiationSFINAEContext;
6921
6922    /// \brief The point of instantiation or synthesis within the source code.
6923    SourceLocation PointOfInstantiation;
6924
6925    /// \brief The entity that is being synthesized.
6926    Decl *Entity;
6927
6928    /// \brief The template (or partial specialization) in which we are
6929    /// performing the instantiation, for substitutions of prior template
6930    /// arguments.
6931    NamedDecl *Template;
6932
6933    /// \brief The list of template arguments we are substituting, if they
6934    /// are not part of the entity.
6935    const TemplateArgument *TemplateArgs;
6936
6937    // FIXME: Wrap this union around more members, or perhaps store the
6938    // kind-specific members in the RAII object owning the context.
6939    union {
6940      /// \brief The number of template arguments in TemplateArgs.
6941      unsigned NumTemplateArgs;
6942
6943      /// \brief The special member being declared or defined.
6944      CXXSpecialMember SpecialMember;
6945    };
6946
6947    ArrayRef<TemplateArgument> template_arguments() const {
6948      assert(Kind != DeclaringSpecialMember);
6949      return {TemplateArgs, NumTemplateArgs};
6950    }
6951
6952    /// \brief The template deduction info object associated with the
6953    /// substitution or checking of explicit or deduced template arguments.
6954    sema::TemplateDeductionInfo *DeductionInfo;
6955
6956    /// \brief The source range that covers the construct that cause
6957    /// the instantiation, e.g., the template-id that causes a class
6958    /// template instantiation.
6959    SourceRange InstantiationRange;
6960
6961    CodeSynthesisContext()
6962      : Kind(TemplateInstantiation), Entity(nullptr), Template(nullptr),
6963        TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
6964
6965    /// \brief Determines whether this template is an actual instantiation
6966    /// that should be counted toward the maximum instantiation depth.
6967    bool isInstantiationRecord() const;
6968  };
6969
6970  /// \brief List of active code synthesis contexts.
6971  ///
6972  /// This vector is treated as a stack. As synthesis of one entity requires
6973  /// synthesis of another, additional contexts are pushed onto the stack.
6974  SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
6975
6976  /// Specializations whose definitions are currently being instantiated.
6977  llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
6978
6979  /// Non-dependent types used in templates that have already been instantiated
6980  /// by some template instantiation.
6981  llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
6982
6983  /// \brief Extra modules inspected when performing a lookup during a template
6984  /// instantiation. Computed lazily.
6985  SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
6986
6987  /// \brief Cache of additional modules that should be used for name lookup
6988  /// within the current template instantiation. Computed lazily; use
6989  /// getLookupModules() to get a complete set.
6990  llvm::DenseSet<Module*> LookupModulesCache;
6991
6992  /// \brief Get the set of additional modules that should be checked during
6993  /// name lookup. A module and its imports become visible when instanting a
6994  /// template defined within it.
6995  llvm::DenseSet<Module*> &getLookupModules();
6996
6997  /// \brief Map from the most recent declaration of a namespace to the most
6998  /// recent visible declaration of that namespace.
6999  llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
7000
7001  /// \brief Whether we are in a SFINAE context that is not associated with
7002  /// template instantiation.
7003  ///
7004  /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
7005  /// of a template instantiation or template argument deduction.
7006  bool InNonInstantiationSFINAEContext;
7007
7008  /// \brief The number of \p CodeSynthesisContexts that are not template
7009  /// instantiations and, therefore, should not be counted as part of the
7010  /// instantiation depth.
7011  ///
7012  /// When the instantiation depth reaches the user-configurable limit
7013  /// \p LangOptions::InstantiationDepth we will abort instantiation.
7014  // FIXME: Should we have a similar limit for other forms of synthesis?
7015  unsigned NonInstantiationEntries;
7016
7017  /// \brief The depth of the context stack at the point when the most recent
7018  /// error or warning was produced.
7019  ///
7020  /// This value is used to suppress printing of redundant context stacks
7021  /// when there are multiple errors or warnings in the same instantiation.
7022  // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
7023  unsigned LastEmittedCodeSynthesisContextDepth = 0;
7024
7025  /// \brief The current index into pack expansion arguments that will be
7026  /// used for substitution of parameter packs.
7027  ///
7028  /// The pack expansion index will be -1 to indicate that parameter packs
7029  /// should be instantiated as themselves. Otherwise, the index specifies
7030  /// which argument within the parameter pack will be used for substitution.
7031  int ArgumentPackSubstitutionIndex;
7032
7033  /// \brief RAII object used to change the argument pack substitution index
7034  /// within a \c Sema object.
7035  ///
7036  /// See \c ArgumentPackSubstitutionIndex for more information.
7037  class ArgumentPackSubstitutionIndexRAII {
7038    Sema &Self;
7039    int OldSubstitutionIndex;
7040
7041  public:
7042    ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
7043      : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
7044      Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
7045    }
7046
7047    ~ArgumentPackSubstitutionIndexRAII() {
7048      Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
7049    }
7050  };
7051
7052  friend class ArgumentPackSubstitutionRAII;
7053
7054  /// \brief For each declaration that involved template argument deduction, the
7055  /// set of diagnostics that were suppressed during that template argument
7056  /// deduction.
7057  ///
7058  /// FIXME: Serialize this structure to the AST file.
7059  typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
7060    SuppressedDiagnosticsMap;
7061  SuppressedDiagnosticsMap SuppressedDiagnostics;
7062
7063  /// \brief A stack object to be created when performing template
7064  /// instantiation.
7065  ///
7066  /// Construction of an object of type \c InstantiatingTemplate
7067  /// pushes the current instantiation onto the stack of active
7068  /// instantiations. If the size of this stack exceeds the maximum
7069  /// number of recursive template instantiations, construction
7070  /// produces an error and evaluates true.
7071  ///
7072  /// Destruction of this object will pop the named instantiation off
7073  /// the stack.
7074  struct InstantiatingTemplate {
7075    /// \brief Note that we are instantiating a class template,
7076    /// function template, variable template, alias template,
7077    /// or a member thereof.
7078    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7079                          Decl *Entity,
7080                          SourceRange InstantiationRange = SourceRange());
7081
7082    struct ExceptionSpecification {};
7083    /// \brief Note that we are instantiating an exception specification
7084    /// of a function template.
7085    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7086                          FunctionDecl *Entity, ExceptionSpecification,
7087                          SourceRange InstantiationRange = SourceRange());
7088
7089    /// \brief Note that we are instantiating a default argument in a
7090    /// template-id.
7091    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7092                          TemplateParameter Param, TemplateDecl *Template,
7093                          ArrayRef<TemplateArgument> TemplateArgs,
7094                          SourceRange InstantiationRange = SourceRange());
7095
7096    /// \brief Note that we are substituting either explicitly-specified or
7097    /// deduced template arguments during function template argument deduction.
7098    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7099                          FunctionTemplateDecl *FunctionTemplate,
7100                          ArrayRef<TemplateArgument> TemplateArgs,
7101                          CodeSynthesisContext::SynthesisKind Kind,
7102                          sema::TemplateDeductionInfo &DeductionInfo,
7103                          SourceRange InstantiationRange = SourceRange());
7104
7105    /// \brief Note that we are instantiating as part of template
7106    /// argument deduction for a class template declaration.
7107    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7108                          TemplateDecl *Template,
7109                          ArrayRef<TemplateArgument> TemplateArgs,
7110                          sema::TemplateDeductionInfo &DeductionInfo,
7111                          SourceRange InstantiationRange = SourceRange());
7112
7113    /// \brief Note that we are instantiating as part of template
7114    /// argument deduction for a class template partial
7115    /// specialization.
7116    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7117                          ClassTemplatePartialSpecializationDecl *PartialSpec,
7118                          ArrayRef<TemplateArgument> TemplateArgs,
7119                          sema::TemplateDeductionInfo &DeductionInfo,
7120                          SourceRange InstantiationRange = SourceRange());
7121
7122    /// \brief Note that we are instantiating as part of template
7123    /// argument deduction for a variable template partial
7124    /// specialization.
7125    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7126                          VarTemplatePartialSpecializationDecl *PartialSpec,
7127                          ArrayRef<TemplateArgument> TemplateArgs,
7128                          sema::TemplateDeductionInfo &DeductionInfo,
7129                          SourceRange InstantiationRange = SourceRange());
7130
7131    /// \brief Note that we are instantiating a default argument for a function
7132    /// parameter.
7133    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7134                          ParmVarDecl *Param,
7135                          ArrayRef<TemplateArgument> TemplateArgs,
7136                          SourceRange InstantiationRange = SourceRange());
7137
7138    /// \brief Note that we are substituting prior template arguments into a
7139    /// non-type parameter.
7140    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7141                          NamedDecl *Template,
7142                          NonTypeTemplateParmDecl *Param,
7143                          ArrayRef<TemplateArgument> TemplateArgs,
7144                          SourceRange InstantiationRange);
7145
7146    /// \brief Note that we are substituting prior template arguments into a
7147    /// template template parameter.
7148    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7149                          NamedDecl *Template,
7150                          TemplateTemplateParmDecl *Param,
7151                          ArrayRef<TemplateArgument> TemplateArgs,
7152                          SourceRange InstantiationRange);
7153
7154    /// \brief Note that we are checking the default template argument
7155    /// against the template parameter for a given template-id.
7156    InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7157                          TemplateDecl *Template,
7158                          NamedDecl *Param,
7159                          ArrayRef<TemplateArgument> TemplateArgs,
7160                          SourceRange InstantiationRange);
7161
7162
7163    /// \brief Note that we have finished instantiating this template.
7164    void Clear();
7165
7166    ~InstantiatingTemplate() { Clear(); }
7167
7168    /// \brief Determines whether we have exceeded the maximum
7169    /// recursive template instantiations.
7170    bool isInvalid() const { return Invalid; }
7171
7172    /// \brief Determine whether we are already instantiating this
7173    /// specialization in some surrounding active instantiation.
7174    bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
7175
7176  private:
7177    Sema &SemaRef;
7178    bool Invalid;
7179    bool AlreadyInstantiating;
7180    bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
7181                                 SourceRange InstantiationRange);
7182
7183    InstantiatingTemplate(
7184        Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
7185        SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
7186        Decl *Entity, NamedDecl *Template = nullptr,
7187        ArrayRef<TemplateArgument> TemplateArgs = None,
7188        sema::TemplateDeductionInfo *DeductionInfo = nullptr);
7189
7190    InstantiatingTemplate(const InstantiatingTemplate&) = delete;
7191
7192    InstantiatingTemplate&
7193    operator=(const InstantiatingTemplate&) = delete;
7194  };
7195
7196  void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
7197  void popCodeSynthesisContext();
7198
7199  /// Determine whether we are currently performing template instantiation.
7200  bool inTemplateInstantiation() const {
7201    return CodeSynthesisContexts.size() > NonInstantiationEntries;
7202  }
7203
7204  void PrintContextStack() {
7205    if (!CodeSynthesisContexts.empty() &&
7206        CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
7207      PrintInstantiationStack();
7208      LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
7209    }
7210  }
7211  void PrintInstantiationStack();
7212
7213  /// \brief Determines whether we are currently in a context where
7214  /// template argument substitution failures are not considered
7215  /// errors.
7216  ///
7217  /// \returns An empty \c Optional if we're not in a SFINAE context.
7218  /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
7219  /// template-deduction context object, which can be used to capture
7220  /// diagnostics that will be suppressed.
7221  Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
7222
7223  /// \brief Determines whether we are currently in a context that
7224  /// is not evaluated as per C++ [expr] p5.
7225  bool isUnevaluatedContext() const {
7226    assert(!ExprEvalContexts.empty() &&
7227           "Must be in an expression evaluation context");
7228    return ExprEvalContexts.back().isUnevaluated();
7229  }
7230
7231  /// \brief RAII class used to determine whether SFINAE has
7232  /// trapped any errors that occur during template argument
7233  /// deduction.
7234  class SFINAETrap {
7235    Sema &SemaRef;
7236    unsigned PrevSFINAEErrors;
7237    bool PrevInNonInstantiationSFINAEContext;
7238    bool PrevAccessCheckingSFINAE;
7239
7240  public:
7241    explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
7242      : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
7243        PrevInNonInstantiationSFINAEContext(
7244                                      SemaRef.InNonInstantiationSFINAEContext),
7245        PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
7246    {
7247      if (!SemaRef.isSFINAEContext())
7248        SemaRef.InNonInstantiationSFINAEContext = true;
7249      SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
7250    }
7251
7252    ~SFINAETrap() {
7253      SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
7254      SemaRef.InNonInstantiationSFINAEContext
7255        = PrevInNonInstantiationSFINAEContext;
7256      SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
7257    }
7258
7259    /// \brief Determine whether any SFINAE errors have been trapped.
7260    bool hasErrorOccurred() const {
7261      return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
7262    }
7263  };
7264
7265  /// \brief RAII class used to indicate that we are performing provisional
7266  /// semantic analysis to determine the validity of a construct, so
7267  /// typo-correction and diagnostics in the immediate context (not within
7268  /// implicitly-instantiated templates) should be suppressed.
7269  class TentativeAnalysisScope {
7270    Sema &SemaRef;
7271    // FIXME: Using a SFINAETrap for this is a hack.
7272    SFINAETrap Trap;
7273    bool PrevDisableTypoCorrection;
7274  public:
7275    explicit TentativeAnalysisScope(Sema &SemaRef)
7276        : SemaRef(SemaRef), Trap(SemaRef, true),
7277          PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
7278      SemaRef.DisableTypoCorrection = true;
7279    }
7280    ~TentativeAnalysisScope() {
7281      SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
7282    }
7283  };
7284
7285  /// \brief The current instantiation scope used to store local
7286  /// variables.
7287  LocalInstantiationScope *CurrentInstantiationScope;
7288
7289  /// \brief Tracks whether we are in a context where typo correction is
7290  /// disabled.
7291  bool DisableTypoCorrection;
7292
7293  /// \brief The number of typos corrected by CorrectTypo.
7294  unsigned TyposCorrected;
7295
7296  typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
7297  typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
7298
7299  /// \brief A cache containing identifiers for which typo correction failed and
7300  /// their locations, so that repeated attempts to correct an identifier in a
7301  /// given location are ignored if typo correction already failed for it.
7302  IdentifierSourceLocations TypoCorrectionFailures;
7303
7304  /// \brief Worker object for performing CFG-based warnings.
7305  sema::AnalysisBasedWarnings AnalysisWarnings;
7306  threadSafety::BeforeSet *ThreadSafetyDeclCache;
7307
7308  /// \brief An entity for which implicit template instantiation is required.
7309  ///
7310  /// The source location associated with the declaration is the first place in
7311  /// the source code where the declaration was "used". It is not necessarily
7312  /// the point of instantiation (which will be either before or after the
7313  /// namespace-scope declaration that triggered this implicit instantiation),
7314  /// However, it is the location that diagnostics should generally refer to,
7315  /// because users will need to know what code triggered the instantiation.
7316  typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
7317
7318  /// \brief The queue of implicit template instantiations that are required
7319  /// but have not yet been performed.
7320  std::deque<PendingImplicitInstantiation> PendingInstantiations;
7321
7322  class SavePendingInstantiationsAndVTableUsesRAII {
7323  public:
7324    SavePendingInstantiationsAndVTableUsesRAII(Sema &S, bool Enabled)
7325        : S(S), Enabled(Enabled) {
7326      if (!Enabled) return;
7327
7328      SavedPendingInstantiations.swap(S.PendingInstantiations);
7329      SavedVTableUses.swap(S.VTableUses);
7330    }
7331
7332    ~SavePendingInstantiationsAndVTableUsesRAII() {
7333      if (!Enabled) return;
7334
7335      // Restore the set of pending vtables.
7336      assert(S.VTableUses.empty() &&
7337             "VTableUses should be empty before it is discarded.");
7338      S.VTableUses.swap(SavedVTableUses);
7339
7340      // Restore the set of pending implicit instantiations.
7341      assert(S.PendingInstantiations.empty() &&
7342             "PendingInstantiations should be empty before it is discarded.");
7343      S.PendingInstantiations.swap(SavedPendingInstantiations);
7344    }
7345
7346  private:
7347    Sema &S;
7348    SmallVector<VTableUse, 16> SavedVTableUses;
7349    std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
7350    bool Enabled;
7351  };
7352
7353  /// \brief The queue of implicit template instantiations that are required
7354  /// and must be performed within the current local scope.
7355  ///
7356  /// This queue is only used for member functions of local classes in
7357  /// templates, which must be instantiated in the same scope as their
7358  /// enclosing function, so that they can reference function-local
7359  /// types, static variables, enumerators, etc.
7360  std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
7361
7362  class SavePendingLocalImplicitInstantiationsRAII {
7363  public:
7364    SavePendingLocalImplicitInstantiationsRAII(Sema &S): S(S) {
7365      SavedPendingLocalImplicitInstantiations.swap(
7366          S.PendingLocalImplicitInstantiations);
7367    }
7368
7369    ~SavePendingLocalImplicitInstantiationsRAII() {
7370      assert(S.PendingLocalImplicitInstantiations.empty() &&
7371             "there shouldn't be any pending local implicit instantiations");
7372      SavedPendingLocalImplicitInstantiations.swap(
7373          S.PendingLocalImplicitInstantiations);
7374    }
7375
7376  private:
7377    Sema &S;
7378    std::deque<PendingImplicitInstantiation>
7379    SavedPendingLocalImplicitInstantiations;
7380  };
7381
7382  /// A helper class for building up ExtParameterInfos.
7383  class ExtParameterInfoBuilder {
7384    SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
7385    bool HasInteresting = false;
7386
7387  public:
7388    /// Set the ExtParameterInfo for the parameter at the given index,
7389    ///
7390    void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
7391      assert(Infos.size() <= index);
7392      Infos.resize(index);
7393      Infos.push_back(info);
7394
7395      if (!HasInteresting)
7396        HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
7397    }
7398
7399    /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
7400    /// ExtParameterInfo array we've built up.
7401    const FunctionProtoType::ExtParameterInfo *
7402    getPointerOrNull(unsigned numParams) {
7403      if (!HasInteresting) return nullptr;
7404      Infos.resize(numParams);
7405      return Infos.data();
7406    }
7407  };
7408
7409  void PerformPendingInstantiations(bool LocalOnly = false);
7410
7411  TypeSourceInfo *SubstType(TypeSourceInfo *T,
7412                            const MultiLevelTemplateArgumentList &TemplateArgs,
7413                            SourceLocation Loc, DeclarationName Entity,
7414                            bool AllowDeducedTST = false);
7415
7416  QualType SubstType(QualType T,
7417                     const MultiLevelTemplateArgumentList &TemplateArgs,
7418                     SourceLocation Loc, DeclarationName Entity);
7419
7420  TypeSourceInfo *SubstType(TypeLoc TL,
7421                            const MultiLevelTemplateArgumentList &TemplateArgs,
7422                            SourceLocation Loc, DeclarationName Entity);
7423
7424  TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
7425                            const MultiLevelTemplateArgumentList &TemplateArgs,
7426                                        SourceLocation Loc,
7427                                        DeclarationName Entity,
7428                                        CXXRecordDecl *ThisContext,
7429                                        unsigned ThisTypeQuals);
7430  void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
7431                          const MultiLevelTemplateArgumentList &Args);
7432  ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
7433                            const MultiLevelTemplateArgumentList &TemplateArgs,
7434                                int indexAdjustment,
7435                                Optional<unsigned> NumExpansions,
7436                                bool ExpectParameterPack);
7437  bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
7438                      const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
7439                      const MultiLevelTemplateArgumentList &TemplateArgs,
7440                      SmallVectorImpl<QualType> &ParamTypes,
7441                      SmallVectorImpl<ParmVarDecl *> *OutParams,
7442                      ExtParameterInfoBuilder &ParamInfos);
7443  ExprResult SubstExpr(Expr *E,
7444                       const MultiLevelTemplateArgumentList &TemplateArgs);
7445
7446  /// \brief Substitute the given template arguments into a list of
7447  /// expressions, expanding pack expansions if required.
7448  ///
7449  /// \param Exprs The list of expressions to substitute into.
7450  ///
7451  /// \param IsCall Whether this is some form of call, in which case
7452  /// default arguments will be dropped.
7453  ///
7454  /// \param TemplateArgs The set of template arguments to substitute.
7455  ///
7456  /// \param Outputs Will receive all of the substituted arguments.
7457  ///
7458  /// \returns true if an error occurred, false otherwise.
7459  bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
7460                  const MultiLevelTemplateArgumentList &TemplateArgs,
7461                  SmallVectorImpl<Expr *> &Outputs);
7462
7463  StmtResult SubstStmt(Stmt *S,
7464                       const MultiLevelTemplateArgumentList &TemplateArgs);
7465
7466  Decl *SubstDecl(Decl *D, DeclContext *Owner,
7467                  const MultiLevelTemplateArgumentList &TemplateArgs);
7468
7469  ExprResult SubstInitializer(Expr *E,
7470                       const MultiLevelTemplateArgumentList &TemplateArgs,
7471                       bool CXXDirectInit);
7472
7473  bool
7474  SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
7475                      CXXRecordDecl *Pattern,
7476                      const MultiLevelTemplateArgumentList &TemplateArgs);
7477
7478  bool
7479  InstantiateClass(SourceLocation PointOfInstantiation,
7480                   CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
7481                   const MultiLevelTemplateArgumentList &TemplateArgs,
7482                   TemplateSpecializationKind TSK,
7483                   bool Complain = true);
7484
7485  bool InstantiateEnum(SourceLocation PointOfInstantiation,
7486                       EnumDecl *Instantiation, EnumDecl *Pattern,
7487                       const MultiLevelTemplateArgumentList &TemplateArgs,
7488                       TemplateSpecializationKind TSK);
7489
7490  bool InstantiateInClassInitializer(
7491      SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
7492      FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
7493
7494  struct LateInstantiatedAttribute {
7495    const Attr *TmplAttr;
7496    LocalInstantiationScope *Scope;
7497    Decl *NewDecl;
7498
7499    LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
7500                              Decl *D)
7501      : TmplAttr(A), Scope(S), NewDecl(D)
7502    { }
7503  };
7504  typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
7505
7506  void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
7507                        const Decl *Pattern, Decl *Inst,
7508                        LateInstantiatedAttrVec *LateAttrs = nullptr,
7509                        LocalInstantiationScope *OuterMostScope = nullptr);
7510
7511  void
7512  InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
7513                          const Decl *Pattern, Decl *Inst,
7514                          LateInstantiatedAttrVec *LateAttrs = nullptr,
7515                          LocalInstantiationScope *OuterMostScope = nullptr);
7516
7517  bool
7518  InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
7519                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
7520                           TemplateSpecializationKind TSK,
7521                           bool Complain = true);
7522
7523  void InstantiateClassMembers(SourceLocation PointOfInstantiation,
7524                               CXXRecordDecl *Instantiation,
7525                            const MultiLevelTemplateArgumentList &TemplateArgs,
7526                               TemplateSpecializationKind TSK);
7527
7528  void InstantiateClassTemplateSpecializationMembers(
7529                                          SourceLocation PointOfInstantiation,
7530                           ClassTemplateSpecializationDecl *ClassTemplateSpec,
7531                                                TemplateSpecializationKind TSK);
7532
7533  NestedNameSpecifierLoc
7534  SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
7535                           const MultiLevelTemplateArgumentList &TemplateArgs);
7536
7537  DeclarationNameInfo
7538  SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
7539                           const MultiLevelTemplateArgumentList &TemplateArgs);
7540  TemplateName
7541  SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
7542                    SourceLocation Loc,
7543                    const MultiLevelTemplateArgumentList &TemplateArgs);
7544  bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
7545             TemplateArgumentListInfo &Result,
7546             const MultiLevelTemplateArgumentList &TemplateArgs);
7547
7548  void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
7549                                FunctionDecl *Function);
7550  void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
7551                                     FunctionDecl *Function,
7552                                     bool Recursive = false,
7553                                     bool DefinitionRequired = false,
7554                                     bool AtEndOfTU = false);
7555  VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
7556      VarTemplateDecl *VarTemplate, VarDecl *FromVar,
7557      const TemplateArgumentList &TemplateArgList,
7558      const TemplateArgumentListInfo &TemplateArgsInfo,
7559      SmallVectorImpl<TemplateArgument> &Converted,
7560      SourceLocation PointOfInstantiation, void *InsertPos,
7561      LateInstantiatedAttrVec *LateAttrs = nullptr,
7562      LocalInstantiationScope *StartingScope = nullptr);
7563  VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
7564      VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
7565      const MultiLevelTemplateArgumentList &TemplateArgs);
7566  void
7567  BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
7568                             const MultiLevelTemplateArgumentList &TemplateArgs,
7569                             LateInstantiatedAttrVec *LateAttrs,
7570                             DeclContext *Owner,
7571                             LocalInstantiationScope *StartingScope,
7572                             bool InstantiatingVarTemplate = false);
7573  void InstantiateVariableInitializer(
7574      VarDecl *Var, VarDecl *OldVar,
7575      const MultiLevelTemplateArgumentList &TemplateArgs);
7576  void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
7577                                     VarDecl *Var, bool Recursive = false,
7578                                     bool DefinitionRequired = false,
7579                                     bool AtEndOfTU = false);
7580  void InstantiateStaticDataMemberDefinition(
7581                                     SourceLocation PointOfInstantiation,
7582                                     VarDecl *Var,
7583                                     bool Recursive = false,
7584                                     bool DefinitionRequired = false);
7585
7586  void InstantiateMemInitializers(CXXConstructorDecl *New,
7587                                  const CXXConstructorDecl *Tmpl,
7588                            const MultiLevelTemplateArgumentList &TemplateArgs);
7589
7590  NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
7591                          const MultiLevelTemplateArgumentList &TemplateArgs);
7592  DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
7593                          const MultiLevelTemplateArgumentList &TemplateArgs);
7594
7595  // Objective-C declarations.
7596  enum ObjCContainerKind {
7597    OCK_None = -1,
7598    OCK_Interface = 0,
7599    OCK_Protocol,
7600    OCK_Category,
7601    OCK_ClassExtension,
7602    OCK_Implementation,
7603    OCK_CategoryImplementation
7604  };
7605  ObjCContainerKind getObjCContainerKind() const;
7606
7607  DeclResult actOnObjCTypeParam(Scope *S,
7608                                ObjCTypeParamVariance variance,
7609                                SourceLocation varianceLoc,
7610                                unsigned index,
7611                                IdentifierInfo *paramName,
7612                                SourceLocation paramLoc,
7613                                SourceLocation colonLoc,
7614                                ParsedType typeBound);
7615
7616  ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
7617                                            ArrayRef<Decl *> typeParams,
7618                                            SourceLocation rAngleLoc);
7619  void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
7620
7621  Decl *ActOnStartClassInterface(Scope *S,
7622                                 SourceLocation AtInterfaceLoc,
7623                                 IdentifierInfo *ClassName,
7624                                 SourceLocation ClassLoc,
7625                                 ObjCTypeParamList *typeParamList,
7626                                 IdentifierInfo *SuperName,
7627                                 SourceLocation SuperLoc,
7628                                 ArrayRef<ParsedType> SuperTypeArgs,
7629                                 SourceRange SuperTypeArgsRange,
7630                                 Decl * const *ProtoRefs,
7631                                 unsigned NumProtoRefs,
7632                                 const SourceLocation *ProtoLocs,
7633                                 SourceLocation EndProtoLoc,
7634                                 AttributeList *AttrList);
7635
7636  void ActOnSuperClassOfClassInterface(Scope *S,
7637                                       SourceLocation AtInterfaceLoc,
7638                                       ObjCInterfaceDecl *IDecl,
7639                                       IdentifierInfo *ClassName,
7640                                       SourceLocation ClassLoc,
7641                                       IdentifierInfo *SuperName,
7642                                       SourceLocation SuperLoc,
7643                                       ArrayRef<ParsedType> SuperTypeArgs,
7644                                       SourceRange SuperTypeArgsRange);
7645
7646  void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
7647                               SmallVectorImpl<SourceLocation> &ProtocolLocs,
7648                               IdentifierInfo *SuperName,
7649                               SourceLocation SuperLoc);
7650
7651  Decl *ActOnCompatibilityAlias(
7652                    SourceLocation AtCompatibilityAliasLoc,
7653                    IdentifierInfo *AliasName,  SourceLocation AliasLocation,
7654                    IdentifierInfo *ClassName, SourceLocation ClassLocation);
7655
7656  bool CheckForwardProtocolDeclarationForCircularDependency(
7657    IdentifierInfo *PName,
7658    SourceLocation &PLoc, SourceLocation PrevLoc,
7659    const ObjCList<ObjCProtocolDecl> &PList);
7660
7661  Decl *ActOnStartProtocolInterface(
7662                    SourceLocation AtProtoInterfaceLoc,
7663                    IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
7664                    Decl * const *ProtoRefNames, unsigned NumProtoRefs,
7665                    const SourceLocation *ProtoLocs,
7666                    SourceLocation EndProtoLoc,
7667                    AttributeList *AttrList);
7668
7669  Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
7670                                    IdentifierInfo *ClassName,
7671                                    SourceLocation ClassLoc,
7672                                    ObjCTypeParamList *typeParamList,
7673                                    IdentifierInfo *CategoryName,
7674                                    SourceLocation CategoryLoc,
7675                                    Decl * const *ProtoRefs,
7676                                    unsigned NumProtoRefs,
7677                                    const SourceLocation *ProtoLocs,
7678                                    SourceLocation EndProtoLoc,
7679                                    AttributeList *AttrList);
7680
7681  Decl *ActOnStartClassImplementation(
7682                    SourceLocation AtClassImplLoc,
7683                    IdentifierInfo *ClassName, SourceLocation ClassLoc,
7684                    IdentifierInfo *SuperClassname,
7685                    SourceLocation SuperClassLoc);
7686
7687  Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
7688                                         IdentifierInfo *ClassName,
7689                                         SourceLocation ClassLoc,
7690                                         IdentifierInfo *CatName,
7691                                         SourceLocation CatLoc);
7692
7693  DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
7694                                               ArrayRef<Decl *> Decls);
7695
7696  DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
7697                   IdentifierInfo **IdentList,
7698                   SourceLocation *IdentLocs,
7699                   ArrayRef<ObjCTypeParamList *> TypeParamLists,
7700                   unsigned NumElts);
7701
7702  DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
7703                                        ArrayRef<IdentifierLocPair> IdentList,
7704                                        AttributeList *attrList);
7705
7706  void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
7707                               ArrayRef<IdentifierLocPair> ProtocolId,
7708                               SmallVectorImpl<Decl *> &Protocols);
7709
7710  void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
7711                                    SourceLocation ProtocolLoc,
7712                                    IdentifierInfo *TypeArgId,
7713                                    SourceLocation TypeArgLoc,
7714                                    bool SelectProtocolFirst = false);
7715
7716  /// Given a list of identifiers (and their locations), resolve the
7717  /// names to either Objective-C protocol qualifiers or type
7718  /// arguments, as appropriate.
7719  void actOnObjCTypeArgsOrProtocolQualifiers(
7720         Scope *S,
7721         ParsedType baseType,
7722         SourceLocation lAngleLoc,
7723         ArrayRef<IdentifierInfo *> identifiers,
7724         ArrayRef<SourceLocation> identifierLocs,
7725         SourceLocation rAngleLoc,
7726         SourceLocation &typeArgsLAngleLoc,
7727         SmallVectorImpl<ParsedType> &typeArgs,
7728         SourceLocation &typeArgsRAngleLoc,
7729         SourceLocation &protocolLAngleLoc,
7730         SmallVectorImpl<Decl *> &protocols,
7731         SourceLocation &protocolRAngleLoc,
7732         bool warnOnIncompleteProtocols);
7733
7734  /// Build a an Objective-C protocol-qualified 'id' type where no
7735  /// base type was specified.
7736  TypeResult actOnObjCProtocolQualifierType(
7737               SourceLocation lAngleLoc,
7738               ArrayRef<Decl *> protocols,
7739               ArrayRef<SourceLocation> protocolLocs,
7740               SourceLocation rAngleLoc);
7741
7742  /// Build a specialized and/or protocol-qualified Objective-C type.
7743  TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
7744               Scope *S,
7745               SourceLocation Loc,
7746               ParsedType BaseType,
7747               SourceLocation TypeArgsLAngleLoc,
7748               ArrayRef<ParsedType> TypeArgs,
7749               SourceLocation TypeArgsRAngleLoc,
7750               SourceLocation ProtocolLAngleLoc,
7751               ArrayRef<Decl *> Protocols,
7752               ArrayRef<SourceLocation> ProtocolLocs,
7753               SourceLocation ProtocolRAngleLoc);
7754
7755  /// Build an Objective-C type parameter type.
7756  QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
7757                                  SourceLocation ProtocolLAngleLoc,
7758                                  ArrayRef<ObjCProtocolDecl *> Protocols,
7759                                  ArrayRef<SourceLocation> ProtocolLocs,
7760                                  SourceLocation ProtocolRAngleLoc,
7761                                  bool FailOnError = false);
7762
7763  /// Build an Objective-C object pointer type.
7764  QualType BuildObjCObjectType(QualType BaseType,
7765                               SourceLocation Loc,
7766                               SourceLocation TypeArgsLAngleLoc,
7767                               ArrayRef<TypeSourceInfo *> TypeArgs,
7768                               SourceLocation TypeArgsRAngleLoc,
7769                               SourceLocation ProtocolLAngleLoc,
7770                               ArrayRef<ObjCProtocolDecl *> Protocols,
7771                               ArrayRef<SourceLocation> ProtocolLocs,
7772                               SourceLocation ProtocolRAngleLoc,
7773                               bool FailOnError = false);
7774
7775  /// Check the application of the Objective-C '__kindof' qualifier to
7776  /// the given type.
7777  bool checkObjCKindOfType(QualType &type, SourceLocation loc);
7778
7779  /// Ensure attributes are consistent with type.
7780  /// \param [in, out] Attributes The attributes to check; they will
7781  /// be modified to be consistent with \p PropertyTy.
7782  void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
7783                                   SourceLocation Loc,
7784                                   unsigned &Attributes,
7785                                   bool propertyInPrimaryClass);
7786
7787  /// Process the specified property declaration and create decls for the
7788  /// setters and getters as needed.
7789  /// \param property The property declaration being processed
7790  void ProcessPropertyDecl(ObjCPropertyDecl *property);
7791
7792
7793  void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
7794                                ObjCPropertyDecl *SuperProperty,
7795                                const IdentifierInfo *Name,
7796                                bool OverridingProtocolProperty);
7797
7798  void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
7799                                        ObjCInterfaceDecl *ID);
7800
7801  Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
7802                   ArrayRef<Decl *> allMethods = None,
7803                   ArrayRef<DeclGroupPtrTy> allTUVars = None);
7804
7805  Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
7806                      SourceLocation LParenLoc,
7807                      FieldDeclarator &FD, ObjCDeclSpec &ODS,
7808                      Selector GetterSel, Selector SetterSel,
7809                      tok::ObjCKeywordKind MethodImplKind,
7810                      DeclContext *lexicalDC = nullptr);
7811
7812  Decl *ActOnPropertyImplDecl(Scope *S,
7813                              SourceLocation AtLoc,
7814                              SourceLocation PropertyLoc,
7815                              bool ImplKind,
7816                              IdentifierInfo *PropertyId,
7817                              IdentifierInfo *PropertyIvar,
7818                              SourceLocation PropertyIvarLoc,
7819                              ObjCPropertyQueryKind QueryKind);
7820
7821  enum ObjCSpecialMethodKind {
7822    OSMK_None,
7823    OSMK_Alloc,
7824    OSMK_New,
7825    OSMK_Copy,
7826    OSMK_RetainingInit,
7827    OSMK_NonRetainingInit
7828  };
7829
7830  struct ObjCArgInfo {
7831    IdentifierInfo *Name;
7832    SourceLocation NameLoc;
7833    // The Type is null if no type was specified, and the DeclSpec is invalid
7834    // in this case.
7835    ParsedType Type;
7836    ObjCDeclSpec DeclSpec;
7837
7838    /// ArgAttrs - Attribute list for this argument.
7839    AttributeList *ArgAttrs;
7840  };
7841
7842  Decl *ActOnMethodDeclaration(
7843    Scope *S,
7844    SourceLocation BeginLoc, // location of the + or -.
7845    SourceLocation EndLoc,   // location of the ; or {.
7846    tok::TokenKind MethodType,
7847    ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
7848    ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
7849    // optional arguments. The number of types/arguments is obtained
7850    // from the Sel.getNumArgs().
7851    ObjCArgInfo *ArgInfo,
7852    DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
7853    AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
7854    bool isVariadic, bool MethodDefinition);
7855
7856  ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
7857                                              const ObjCObjectPointerType *OPT,
7858                                              bool IsInstance);
7859  ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
7860                                           bool IsInstance);
7861
7862  bool CheckARCMethodDecl(ObjCMethodDecl *method);
7863  bool inferObjCARCLifetime(ValueDecl *decl);
7864
7865  ExprResult
7866  HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
7867                            Expr *BaseExpr,
7868                            SourceLocation OpLoc,
7869                            DeclarationName MemberName,
7870                            SourceLocation MemberLoc,
7871                            SourceLocation SuperLoc, QualType SuperType,
7872                            bool Super);
7873
7874  ExprResult
7875  ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
7876                            IdentifierInfo &propertyName,
7877                            SourceLocation receiverNameLoc,
7878                            SourceLocation propertyNameLoc);
7879
7880  ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
7881
7882  /// \brief Describes the kind of message expression indicated by a message
7883  /// send that starts with an identifier.
7884  enum ObjCMessageKind {
7885    /// \brief The message is sent to 'super'.
7886    ObjCSuperMessage,
7887    /// \brief The message is an instance message.
7888    ObjCInstanceMessage,
7889    /// \brief The message is a class message, and the identifier is a type
7890    /// name.
7891    ObjCClassMessage
7892  };
7893
7894  ObjCMessageKind getObjCMessageKind(Scope *S,
7895                                     IdentifierInfo *Name,
7896                                     SourceLocation NameLoc,
7897                                     bool IsSuper,
7898                                     bool HasTrailingDot,
7899                                     ParsedType &ReceiverType);
7900
7901  ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
7902                               Selector Sel,
7903                               SourceLocation LBracLoc,
7904                               ArrayRef<SourceLocation> SelectorLocs,
7905                               SourceLocation RBracLoc,
7906                               MultiExprArg Args);
7907
7908  ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
7909                               QualType ReceiverType,
7910                               SourceLocation SuperLoc,
7911                               Selector Sel,
7912                               ObjCMethodDecl *Method,
7913                               SourceLocation LBracLoc,
7914                               ArrayRef<SourceLocation> SelectorLocs,
7915                               SourceLocation RBracLoc,
7916                               MultiExprArg Args,
7917                               bool isImplicit = false);
7918
7919  ExprResult BuildClassMessageImplicit(QualType ReceiverType,
7920                                       bool isSuperReceiver,
7921                                       SourceLocation Loc,
7922                                       Selector Sel,
7923                                       ObjCMethodDecl *Method,
7924                                       MultiExprArg Args);
7925
7926  ExprResult ActOnClassMessage(Scope *S,
7927                               ParsedType Receiver,
7928                               Selector Sel,
7929                               SourceLocation LBracLoc,
7930                               ArrayRef<SourceLocation> SelectorLocs,
7931                               SourceLocation RBracLoc,
7932                               MultiExprArg Args);
7933
7934  ExprResult BuildInstanceMessage(Expr *Receiver,
7935                                  QualType ReceiverType,
7936                                  SourceLocation SuperLoc,
7937                                  Selector Sel,
7938                                  ObjCMethodDecl *Method,
7939                                  SourceLocation LBracLoc,
7940                                  ArrayRef<SourceLocation> SelectorLocs,
7941                                  SourceLocation RBracLoc,
7942                                  MultiExprArg Args,
7943                                  bool isImplicit = false);
7944
7945  ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
7946                                          QualType ReceiverType,
7947                                          SourceLocation Loc,
7948                                          Selector Sel,
7949                                          ObjCMethodDecl *Method,
7950                                          MultiExprArg Args);
7951
7952  ExprResult ActOnInstanceMessage(Scope *S,
7953                                  Expr *Receiver,
7954                                  Selector Sel,
7955                                  SourceLocation LBracLoc,
7956                                  ArrayRef<SourceLocation> SelectorLocs,
7957                                  SourceLocation RBracLoc,
7958                                  MultiExprArg Args);
7959
7960  ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
7961                                  ObjCBridgeCastKind Kind,
7962                                  SourceLocation BridgeKeywordLoc,
7963                                  TypeSourceInfo *TSInfo,
7964                                  Expr *SubExpr);
7965
7966  ExprResult ActOnObjCBridgedCast(Scope *S,
7967                                  SourceLocation LParenLoc,
7968                                  ObjCBridgeCastKind Kind,
7969                                  SourceLocation BridgeKeywordLoc,
7970                                  ParsedType Type,
7971                                  SourceLocation RParenLoc,
7972                                  Expr *SubExpr);
7973
7974  void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
7975
7976  void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
7977
7978  bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
7979                                     CastKind &Kind);
7980
7981  bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
7982                                        QualType DestType, QualType SrcType,
7983                                        ObjCInterfaceDecl *&RelatedClass,
7984                                        ObjCMethodDecl *&ClassMethod,
7985                                        ObjCMethodDecl *&InstanceMethod,
7986                                        TypedefNameDecl *&TDNDecl,
7987                                        bool CfToNs, bool Diagnose = true);
7988
7989  bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
7990                                         QualType DestType, QualType SrcType,
7991                                         Expr *&SrcExpr, bool Diagnose = true);
7992
7993  bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
7994                                          bool Diagnose = true);
7995
7996  bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
7997
7998  /// \brief Check whether the given new method is a valid override of the
7999  /// given overridden method, and set any properties that should be inherited.
8000  void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
8001                               const ObjCMethodDecl *Overridden);
8002
8003  /// \brief Describes the compatibility of a result type with its method.
8004  enum ResultTypeCompatibilityKind {
8005    RTC_Compatible,
8006    RTC_Incompatible,
8007    RTC_Unknown
8008  };
8009
8010  void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
8011                                ObjCInterfaceDecl *CurrentClass,
8012                                ResultTypeCompatibilityKind RTC);
8013
8014  enum PragmaOptionsAlignKind {
8015    POAK_Native,  // #pragma options align=native
8016    POAK_Natural, // #pragma options align=natural
8017    POAK_Packed,  // #pragma options align=packed
8018    POAK_Power,   // #pragma options align=power
8019    POAK_Mac68k,  // #pragma options align=mac68k
8020    POAK_Reset    // #pragma options align=reset
8021  };
8022
8023  /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
8024  void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
8025                               SourceLocation PragmaLoc);
8026
8027  /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
8028  void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
8029                       StringRef SlotLabel, Expr *Alignment);
8030
8031  /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
8032  void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
8033
8034  /// ActOnPragmaMSComment - Called on well formed
8035  /// \#pragma comment(kind, "arg").
8036  void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
8037                            StringRef Arg);
8038
8039  /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
8040  /// pointers_to_members(representation method[, general purpose
8041  /// representation]).
8042  void ActOnPragmaMSPointersToMembers(
8043      LangOptions::PragmaMSPointersToMembersKind Kind,
8044      SourceLocation PragmaLoc);
8045
8046  /// \brief Called on well formed \#pragma vtordisp().
8047  void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
8048                             SourceLocation PragmaLoc,
8049                             MSVtorDispAttr::Mode Value);
8050
8051  enum PragmaSectionKind {
8052    PSK_DataSeg,
8053    PSK_BSSSeg,
8054    PSK_ConstSeg,
8055    PSK_CodeSeg,
8056  };
8057
8058  bool UnifySection(StringRef SectionName,
8059                    int SectionFlags,
8060                    DeclaratorDecl *TheDecl);
8061  bool UnifySection(StringRef SectionName,
8062                    int SectionFlags,
8063                    SourceLocation PragmaSectionLocation);
8064
8065  /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
8066  void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
8067                        PragmaMsStackAction Action,
8068                        llvm::StringRef StackSlotLabel,
8069                        StringLiteral *SegmentName,
8070                        llvm::StringRef PragmaName);
8071
8072  /// \brief Called on well formed \#pragma section().
8073  void ActOnPragmaMSSection(SourceLocation PragmaLocation,
8074                            int SectionFlags, StringLiteral *SegmentName);
8075
8076  /// \brief Called on well-formed \#pragma init_seg().
8077  void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
8078                            StringLiteral *SegmentName);
8079
8080  /// \brief Called on #pragma clang __debug dump II
8081  void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
8082
8083  /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
8084  void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
8085                                 StringRef Value);
8086
8087  /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
8088  void ActOnPragmaUnused(const Token &Identifier,
8089                         Scope *curScope,
8090                         SourceLocation PragmaLoc);
8091
8092  /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
8093  void ActOnPragmaVisibility(const IdentifierInfo* VisType,
8094                             SourceLocation PragmaLoc);
8095
8096  NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
8097                                 SourceLocation Loc);
8098  void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
8099
8100  /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
8101  void ActOnPragmaWeakID(IdentifierInfo* WeakName,
8102                         SourceLocation PragmaLoc,
8103                         SourceLocation WeakNameLoc);
8104
8105  /// ActOnPragmaRedefineExtname - Called on well formed
8106  /// \#pragma redefine_extname oldname newname.
8107  void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
8108                                  IdentifierInfo* AliasName,
8109                                  SourceLocation PragmaLoc,
8110                                  SourceLocation WeakNameLoc,
8111                                  SourceLocation AliasNameLoc);
8112
8113  /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
8114  void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
8115                            IdentifierInfo* AliasName,
8116                            SourceLocation PragmaLoc,
8117                            SourceLocation WeakNameLoc,
8118                            SourceLocation AliasNameLoc);
8119
8120  /// ActOnPragmaFPContract - Called on well formed
8121  /// \#pragma {STDC,OPENCL} FP_CONTRACT and
8122  /// \#pragma clang fp contract
8123  void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
8124
8125  /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
8126  /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
8127  void AddAlignmentAttributesForRecord(RecordDecl *RD);
8128
8129  /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
8130  void AddMsStructLayoutForRecord(RecordDecl *RD);
8131
8132  /// FreePackedContext - Deallocate and null out PackContext.
8133  void FreePackedContext();
8134
8135  /// PushNamespaceVisibilityAttr - Note that we've entered a
8136  /// namespace with a visibility attribute.
8137  void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
8138                                   SourceLocation Loc);
8139
8140  /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
8141  /// add an appropriate visibility attribute.
8142  void AddPushedVisibilityAttribute(Decl *RD);
8143
8144  /// PopPragmaVisibility - Pop the top element of the visibility stack; used
8145  /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
8146  void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
8147
8148  /// FreeVisContext - Deallocate and null out VisContext.
8149  void FreeVisContext();
8150
8151  /// AddCFAuditedAttribute - Check whether we're currently within
8152  /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
8153  /// the appropriate attribute.
8154  void AddCFAuditedAttribute(Decl *D);
8155
8156  /// \brief Called on well formed \#pragma clang optimize.
8157  void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
8158
8159  /// \brief Get the location for the currently active "\#pragma clang optimize
8160  /// off". If this location is invalid, then the state of the pragma is "on".
8161  SourceLocation getOptimizeOffPragmaLocation() const {
8162    return OptimizeOffPragmaLocation;
8163  }
8164
8165  /// \brief Only called on function definitions; if there is a pragma in scope
8166  /// with the effect of a range-based optnone, consider marking the function
8167  /// with attribute optnone.
8168  void AddRangeBasedOptnone(FunctionDecl *FD);
8169
8170  /// \brief Adds the 'optnone' attribute to the function declaration if there
8171  /// are no conflicts; Loc represents the location causing the 'optnone'
8172  /// attribute to be added (usually because of a pragma).
8173  void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
8174
8175  /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
8176  void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
8177                      unsigned SpellingListIndex, bool IsPackExpansion);
8178  void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
8179                      unsigned SpellingListIndex, bool IsPackExpansion);
8180
8181  /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
8182  /// declaration.
8183  void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
8184                            unsigned SpellingListIndex);
8185
8186  /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
8187  /// declaration.
8188  void AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
8189                         unsigned SpellingListIndex);
8190
8191  /// AddAlignValueAttr - Adds an align_value attribute to a particular
8192  /// declaration.
8193  void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
8194                         unsigned SpellingListIndex);
8195
8196  /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
8197  /// declaration.
8198  void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
8199                           Expr *MinBlocks, unsigned SpellingListIndex);
8200
8201  /// AddModeAttr - Adds a mode attribute to a particular declaration.
8202  void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
8203                   unsigned SpellingListIndex, bool InInstantiation = false);
8204
8205  void AddParameterABIAttr(SourceRange AttrRange, Decl *D,
8206                           ParameterABI ABI, unsigned SpellingListIndex);
8207
8208  void AddNSConsumedAttr(SourceRange AttrRange, Decl *D,
8209                         unsigned SpellingListIndex, bool isNSConsumed,
8210                         bool isTemplateInstantiation);
8211
8212  //===--------------------------------------------------------------------===//
8213  // C++ Coroutines TS
8214  //
8215  ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8216  ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8217  StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
8218
8219  ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8220                                      bool IsImplicit = false);
8221  ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8222                                        UnresolvedLookupExpr* Lookup);
8223  ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
8224  StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
8225                               bool IsImplicit = false);
8226  StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
8227  VarDecl *buildCoroutinePromise(SourceLocation Loc);
8228  void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
8229
8230  //===--------------------------------------------------------------------===//
8231  // OpenCL extensions.
8232  //
8233private:
8234  std::string CurrOpenCLExtension;
8235  /// Extensions required by an OpenCL type.
8236  llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
8237  /// Extensions required by an OpenCL declaration.
8238  llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
8239public:
8240  llvm::StringRef getCurrentOpenCLExtension() const {
8241    return CurrOpenCLExtension;
8242  }
8243  void setCurrentOpenCLExtension(llvm::StringRef Ext) {
8244    CurrOpenCLExtension = Ext;
8245  }
8246
8247  /// \brief Set OpenCL extensions for a type which can only be used when these
8248  /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
8249  /// \param Exts A space separated list of OpenCL extensions.
8250  void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
8251
8252  /// \brief Set OpenCL extensions for a declaration which can only be
8253  /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
8254  /// nothing.
8255  /// \param Exts A space separated list of OpenCL extensions.
8256  void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
8257
8258  /// \brief Set current OpenCL extensions for a type which can only be used
8259  /// when these OpenCL extensions are enabled. If current OpenCL extension is
8260  /// empty, do nothing.
8261  void setCurrentOpenCLExtensionForType(QualType T);
8262
8263  /// \brief Set current OpenCL extensions for a declaration which
8264  /// can only be used when these OpenCL extensions are enabled. If current
8265  /// OpenCL extension is empty, do nothing.
8266  void setCurrentOpenCLExtensionForDecl(Decl *FD);
8267
8268  bool isOpenCLDisabledDecl(Decl *FD);
8269
8270  /// \brief Check if type \p T corresponding to declaration specifier \p DS
8271  /// is disabled due to required OpenCL extensions being disabled. If so,
8272  /// emit diagnostics.
8273  /// \return true if type is disabled.
8274  bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
8275
8276  /// \brief Check if declaration \p D used by expression \p E
8277  /// is disabled due to required OpenCL extensions being disabled. If so,
8278  /// emit diagnostics.
8279  /// \return true if type is disabled.
8280  bool checkOpenCLDisabledDecl(const Decl &D, const Expr &E);
8281
8282  //===--------------------------------------------------------------------===//
8283  // OpenMP directives and clauses.
8284  //
8285private:
8286  void *VarDataSharingAttributesStack;
8287  /// Set to true inside '#pragma omp declare target' region.
8288  bool IsInOpenMPDeclareTargetContext = false;
8289  /// \brief Initialization of data-sharing attributes stack.
8290  void InitDataSharingAttributesStack();
8291  void DestroyDataSharingAttributesStack();
8292  ExprResult
8293  VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
8294                                        bool StrictlyPositive = true);
8295  /// Returns OpenMP nesting level for current directive.
8296  unsigned getOpenMPNestingLevel() const;
8297
8298  /// Checks if a type or a declaration is disabled due to the owning extension
8299  /// being disabled, and emits diagnostic messages if it is disabled.
8300  /// \param D type or declaration to be checked.
8301  /// \param DiagLoc source location for the diagnostic message.
8302  /// \param DiagInfo information to be emitted for the diagnostic message.
8303  /// \param SrcRange source range of the declaration.
8304  /// \param Map maps type or declaration to the extensions.
8305  /// \param Selector selects diagnostic message: 0 for type and 1 for
8306  ///        declaration.
8307  /// \return true if the type or declaration is disabled.
8308  template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
8309  bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
8310                                     MapT &Map, unsigned Selector = 0,
8311                                     SourceRange SrcRange = SourceRange());
8312
8313public:
8314  /// \brief Return true if the provided declaration \a VD should be captured by
8315  /// reference.
8316  /// \param Level Relative level of nested OpenMP construct for that the check
8317  /// is performed.
8318  bool IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level);
8319
8320  /// \brief Check if the specified variable is used in one of the private
8321  /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
8322  /// constructs.
8323  VarDecl *IsOpenMPCapturedDecl(ValueDecl *D);
8324  ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
8325                                   ExprObjectKind OK, SourceLocation Loc);
8326
8327  /// \brief Check if the specified variable is used in 'private' clause.
8328  /// \param Level Relative level of nested OpenMP construct for that the check
8329  /// is performed.
8330  bool isOpenMPPrivateDecl(ValueDecl *D, unsigned Level);
8331
8332  /// \brief Check if the specified variable is captured  by 'target' directive.
8333  /// \param Level Relative level of nested OpenMP construct for that the check
8334  /// is performed.
8335  bool isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level);
8336
8337  ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
8338                                                    Expr *Op);
8339  /// \brief Called on start of new data sharing attribute block.
8340  void StartOpenMPDSABlock(OpenMPDirectiveKind K,
8341                           const DeclarationNameInfo &DirName, Scope *CurScope,
8342                           SourceLocation Loc);
8343  /// \brief Start analysis of clauses.
8344  void StartOpenMPClause(OpenMPClauseKind K);
8345  /// \brief End analysis of clauses.
8346  void EndOpenMPClause();
8347  /// \brief Called on end of data sharing attribute block.
8348  void EndOpenMPDSABlock(Stmt *CurDirective);
8349
8350  /// \brief Check if the current region is an OpenMP loop region and if it is,
8351  /// mark loop control variable, used in \p Init for loop initialization, as
8352  /// private by default.
8353  /// \param Init First part of the for loop.
8354  void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
8355
8356  // OpenMP directives and clauses.
8357  /// \brief Called on correct id-expression from the '#pragma omp
8358  /// threadprivate'.
8359  ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
8360                                     CXXScopeSpec &ScopeSpec,
8361                                     const DeclarationNameInfo &Id);
8362  /// \brief Called on well-formed '#pragma omp threadprivate'.
8363  DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
8364                                     SourceLocation Loc,
8365                                     ArrayRef<Expr *> VarList);
8366  /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
8367  OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
8368                                     SourceLocation Loc,
8369                                     ArrayRef<Expr *> VarList);
8370  /// \brief Check if the specified type is allowed to be used in 'omp declare
8371  /// reduction' construct.
8372  QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
8373                                           TypeResult ParsedType);
8374  /// \brief Called on start of '#pragma omp declare reduction'.
8375  DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
8376      Scope *S, DeclContext *DC, DeclarationName Name,
8377      ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
8378      AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
8379  /// \brief Initialize declare reduction construct initializer.
8380  void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
8381  /// \brief Finish current declare reduction construct initializer.
8382  void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
8383  /// \brief Initialize declare reduction construct initializer.
8384  void ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
8385  /// \brief Finish current declare reduction construct initializer.
8386  void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer);
8387  /// \brief Called at the end of '#pragma omp declare reduction'.
8388  DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
8389      Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
8390
8391  /// Called on the start of target region i.e. '#pragma omp declare target'.
8392  bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
8393  /// Called at the end of target region i.e. '#pragme omp end declare target'.
8394  void ActOnFinishOpenMPDeclareTargetDirective();
8395  /// Called on correct id-expression from the '#pragma omp declare target'.
8396  void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
8397                                    const DeclarationNameInfo &Id,
8398                                    OMPDeclareTargetDeclAttr::MapTypeTy MT,
8399                                    NamedDeclSetType &SameDirectiveDecls);
8400  /// Check declaration inside target region.
8401  void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D);
8402  /// Return true inside OpenMP target region.
8403  bool isInOpenMPDeclareTargetContext() const {
8404    return IsInOpenMPDeclareTargetContext;
8405  }
8406
8407  /// Return the number of captured regions created for an OpenMP directive.
8408  static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
8409
8410  /// \brief Initialization of captured region for OpenMP region.
8411  void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
8412  /// \brief End of OpenMP region.
8413  ///
8414  /// \param S Statement associated with the current OpenMP region.
8415  /// \param Clauses List of clauses for the current OpenMP region.
8416  ///
8417  /// \returns Statement for finished OpenMP region.
8418  StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
8419  StmtResult ActOnOpenMPExecutableDirective(
8420      OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
8421      OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
8422      Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
8423  /// \brief Called on well-formed '\#pragma omp parallel' after parsing
8424  /// of the  associated statement.
8425  StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
8426                                          Stmt *AStmt,
8427                                          SourceLocation StartLoc,
8428                                          SourceLocation EndLoc);
8429  /// \brief Called on well-formed '\#pragma omp simd' after parsing
8430  /// of the associated statement.
8431  StmtResult ActOnOpenMPSimdDirective(
8432      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8433      SourceLocation EndLoc,
8434      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8435  /// \brief Called on well-formed '\#pragma omp for' after parsing
8436  /// of the associated statement.
8437  StmtResult ActOnOpenMPForDirective(
8438      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8439      SourceLocation EndLoc,
8440      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8441  /// \brief Called on well-formed '\#pragma omp for simd' after parsing
8442  /// of the associated statement.
8443  StmtResult ActOnOpenMPForSimdDirective(
8444      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8445      SourceLocation EndLoc,
8446      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8447  /// \brief Called on well-formed '\#pragma omp sections' after parsing
8448  /// of the associated statement.
8449  StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8450                                          Stmt *AStmt, SourceLocation StartLoc,
8451                                          SourceLocation EndLoc);
8452  /// \brief Called on well-formed '\#pragma omp section' after parsing of the
8453  /// associated statement.
8454  StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
8455                                         SourceLocation EndLoc);
8456  /// \brief Called on well-formed '\#pragma omp single' after parsing of the
8457  /// associated statement.
8458  StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8459                                        Stmt *AStmt, SourceLocation StartLoc,
8460                                        SourceLocation EndLoc);
8461  /// \brief Called on well-formed '\#pragma omp master' after parsing of the
8462  /// associated statement.
8463  StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
8464                                        SourceLocation EndLoc);
8465  /// \brief Called on well-formed '\#pragma omp critical' after parsing of the
8466  /// associated statement.
8467  StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
8468                                          ArrayRef<OMPClause *> Clauses,
8469                                          Stmt *AStmt, SourceLocation StartLoc,
8470                                          SourceLocation EndLoc);
8471  /// \brief Called on well-formed '\#pragma omp parallel for' after parsing
8472  /// of the  associated statement.
8473  StmtResult ActOnOpenMPParallelForDirective(
8474      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8475      SourceLocation EndLoc,
8476      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8477  /// \brief Called on well-formed '\#pragma omp parallel for simd' after
8478  /// parsing of the  associated statement.
8479  StmtResult ActOnOpenMPParallelForSimdDirective(
8480      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8481      SourceLocation EndLoc,
8482      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8483  /// \brief Called on well-formed '\#pragma omp parallel sections' after
8484  /// parsing of the  associated statement.
8485  StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8486                                                  Stmt *AStmt,
8487                                                  SourceLocation StartLoc,
8488                                                  SourceLocation EndLoc);
8489  /// \brief Called on well-formed '\#pragma omp task' after parsing of the
8490  /// associated statement.
8491  StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8492                                      Stmt *AStmt, SourceLocation StartLoc,
8493                                      SourceLocation EndLoc);
8494  /// \brief Called on well-formed '\#pragma omp taskyield'.
8495  StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8496                                           SourceLocation EndLoc);
8497  /// \brief Called on well-formed '\#pragma omp barrier'.
8498  StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8499                                         SourceLocation EndLoc);
8500  /// \brief Called on well-formed '\#pragma omp taskwait'.
8501  StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8502                                          SourceLocation EndLoc);
8503  /// \brief Called on well-formed '\#pragma omp taskgroup'.
8504  StmtResult ActOnOpenMPTaskgroupDirective(Stmt *AStmt, SourceLocation StartLoc,
8505                                           SourceLocation EndLoc);
8506  /// \brief Called on well-formed '\#pragma omp flush'.
8507  StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8508                                       SourceLocation StartLoc,
8509                                       SourceLocation EndLoc);
8510  /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
8511  /// associated statement.
8512  StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8513                                         Stmt *AStmt, SourceLocation StartLoc,
8514                                         SourceLocation EndLoc);
8515  /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
8516  /// associated statement.
8517  StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8518                                        Stmt *AStmt, SourceLocation StartLoc,
8519                                        SourceLocation EndLoc);
8520  /// \brief Called on well-formed '\#pragma omp target' after parsing of the
8521  /// associated statement.
8522  StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8523                                        Stmt *AStmt, SourceLocation StartLoc,
8524                                        SourceLocation EndLoc);
8525  /// \brief Called on well-formed '\#pragma omp target data' after parsing of
8526  /// the associated statement.
8527  StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
8528                                            Stmt *AStmt, SourceLocation StartLoc,
8529                                            SourceLocation EndLoc);
8530  /// \brief Called on well-formed '\#pragma omp target enter data' after
8531  /// parsing of the associated statement.
8532  StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
8533                                                 SourceLocation StartLoc,
8534                                                 SourceLocation EndLoc);
8535  /// \brief Called on well-formed '\#pragma omp target exit data' after
8536  /// parsing of the associated statement.
8537  StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8538                                                SourceLocation StartLoc,
8539                                                SourceLocation EndLoc);
8540  /// \brief Called on well-formed '\#pragma omp target parallel' after
8541  /// parsing of the associated statement.
8542  StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8543                                                Stmt *AStmt,
8544                                                SourceLocation StartLoc,
8545                                                SourceLocation EndLoc);
8546  /// \brief Called on well-formed '\#pragma omp target parallel for' after
8547  /// parsing of the  associated statement.
8548  StmtResult ActOnOpenMPTargetParallelForDirective(
8549      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8550      SourceLocation EndLoc,
8551      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8552  /// \brief Called on well-formed '\#pragma omp teams' after parsing of the
8553  /// associated statement.
8554  StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
8555                                       Stmt *AStmt, SourceLocation StartLoc,
8556                                       SourceLocation EndLoc);
8557  /// \brief Called on well-formed '\#pragma omp cancellation point'.
8558  StmtResult
8559  ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
8560                                        SourceLocation EndLoc,
8561                                        OpenMPDirectiveKind CancelRegion);
8562  /// \brief Called on well-formed '\#pragma omp cancel'.
8563  StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
8564                                        SourceLocation StartLoc,
8565                                        SourceLocation EndLoc,
8566                                        OpenMPDirectiveKind CancelRegion);
8567  /// \brief Called on well-formed '\#pragma omp taskloop' after parsing of the
8568  /// associated statement.
8569  StmtResult ActOnOpenMPTaskLoopDirective(
8570      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8571      SourceLocation EndLoc,
8572      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8573  /// \brief Called on well-formed '\#pragma omp taskloop simd' after parsing of
8574  /// the associated statement.
8575  StmtResult ActOnOpenMPTaskLoopSimdDirective(
8576      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8577      SourceLocation EndLoc,
8578      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8579  /// \brief Called on well-formed '\#pragma omp distribute' after parsing
8580  /// of the associated statement.
8581  StmtResult ActOnOpenMPDistributeDirective(
8582      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8583      SourceLocation EndLoc,
8584      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8585  /// \brief Called on well-formed '\#pragma omp target update'.
8586  StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
8587                                              SourceLocation StartLoc,
8588                                              SourceLocation EndLoc);
8589  /// \brief Called on well-formed '\#pragma omp distribute parallel for' after
8590  /// parsing of the associated statement.
8591  StmtResult ActOnOpenMPDistributeParallelForDirective(
8592      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8593      SourceLocation EndLoc,
8594      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8595  /// \brief Called on well-formed '\#pragma omp distribute parallel for simd'
8596  /// after parsing of the associated statement.
8597  StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
8598      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8599      SourceLocation EndLoc,
8600      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8601  /// \brief Called on well-formed '\#pragma omp distribute simd' after
8602  /// parsing of the associated statement.
8603  StmtResult ActOnOpenMPDistributeSimdDirective(
8604      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8605      SourceLocation EndLoc,
8606      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8607  /// \brief Called on well-formed '\#pragma omp target parallel for simd' after
8608  /// parsing of the associated statement.
8609  StmtResult ActOnOpenMPTargetParallelForSimdDirective(
8610      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8611      SourceLocation EndLoc,
8612      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8613  /// \brief Called on well-formed '\#pragma omp target simd' after parsing of
8614  /// the associated statement.
8615  StmtResult ActOnOpenMPTargetSimdDirective(
8616      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8617      SourceLocation EndLoc,
8618      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8619  /// Called on well-formed '\#pragma omp teams distribute' after parsing of
8620  /// the associated statement.
8621  StmtResult ActOnOpenMPTeamsDistributeDirective(
8622      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8623      SourceLocation EndLoc,
8624      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8625  /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
8626  /// of the associated statement.
8627  StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
8628      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8629      SourceLocation EndLoc,
8630      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8631  /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
8632  /// after parsing of the associated statement.
8633  StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8634      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8635      SourceLocation EndLoc,
8636      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8637  /// Called on well-formed '\#pragma omp teams distribute parallel for'
8638  /// after parsing of the associated statement.
8639  StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
8640      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8641      SourceLocation EndLoc,
8642      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8643  /// Called on well-formed '\#pragma omp target teams' after parsing of the
8644  /// associated statement.
8645  StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8646                                             Stmt *AStmt,
8647                                             SourceLocation StartLoc,
8648                                             SourceLocation EndLoc);
8649  /// Called on well-formed '\#pragma omp target teams distribute' after parsing
8650  /// of the associated statement.
8651  StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
8652      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8653      SourceLocation EndLoc,
8654      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8655  /// Called on well-formed '\#pragma omp target teams distribute parallel for'
8656  /// after parsing of the associated statement.
8657  StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8658      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8659      SourceLocation EndLoc,
8660      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8661  /// Called on well-formed '\#pragma omp target teams distribute parallel for
8662  /// simd' after parsing of the associated statement.
8663  StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8664      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8665      SourceLocation EndLoc,
8666      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8667  /// Called on well-formed '\#pragma omp target teams distribute simd' after
8668  /// parsing of the associated statement.
8669  StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
8670      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8671      SourceLocation EndLoc,
8672      llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8673
8674  /// Checks correctness of linear modifiers.
8675  bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8676                                 SourceLocation LinLoc);
8677  /// Checks that the specified declaration matches requirements for the linear
8678  /// decls.
8679  bool CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8680                             OpenMPLinearClauseKind LinKind, QualType Type);
8681
8682  /// \brief Called on well-formed '\#pragma omp declare simd' after parsing of
8683  /// the associated method/function.
8684  DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
8685      DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
8686      Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
8687      ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
8688      ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
8689
8690  OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
8691                                         Expr *Expr,
8692                                         SourceLocation StartLoc,
8693                                         SourceLocation LParenLoc,
8694                                         SourceLocation EndLoc);
8695  /// \brief Called on well-formed 'if' clause.
8696  OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8697                                 Expr *Condition, SourceLocation StartLoc,
8698                                 SourceLocation LParenLoc,
8699                                 SourceLocation NameModifierLoc,
8700                                 SourceLocation ColonLoc,
8701                                 SourceLocation EndLoc);
8702  /// \brief Called on well-formed 'final' clause.
8703  OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
8704                                    SourceLocation LParenLoc,
8705                                    SourceLocation EndLoc);
8706  /// \brief Called on well-formed 'num_threads' clause.
8707  OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8708                                         SourceLocation StartLoc,
8709                                         SourceLocation LParenLoc,
8710                                         SourceLocation EndLoc);
8711  /// \brief Called on well-formed 'safelen' clause.
8712  OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
8713                                      SourceLocation StartLoc,
8714                                      SourceLocation LParenLoc,
8715                                      SourceLocation EndLoc);
8716  /// \brief Called on well-formed 'simdlen' clause.
8717  OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
8718                                      SourceLocation LParenLoc,
8719                                      SourceLocation EndLoc);
8720  /// \brief Called on well-formed 'collapse' clause.
8721  OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
8722                                       SourceLocation StartLoc,
8723                                       SourceLocation LParenLoc,
8724                                       SourceLocation EndLoc);
8725  /// \brief Called on well-formed 'ordered' clause.
8726  OMPClause *
8727  ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
8728                           SourceLocation LParenLoc = SourceLocation(),
8729                           Expr *NumForLoops = nullptr);
8730  /// \brief Called on well-formed 'grainsize' clause.
8731  OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
8732                                        SourceLocation LParenLoc,
8733                                        SourceLocation EndLoc);
8734  /// \brief Called on well-formed 'num_tasks' clause.
8735  OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
8736                                       SourceLocation LParenLoc,
8737                                       SourceLocation EndLoc);
8738  /// \brief Called on well-formed 'hint' clause.
8739  OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
8740                                   SourceLocation LParenLoc,
8741                                   SourceLocation EndLoc);
8742
8743  OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
8744                                     unsigned Argument,
8745                                     SourceLocation ArgumentLoc,
8746                                     SourceLocation StartLoc,
8747                                     SourceLocation LParenLoc,
8748                                     SourceLocation EndLoc);
8749  /// \brief Called on well-formed 'default' clause.
8750  OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8751                                      SourceLocation KindLoc,
8752                                      SourceLocation StartLoc,
8753                                      SourceLocation LParenLoc,
8754                                      SourceLocation EndLoc);
8755  /// \brief Called on well-formed 'proc_bind' clause.
8756  OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8757                                       SourceLocation KindLoc,
8758                                       SourceLocation StartLoc,
8759                                       SourceLocation LParenLoc,
8760                                       SourceLocation EndLoc);
8761
8762  OMPClause *ActOnOpenMPSingleExprWithArgClause(
8763      OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
8764      SourceLocation StartLoc, SourceLocation LParenLoc,
8765      ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
8766      SourceLocation EndLoc);
8767  /// \brief Called on well-formed 'schedule' clause.
8768  OMPClause *ActOnOpenMPScheduleClause(
8769      OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
8770      OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
8771      SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8772      SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
8773
8774  OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
8775                               SourceLocation EndLoc);
8776  /// \brief Called on well-formed 'nowait' clause.
8777  OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8778                                     SourceLocation EndLoc);
8779  /// \brief Called on well-formed 'untied' clause.
8780  OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8781                                     SourceLocation EndLoc);
8782  /// \brief Called on well-formed 'mergeable' clause.
8783  OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8784                                        SourceLocation EndLoc);
8785  /// \brief Called on well-formed 'read' clause.
8786  OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
8787                                   SourceLocation EndLoc);
8788  /// \brief Called on well-formed 'write' clause.
8789  OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
8790                                    SourceLocation EndLoc);
8791  /// \brief Called on well-formed 'update' clause.
8792  OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8793                                     SourceLocation EndLoc);
8794  /// \brief Called on well-formed 'capture' clause.
8795  OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8796                                      SourceLocation EndLoc);
8797  /// \brief Called on well-formed 'seq_cst' clause.
8798  OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8799                                     SourceLocation EndLoc);
8800  /// \brief Called on well-formed 'threads' clause.
8801  OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8802                                      SourceLocation EndLoc);
8803  /// \brief Called on well-formed 'simd' clause.
8804  OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8805                                   SourceLocation EndLoc);
8806  /// \brief Called on well-formed 'nogroup' clause.
8807  OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8808                                      SourceLocation EndLoc);
8809
8810  OMPClause *ActOnOpenMPVarListClause(
8811      OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
8812      SourceLocation StartLoc, SourceLocation LParenLoc,
8813      SourceLocation ColonLoc, SourceLocation EndLoc,
8814      CXXScopeSpec &ReductionIdScopeSpec,
8815      const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
8816      OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8817      OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8818      SourceLocation DepLinMapLoc);
8819  /// \brief Called on well-formed 'private' clause.
8820  OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
8821                                      SourceLocation StartLoc,
8822                                      SourceLocation LParenLoc,
8823                                      SourceLocation EndLoc);
8824  /// \brief Called on well-formed 'firstprivate' clause.
8825  OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
8826                                           SourceLocation StartLoc,
8827                                           SourceLocation LParenLoc,
8828                                           SourceLocation EndLoc);
8829  /// \brief Called on well-formed 'lastprivate' clause.
8830  OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
8831                                          SourceLocation StartLoc,
8832                                          SourceLocation LParenLoc,
8833                                          SourceLocation EndLoc);
8834  /// \brief Called on well-formed 'shared' clause.
8835  OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
8836                                     SourceLocation StartLoc,
8837                                     SourceLocation LParenLoc,
8838                                     SourceLocation EndLoc);
8839  /// \brief Called on well-formed 'reduction' clause.
8840  OMPClause *ActOnOpenMPReductionClause(
8841      ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8842      SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
8843      CXXScopeSpec &ReductionIdScopeSpec,
8844      const DeclarationNameInfo &ReductionId,
8845      ArrayRef<Expr *> UnresolvedReductions = llvm::None);
8846  /// \brief Called on well-formed 'linear' clause.
8847  OMPClause *
8848  ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
8849                          SourceLocation StartLoc, SourceLocation LParenLoc,
8850                          OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
8851                          SourceLocation ColonLoc, SourceLocation EndLoc);
8852  /// \brief Called on well-formed 'aligned' clause.
8853  OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
8854                                      Expr *Alignment,
8855                                      SourceLocation StartLoc,
8856                                      SourceLocation LParenLoc,
8857                                      SourceLocation ColonLoc,
8858                                      SourceLocation EndLoc);
8859  /// \brief Called on well-formed 'copyin' clause.
8860  OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
8861                                     SourceLocation StartLoc,
8862                                     SourceLocation LParenLoc,
8863                                     SourceLocation EndLoc);
8864  /// \brief Called on well-formed 'copyprivate' clause.
8865  OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
8866                                          SourceLocation StartLoc,
8867                                          SourceLocation LParenLoc,
8868                                          SourceLocation EndLoc);
8869  /// \brief Called on well-formed 'flush' pseudo clause.
8870  OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
8871                                    SourceLocation StartLoc,
8872                                    SourceLocation LParenLoc,
8873                                    SourceLocation EndLoc);
8874  /// \brief Called on well-formed 'depend' clause.
8875  OMPClause *
8876  ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
8877                          SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
8878                          SourceLocation StartLoc, SourceLocation LParenLoc,
8879                          SourceLocation EndLoc);
8880  /// \brief Called on well-formed 'device' clause.
8881  OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
8882                                     SourceLocation LParenLoc,
8883                                     SourceLocation EndLoc);
8884  /// \brief Called on well-formed 'map' clause.
8885  OMPClause *
8886  ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
8887                       OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8888                       SourceLocation MapLoc, SourceLocation ColonLoc,
8889                       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
8890                       SourceLocation LParenLoc, SourceLocation EndLoc);
8891  /// \brief Called on well-formed 'num_teams' clause.
8892  OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
8893                                       SourceLocation LParenLoc,
8894                                       SourceLocation EndLoc);
8895  /// \brief Called on well-formed 'thread_limit' clause.
8896  OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
8897                                          SourceLocation StartLoc,
8898                                          SourceLocation LParenLoc,
8899                                          SourceLocation EndLoc);
8900  /// \brief Called on well-formed 'priority' clause.
8901  OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
8902                                       SourceLocation LParenLoc,
8903                                       SourceLocation EndLoc);
8904  /// \brief Called on well-formed 'dist_schedule' clause.
8905  OMPClause *ActOnOpenMPDistScheduleClause(
8906      OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
8907      SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
8908      SourceLocation CommaLoc, SourceLocation EndLoc);
8909  /// \brief Called on well-formed 'defaultmap' clause.
8910  OMPClause *ActOnOpenMPDefaultmapClause(
8911      OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
8912      SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
8913      SourceLocation KindLoc, SourceLocation EndLoc);
8914  /// \brief Called on well-formed 'to' clause.
8915  OMPClause *ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
8916                                 SourceLocation StartLoc,
8917                                 SourceLocation LParenLoc,
8918                                 SourceLocation EndLoc);
8919  /// \brief Called on well-formed 'from' clause.
8920  OMPClause *ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
8921                                   SourceLocation StartLoc,
8922                                   SourceLocation LParenLoc,
8923                                   SourceLocation EndLoc);
8924  /// Called on well-formed 'use_device_ptr' clause.
8925  OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
8926                                           SourceLocation StartLoc,
8927                                           SourceLocation LParenLoc,
8928                                           SourceLocation EndLoc);
8929  /// Called on well-formed 'is_device_ptr' clause.
8930  OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
8931                                          SourceLocation StartLoc,
8932                                          SourceLocation LParenLoc,
8933                                          SourceLocation EndLoc);
8934
8935  /// \brief The kind of conversion being performed.
8936  enum CheckedConversionKind {
8937    /// \brief An implicit conversion.
8938    CCK_ImplicitConversion,
8939    /// \brief A C-style cast.
8940    CCK_CStyleCast,
8941    /// \brief A functional-style cast.
8942    CCK_FunctionalCast,
8943    /// \brief A cast other than a C-style cast.
8944    CCK_OtherCast
8945  };
8946
8947  /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
8948  /// cast.  If there is already an implicit cast, merge into the existing one.
8949  /// If isLvalue, the result of the cast is an lvalue.
8950  ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
8951                               ExprValueKind VK = VK_RValue,
8952                               const CXXCastPath *BasePath = nullptr,
8953                               CheckedConversionKind CCK
8954                                  = CCK_ImplicitConversion);
8955
8956  /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
8957  /// to the conversion from scalar type ScalarTy to the Boolean type.
8958  static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
8959
8960  /// IgnoredValueConversions - Given that an expression's result is
8961  /// syntactically ignored, perform any conversions that are
8962  /// required.
8963  ExprResult IgnoredValueConversions(Expr *E);
8964
8965  // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
8966  // functions and arrays to their respective pointers (C99 6.3.2.1).
8967  ExprResult UsualUnaryConversions(Expr *E);
8968
8969  /// CallExprUnaryConversions - a special case of an unary conversion
8970  /// performed on a function designator of a call expression.
8971  ExprResult CallExprUnaryConversions(Expr *E);
8972
8973  // DefaultFunctionArrayConversion - converts functions and arrays
8974  // to their respective pointers (C99 6.3.2.1).
8975  ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
8976
8977  // DefaultFunctionArrayLvalueConversion - converts functions and
8978  // arrays to their respective pointers and performs the
8979  // lvalue-to-rvalue conversion.
8980  ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
8981                                                  bool Diagnose = true);
8982
8983  // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
8984  // the operand.  This is DefaultFunctionArrayLvalueConversion,
8985  // except that it assumes the operand isn't of function or array
8986  // type.
8987  ExprResult DefaultLvalueConversion(Expr *E);
8988
8989  // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
8990  // do not have a prototype. Integer promotions are performed on each
8991  // argument, and arguments that have type float are promoted to double.
8992  ExprResult DefaultArgumentPromotion(Expr *E);
8993
8994  /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
8995  /// it as an xvalue. In C++98, the result will still be a prvalue, because
8996  /// we don't have xvalues there.
8997  ExprResult TemporaryMaterializationConversion(Expr *E);
8998
8999  // Used for emitting the right warning by DefaultVariadicArgumentPromotion
9000  enum VariadicCallType {
9001    VariadicFunction,
9002    VariadicBlock,
9003    VariadicMethod,
9004    VariadicConstructor,
9005    VariadicDoesNotApply
9006  };
9007
9008  VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
9009                                       const FunctionProtoType *Proto,
9010                                       Expr *Fn);
9011
9012  // Used for determining in which context a type is allowed to be passed to a
9013  // vararg function.
9014  enum VarArgKind {
9015    VAK_Valid,
9016    VAK_ValidInCXX11,
9017    VAK_Undefined,
9018    VAK_MSVCUndefined,
9019    VAK_Invalid
9020  };
9021
9022  // Determines which VarArgKind fits an expression.
9023  VarArgKind isValidVarArgType(const QualType &Ty);
9024
9025  /// Check to see if the given expression is a valid argument to a variadic
9026  /// function, issuing a diagnostic if not.
9027  void checkVariadicArgument(const Expr *E, VariadicCallType CT);
9028
9029  /// Check to see if a given expression could have '.c_str()' called on it.
9030  bool hasCStrMethod(const Expr *E);
9031
9032  /// GatherArgumentsForCall - Collector argument expressions for various
9033  /// form of call prototypes.
9034  bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
9035                              const FunctionProtoType *Proto,
9036                              unsigned FirstParam, ArrayRef<Expr *> Args,
9037                              SmallVectorImpl<Expr *> &AllArgs,
9038                              VariadicCallType CallType = VariadicDoesNotApply,
9039                              bool AllowExplicit = false,
9040                              bool IsListInitialization = false);
9041
9042  // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
9043  // will create a runtime trap if the resulting type is not a POD type.
9044  ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
9045                                              FunctionDecl *FDecl);
9046
9047  // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
9048  // operands and then handles various conversions that are common to binary
9049  // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
9050  // routine returns the first non-arithmetic type found. The client is
9051  // responsible for emitting appropriate error diagnostics.
9052  QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
9053                                      bool IsCompAssign = false);
9054
9055  /// AssignConvertType - All of the 'assignment' semantic checks return this
9056  /// enum to indicate whether the assignment was allowed.  These checks are
9057  /// done for simple assignments, as well as initialization, return from
9058  /// function, argument passing, etc.  The query is phrased in terms of a
9059  /// source and destination type.
9060  enum AssignConvertType {
9061    /// Compatible - the types are compatible according to the standard.
9062    Compatible,
9063
9064    /// PointerToInt - The assignment converts a pointer to an int, which we
9065    /// accept as an extension.
9066    PointerToInt,
9067
9068    /// IntToPointer - The assignment converts an int to a pointer, which we
9069    /// accept as an extension.
9070    IntToPointer,
9071
9072    /// FunctionVoidPointer - The assignment is between a function pointer and
9073    /// void*, which the standard doesn't allow, but we accept as an extension.
9074    FunctionVoidPointer,
9075
9076    /// IncompatiblePointer - The assignment is between two pointers types that
9077    /// are not compatible, but we accept them as an extension.
9078    IncompatiblePointer,
9079
9080    /// IncompatiblePointerSign - The assignment is between two pointers types
9081    /// which point to integers which have a different sign, but are otherwise
9082    /// identical. This is a subset of the above, but broken out because it's by
9083    /// far the most common case of incompatible pointers.
9084    IncompatiblePointerSign,
9085
9086    /// CompatiblePointerDiscardsQualifiers - The assignment discards
9087    /// c/v/r qualifiers, which we accept as an extension.
9088    CompatiblePointerDiscardsQualifiers,
9089
9090    /// IncompatiblePointerDiscardsQualifiers - The assignment
9091    /// discards qualifiers that we don't permit to be discarded,
9092    /// like address spaces.
9093    IncompatiblePointerDiscardsQualifiers,
9094
9095    /// IncompatibleNestedPointerQualifiers - The assignment is between two
9096    /// nested pointer types, and the qualifiers other than the first two
9097    /// levels differ e.g. char ** -> const char **, but we accept them as an
9098    /// extension.
9099    IncompatibleNestedPointerQualifiers,
9100
9101    /// IncompatibleVectors - The assignment is between two vector types that
9102    /// have the same size, which we accept as an extension.
9103    IncompatibleVectors,
9104
9105    /// IntToBlockPointer - The assignment converts an int to a block
9106    /// pointer. We disallow this.
9107    IntToBlockPointer,
9108
9109    /// IncompatibleBlockPointer - The assignment is between two block
9110    /// pointers types that are not compatible.
9111    IncompatibleBlockPointer,
9112
9113    /// IncompatibleObjCQualifiedId - The assignment is between a qualified
9114    /// id type and something else (that is incompatible with it). For example,
9115    /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
9116    IncompatibleObjCQualifiedId,
9117
9118    /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
9119    /// object with __weak qualifier.
9120    IncompatibleObjCWeakRef,
9121
9122    /// Incompatible - We reject this conversion outright, it is invalid to
9123    /// represent it in the AST.
9124    Incompatible
9125  };
9126
9127  /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
9128  /// assignment conversion type specified by ConvTy.  This returns true if the
9129  /// conversion was invalid or false if the conversion was accepted.
9130  bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
9131                                SourceLocation Loc,
9132                                QualType DstType, QualType SrcType,
9133                                Expr *SrcExpr, AssignmentAction Action,
9134                                bool *Complained = nullptr);
9135
9136  /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
9137  /// enum. If AllowMask is true, then we also allow the complement of a valid
9138  /// value, to be used as a mask.
9139  bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
9140                         bool AllowMask) const;
9141
9142  /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
9143  /// integer not in the range of enum values.
9144  void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
9145                              Expr *SrcExpr);
9146
9147  /// CheckAssignmentConstraints - Perform type checking for assignment,
9148  /// argument passing, variable initialization, and function return values.
9149  /// C99 6.5.16.
9150  AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
9151                                               QualType LHSType,
9152                                               QualType RHSType);
9153
9154  /// Check assignment constraints and optionally prepare for a conversion of
9155  /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
9156  /// is true.
9157  AssignConvertType CheckAssignmentConstraints(QualType LHSType,
9158                                               ExprResult &RHS,
9159                                               CastKind &Kind,
9160                                               bool ConvertRHS = true);
9161
9162  /// Check assignment constraints for an assignment of RHS to LHSType.
9163  ///
9164  /// \param LHSType The destination type for the assignment.
9165  /// \param RHS The source expression for the assignment.
9166  /// \param Diagnose If \c true, diagnostics may be produced when checking
9167  ///        for assignability. If a diagnostic is produced, \p RHS will be
9168  ///        set to ExprError(). Note that this function may still return
9169  ///        without producing a diagnostic, even for an invalid assignment.
9170  /// \param DiagnoseCFAudited If \c true, the target is a function parameter
9171  ///        in an audited Core Foundation API and does not need to be checked
9172  ///        for ARC retain issues.
9173  /// \param ConvertRHS If \c true, \p RHS will be updated to model the
9174  ///        conversions necessary to perform the assignment. If \c false,
9175  ///        \p Diagnose must also be \c false.
9176  AssignConvertType CheckSingleAssignmentConstraints(
9177      QualType LHSType, ExprResult &RHS, bool Diagnose = true,
9178      bool DiagnoseCFAudited = false, bool ConvertRHS = true);
9179
9180  // \brief If the lhs type is a transparent union, check whether we
9181  // can initialize the transparent union with the given expression.
9182  AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
9183                                                             ExprResult &RHS);
9184
9185  bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
9186
9187  bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
9188
9189  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9190                                       AssignmentAction Action,
9191                                       bool AllowExplicit = false);
9192  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9193                                       AssignmentAction Action,
9194                                       bool AllowExplicit,
9195                                       ImplicitConversionSequence& ICS);
9196  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9197                                       const ImplicitConversionSequence& ICS,
9198                                       AssignmentAction Action,
9199                                       CheckedConversionKind CCK
9200                                          = CCK_ImplicitConversion);
9201  ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9202                                       const StandardConversionSequence& SCS,
9203                                       AssignmentAction Action,
9204                                       CheckedConversionKind CCK);
9205
9206  /// the following "Check" methods will return a valid/converted QualType
9207  /// or a null QualType (indicating an error diagnostic was issued).
9208
9209  /// type checking binary operators (subroutines of CreateBuiltinBinOp).
9210  QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9211                           ExprResult &RHS);
9212  QualType CheckPointerToMemberOperands( // C++ 5.5
9213    ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
9214    SourceLocation OpLoc, bool isIndirect);
9215  QualType CheckMultiplyDivideOperands( // C99 6.5.5
9216    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
9217    bool IsDivide);
9218  QualType CheckRemainderOperands( // C99 6.5.5
9219    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9220    bool IsCompAssign = false);
9221  QualType CheckAdditionOperands( // C99 6.5.6
9222    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9223    BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
9224  QualType CheckSubtractionOperands( // C99 6.5.6
9225    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9226    QualType* CompLHSTy = nullptr);
9227  QualType CheckShiftOperands( // C99 6.5.7
9228    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9229    BinaryOperatorKind Opc, bool IsCompAssign = false);
9230  QualType CheckCompareOperands( // C99 6.5.8/9
9231    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9232    BinaryOperatorKind Opc, bool isRelational);
9233  QualType CheckBitwiseOperands( // C99 6.5.[10...12]
9234      ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9235      BinaryOperatorKind Opc);
9236  QualType CheckLogicalOperands( // C99 6.5.[13,14]
9237    ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9238    BinaryOperatorKind Opc);
9239  // CheckAssignmentOperands is used for both simple and compound assignment.
9240  // For simple assignment, pass both expressions and a null converted type.
9241  // For compound assignment, pass both expressions and the converted type.
9242  QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
9243    Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
9244
9245  ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
9246                                     UnaryOperatorKind Opcode, Expr *Op);
9247  ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
9248                                         BinaryOperatorKind Opcode,
9249                                         Expr *LHS, Expr *RHS);
9250  ExprResult checkPseudoObjectRValue(Expr *E);
9251  Expr *recreateSyntacticForm(PseudoObjectExpr *E);
9252
9253  QualType CheckConditionalOperands( // C99 6.5.15
9254    ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
9255    ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
9256  QualType CXXCheckConditionalOperands( // C++ 5.16
9257    ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
9258    ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
9259  QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
9260                                    bool ConvertArgs = true);
9261  QualType FindCompositePointerType(SourceLocation Loc,
9262                                    ExprResult &E1, ExprResult &E2,
9263                                    bool ConvertArgs = true) {
9264    Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
9265    QualType Composite =
9266        FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
9267    E1 = E1Tmp;
9268    E2 = E2Tmp;
9269    return Composite;
9270  }
9271
9272  QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
9273                                        SourceLocation QuestionLoc);
9274
9275  bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
9276                                  SourceLocation QuestionLoc);
9277
9278  void DiagnoseAlwaysNonNullPointer(Expr *E,
9279                                    Expr::NullPointerConstantKind NullType,
9280                                    bool IsEqual, SourceRange Range);
9281
9282  /// type checking for vector binary operators.
9283  QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9284                               SourceLocation Loc, bool IsCompAssign,
9285                               bool AllowBothBool, bool AllowBoolConversion);
9286  QualType GetSignedVectorType(QualType V);
9287  QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9288                                      SourceLocation Loc, bool isRelational);
9289  QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9290                                      SourceLocation Loc);
9291
9292  bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
9293  bool isLaxVectorConversion(QualType srcType, QualType destType);
9294
9295  /// type checking declaration initializers (C99 6.7.8)
9296  bool CheckForConstantInitializer(Expr *e, QualType t);
9297
9298  // type checking C++ declaration initializers (C++ [dcl.init]).
9299
9300  /// ReferenceCompareResult - Expresses the result of comparing two
9301  /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
9302  /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
9303  enum ReferenceCompareResult {
9304    /// Ref_Incompatible - The two types are incompatible, so direct
9305    /// reference binding is not possible.
9306    Ref_Incompatible = 0,
9307    /// Ref_Related - The two types are reference-related, which means
9308    /// that their unqualified forms (T1 and T2) are either the same
9309    /// or T1 is a base class of T2.
9310    Ref_Related,
9311    /// Ref_Compatible - The two types are reference-compatible.
9312    Ref_Compatible
9313  };
9314
9315  ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
9316                                                      QualType T1, QualType T2,
9317                                                      bool &DerivedToBase,
9318                                                      bool &ObjCConversion,
9319                                                bool &ObjCLifetimeConversion);
9320
9321  ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
9322                                 Expr *CastExpr, CastKind &CastKind,
9323                                 ExprValueKind &VK, CXXCastPath &Path);
9324
9325  /// \brief Force an expression with unknown-type to an expression of the
9326  /// given type.
9327  ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
9328
9329  /// \brief Type-check an expression that's being passed to an
9330  /// __unknown_anytype parameter.
9331  ExprResult checkUnknownAnyArg(SourceLocation callLoc,
9332                                Expr *result, QualType &paramType);
9333
9334  // CheckVectorCast - check type constraints for vectors.
9335  // Since vectors are an extension, there are no C standard reference for this.
9336  // We allow casting between vectors and integer datatypes of the same size.
9337  // returns true if the cast is invalid
9338  bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
9339                       CastKind &Kind);
9340
9341  /// \brief Prepare `SplattedExpr` for a vector splat operation, adding
9342  /// implicit casts if necessary.
9343  ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
9344
9345  // CheckExtVectorCast - check type constraints for extended vectors.
9346  // Since vectors are an extension, there are no C standard reference for this.
9347  // We allow casting between vectors and integer datatypes of the same size,
9348  // or vectors and the element type of that vector.
9349  // returns the cast expr
9350  ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
9351                                CastKind &Kind);
9352
9353  ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
9354                                        SourceLocation LParenLoc,
9355                                        Expr *CastExpr,
9356                                        SourceLocation RParenLoc);
9357
9358  enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
9359
9360  /// \brief Checks for invalid conversions and casts between
9361  /// retainable pointers and other pointer kinds for ARC and Weak.
9362  ARCConversionResult CheckObjCConversion(SourceRange castRange,
9363                                          QualType castType, Expr *&op,
9364                                          CheckedConversionKind CCK,
9365                                          bool Diagnose = true,
9366                                          bool DiagnoseCFAudited = false,
9367                                          BinaryOperatorKind Opc = BO_PtrMemD
9368                                          );
9369
9370  Expr *stripARCUnbridgedCast(Expr *e);
9371  void diagnoseARCUnbridgedCast(Expr *e);
9372
9373  bool CheckObjCARCUnavailableWeakConversion(QualType castType,
9374                                             QualType ExprType);
9375
9376  /// checkRetainCycles - Check whether an Objective-C message send
9377  /// might create an obvious retain cycle.
9378  void checkRetainCycles(ObjCMessageExpr *msg);
9379  void checkRetainCycles(Expr *receiver, Expr *argument);
9380  void checkRetainCycles(VarDecl *Var, Expr *Init);
9381
9382  /// checkUnsafeAssigns - Check whether +1 expr is being assigned
9383  /// to weak/__unsafe_unretained type.
9384  bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
9385
9386  /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
9387  /// to weak/__unsafe_unretained expression.
9388  void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
9389
9390  /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
9391  /// \param Method - May be null.
9392  /// \param [out] ReturnType - The return type of the send.
9393  /// \return true iff there were any incompatible types.
9394  bool CheckMessageArgumentTypes(QualType ReceiverType,
9395                                 MultiExprArg Args, Selector Sel,
9396                                 ArrayRef<SourceLocation> SelectorLocs,
9397                                 ObjCMethodDecl *Method, bool isClassMessage,
9398                                 bool isSuperMessage,
9399                                 SourceLocation lbrac, SourceLocation rbrac,
9400                                 SourceRange RecRange,
9401                                 QualType &ReturnType, ExprValueKind &VK);
9402
9403  /// \brief Determine the result of a message send expression based on
9404  /// the type of the receiver, the method expected to receive the message,
9405  /// and the form of the message send.
9406  QualType getMessageSendResultType(QualType ReceiverType,
9407                                    ObjCMethodDecl *Method,
9408                                    bool isClassMessage, bool isSuperMessage);
9409
9410  /// \brief If the given expression involves a message send to a method
9411  /// with a related result type, emit a note describing what happened.
9412  void EmitRelatedResultTypeNote(const Expr *E);
9413
9414  /// \brief Given that we had incompatible pointer types in a return
9415  /// statement, check whether we're in a method with a related result
9416  /// type, and if so, emit a note describing what happened.
9417  void EmitRelatedResultTypeNoteForReturn(QualType destType);
9418
9419  class ConditionResult {
9420    Decl *ConditionVar;
9421    FullExprArg Condition;
9422    bool Invalid;
9423    bool HasKnownValue;
9424    bool KnownValue;
9425
9426    friend class Sema;
9427    ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
9428                    bool IsConstexpr)
9429        : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
9430          HasKnownValue(IsConstexpr && Condition.get() &&
9431                        !Condition.get()->isValueDependent()),
9432          KnownValue(HasKnownValue &&
9433                     !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
9434    explicit ConditionResult(bool Invalid)
9435        : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
9436          HasKnownValue(false), KnownValue(false) {}
9437
9438  public:
9439    ConditionResult() : ConditionResult(false) {}
9440    bool isInvalid() const { return Invalid; }
9441    std::pair<VarDecl *, Expr *> get() const {
9442      return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
9443                            Condition.get());
9444    }
9445    llvm::Optional<bool> getKnownValue() const {
9446      if (!HasKnownValue)
9447        return None;
9448      return KnownValue;
9449    }
9450  };
9451  static ConditionResult ConditionError() { return ConditionResult(true); }
9452
9453  enum class ConditionKind {
9454    Boolean,     ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
9455    ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
9456    Switch       ///< An integral condition for a 'switch' statement.
9457  };
9458
9459  ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
9460                                 Expr *SubExpr, ConditionKind CK);
9461
9462  ConditionResult ActOnConditionVariable(Decl *ConditionVar,
9463                                         SourceLocation StmtLoc,
9464                                         ConditionKind CK);
9465
9466  DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
9467
9468  ExprResult CheckConditionVariable(VarDecl *ConditionVar,
9469                                    SourceLocation StmtLoc,
9470                                    ConditionKind CK);
9471  ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
9472
9473  /// CheckBooleanCondition - Diagnose problems involving the use of
9474  /// the given expression as a boolean condition (e.g. in an if
9475  /// statement).  Also performs the standard function and array
9476  /// decays, possibly changing the input variable.
9477  ///
9478  /// \param Loc - A location associated with the condition, e.g. the
9479  /// 'if' keyword.
9480  /// \return true iff there were any errors
9481  ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
9482                                   bool IsConstexpr = false);
9483
9484  /// DiagnoseAssignmentAsCondition - Given that an expression is
9485  /// being used as a boolean condition, warn if it's an assignment.
9486  void DiagnoseAssignmentAsCondition(Expr *E);
9487
9488  /// \brief Redundant parentheses over an equality comparison can indicate
9489  /// that the user intended an assignment used as condition.
9490  void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
9491
9492  /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
9493  ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
9494
9495  /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
9496  /// the specified width and sign.  If an overflow occurs, detect it and emit
9497  /// the specified diagnostic.
9498  void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
9499                                          unsigned NewWidth, bool NewSign,
9500                                          SourceLocation Loc, unsigned DiagID);
9501
9502  /// Checks that the Objective-C declaration is declared in the global scope.
9503  /// Emits an error and marks the declaration as invalid if it's not declared
9504  /// in the global scope.
9505  bool CheckObjCDeclScope(Decl *D);
9506
9507  /// \brief Abstract base class used for diagnosing integer constant
9508  /// expression violations.
9509  class VerifyICEDiagnoser {
9510  public:
9511    bool Suppress;
9512
9513    VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
9514
9515    virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
9516    virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
9517    virtual ~VerifyICEDiagnoser() { }
9518  };
9519
9520  /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
9521  /// and reports the appropriate diagnostics. Returns false on success.
9522  /// Can optionally return the value of the expression.
9523  ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9524                                             VerifyICEDiagnoser &Diagnoser,
9525                                             bool AllowFold = true);
9526  ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9527                                             unsigned DiagID,
9528                                             bool AllowFold = true);
9529  ExprResult VerifyIntegerConstantExpression(Expr *E,
9530                                             llvm::APSInt *Result = nullptr);
9531
9532  /// VerifyBitField - verifies that a bit field expression is an ICE and has
9533  /// the correct width, and that the field type is valid.
9534  /// Returns false on success.
9535  /// Can optionally return whether the bit-field is of width 0
9536  ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
9537                            QualType FieldTy, bool IsMsStruct,
9538                            Expr *BitWidth, bool *ZeroWidth = nullptr);
9539
9540private:
9541  unsigned ForceCUDAHostDeviceDepth = 0;
9542
9543public:
9544  /// Increments our count of the number of times we've seen a pragma forcing
9545  /// functions to be __host__ __device__.  So long as this count is greater
9546  /// than zero, all functions encountered will be __host__ __device__.
9547  void PushForceCUDAHostDevice();
9548
9549  /// Decrements our count of the number of times we've seen a pragma forcing
9550  /// functions to be __host__ __device__.  Returns false if the count is 0
9551  /// before incrementing, so you can emit an error.
9552  bool PopForceCUDAHostDevice();
9553
9554  /// Diagnostics that are emitted only if we discover that the given function
9555  /// must be codegen'ed.  Because handling these correctly adds overhead to
9556  /// compilation, this is currently only enabled for CUDA compilations.
9557  llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
9558                 std::vector<PartialDiagnosticAt>>
9559      CUDADeferredDiags;
9560
9561  /// A pair of a canonical FunctionDecl and a SourceLocation.  When used as the
9562  /// key in a hashtable, both the FD and location are hashed.
9563  struct FunctionDeclAndLoc {
9564    CanonicalDeclPtr<FunctionDecl> FD;
9565    SourceLocation Loc;
9566  };
9567
9568  /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
9569  /// (maybe deferred) "bad call" diagnostic.  We use this to avoid emitting the
9570  /// same deferred diag twice.
9571  llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
9572
9573  /// An inverse call graph, mapping known-emitted functions to one of their
9574  /// known-emitted callers (plus the location of the call).
9575  ///
9576  /// Functions that we can tell a priori must be emitted aren't added to this
9577  /// map.
9578  llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
9579                 /* Caller = */ FunctionDeclAndLoc>
9580      CUDAKnownEmittedFns;
9581
9582  /// A partial call graph maintained during CUDA compilation to support
9583  /// deferred diagnostics.
9584  ///
9585  /// Functions are only added here if, at the time they're considered, they are
9586  /// not known-emitted.  As soon as we discover that a function is
9587  /// known-emitted, we remove it and everything it transitively calls from this
9588  /// set and add those functions to CUDAKnownEmittedFns.
9589  llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
9590                 /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
9591                                                 SourceLocation>>
9592      CUDACallGraph;
9593
9594  /// Diagnostic builder for CUDA errors which may or may not be deferred.
9595  ///
9596  /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
9597  /// which are not allowed to appear inside __device__ functions and are
9598  /// allowed to appear in __host__ __device__ functions only if the host+device
9599  /// function is never codegen'ed.
9600  ///
9601  /// To handle this, we use the notion of "deferred diagnostics", where we
9602  /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
9603  ///
9604  /// This class lets you emit either a regular diagnostic, a deferred
9605  /// diagnostic, or no diagnostic at all, according to an argument you pass to
9606  /// its constructor, thus simplifying the process of creating these "maybe
9607  /// deferred" diagnostics.
9608  class CUDADiagBuilder {
9609  public:
9610    enum Kind {
9611      /// Emit no diagnostics.
9612      K_Nop,
9613      /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
9614      K_Immediate,
9615      /// Emit the diagnostic immediately, and, if it's a warning or error, also
9616      /// emit a call stack showing how this function can be reached by an a
9617      /// priori known-emitted function.
9618      K_ImmediateWithCallStack,
9619      /// Create a deferred diagnostic, which is emitted only if the function
9620      /// it's attached to is codegen'ed.  Also emit a call stack as with
9621      /// K_ImmediateWithCallStack.
9622      K_Deferred
9623    };
9624
9625    CUDADiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
9626                    FunctionDecl *Fn, Sema &S);
9627    ~CUDADiagBuilder();
9628
9629    /// Convertible to bool: True if we immediately emitted an error, false if
9630    /// we didn't emit an error or we created a deferred error.
9631    ///
9632    /// Example usage:
9633    ///
9634    ///   if (CUDADiagBuilder(...) << foo << bar)
9635    ///     return ExprError();
9636    ///
9637    /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
9638    /// want to use these instead of creating a CUDADiagBuilder yourself.
9639    operator bool() const { return ImmediateDiag.hasValue(); }
9640
9641    template <typename T>
9642    friend const CUDADiagBuilder &operator<<(const CUDADiagBuilder &Diag,
9643                                             const T &Value) {
9644      if (Diag.ImmediateDiag.hasValue())
9645        *Diag.ImmediateDiag << Value;
9646      else if (Diag.PartialDiag.hasValue())
9647        *Diag.PartialDiag << Value;
9648      return Diag;
9649    }
9650
9651  private:
9652    Sema &S;
9653    SourceLocation Loc;
9654    unsigned DiagID;
9655    FunctionDecl *Fn;
9656    bool ShowCallStack;
9657
9658    // Invariant: At most one of these Optionals has a value.
9659    // FIXME: Switch these to a Variant once that exists.
9660    llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
9661    llvm::Optional<PartialDiagnostic> PartialDiag;
9662  };
9663
9664  /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9665  /// is "used as device code".
9666  ///
9667  /// - If CurContext is a __host__ function, does not emit any diagnostics.
9668  /// - If CurContext is a __device__ or __global__ function, emits the
9669  ///   diagnostics immediately.
9670  /// - If CurContext is a __host__ __device__ function and we are compiling for
9671  ///   the device, creates a diagnostic which is emitted if and when we realize
9672  ///   that the function will be codegen'ed.
9673  ///
9674  /// Example usage:
9675  ///
9676  ///  // Variable-length arrays are not allowed in CUDA device code.
9677  ///  if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
9678  ///    return ExprError();
9679  ///  // Otherwise, continue parsing as normal.
9680  CUDADiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
9681
9682  /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9683  /// is "used as host code".
9684  ///
9685  /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
9686  CUDADiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
9687
9688  enum CUDAFunctionTarget {
9689    CFT_Device,
9690    CFT_Global,
9691    CFT_Host,
9692    CFT_HostDevice,
9693    CFT_InvalidTarget
9694  };
9695
9696  /// Determines whether the given function is a CUDA device/host/kernel/etc.
9697  /// function.
9698  ///
9699  /// Use this rather than examining the function's attributes yourself -- you
9700  /// will get it wrong.  Returns CFT_Host if D is null.
9701  CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
9702                                        bool IgnoreImplicitHDAttr = false);
9703  CUDAFunctionTarget IdentifyCUDATarget(const AttributeList *Attr);
9704
9705  /// Gets the CUDA target for the current context.
9706  CUDAFunctionTarget CurrentCUDATarget() {
9707    return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
9708  }
9709
9710  // CUDA function call preference. Must be ordered numerically from
9711  // worst to best.
9712  enum CUDAFunctionPreference {
9713    CFP_Never,      // Invalid caller/callee combination.
9714    CFP_WrongSide,  // Calls from host-device to host or device
9715                    // function that do not match current compilation
9716                    // mode.
9717    CFP_HostDevice, // Any calls to host/device functions.
9718    CFP_SameSide,   // Calls from host-device to host or device
9719                    // function matching current compilation mode.
9720    CFP_Native,     // host-to-host or device-to-device calls.
9721  };
9722
9723  /// Identifies relative preference of a given Caller/Callee
9724  /// combination, based on their host/device attributes.
9725  /// \param Caller function which needs address of \p Callee.
9726  ///               nullptr in case of global context.
9727  /// \param Callee target function
9728  ///
9729  /// \returns preference value for particular Caller/Callee combination.
9730  CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
9731                                                const FunctionDecl *Callee);
9732
9733  /// Determines whether Caller may invoke Callee, based on their CUDA
9734  /// host/device attributes.  Returns false if the call is not allowed.
9735  ///
9736  /// Note: Will return true for CFP_WrongSide calls.  These may appear in
9737  /// semantically correct CUDA programs, but only if they're never codegen'ed.
9738  bool IsAllowedCUDACall(const FunctionDecl *Caller,
9739                         const FunctionDecl *Callee) {
9740    return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
9741  }
9742
9743  /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
9744  /// depending on FD and the current compilation settings.
9745  void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
9746                                   const LookupResult &Previous);
9747
9748public:
9749  /// Check whether we're allowed to call Callee from the current context.
9750  ///
9751  /// - If the call is never allowed in a semantically-correct program
9752  ///   (CFP_Never), emits an error and returns false.
9753  ///
9754  /// - If the call is allowed in semantically-correct programs, but only if
9755  ///   it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
9756  ///   be emitted if and when the caller is codegen'ed, and returns true.
9757  ///
9758  ///   Will only create deferred diagnostics for a given SourceLocation once,
9759  ///   so you can safely call this multiple times without generating duplicate
9760  ///   deferred errors.
9761  ///
9762  /// - Otherwise, returns true without emitting any diagnostics.
9763  bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
9764
9765  /// Set __device__ or __host__ __device__ attributes on the given lambda
9766  /// operator() method.
9767  ///
9768  /// CUDA lambdas declared inside __device__ or __global__ functions inherit
9769  /// the __device__ attribute.  Similarly, lambdas inside __host__ __device__
9770  /// functions become __host__ __device__ themselves.
9771  void CUDASetLambdaAttrs(CXXMethodDecl *Method);
9772
9773  /// Finds a function in \p Matches with highest calling priority
9774  /// from \p Caller context and erases all functions with lower
9775  /// calling priority.
9776  void EraseUnwantedCUDAMatches(
9777      const FunctionDecl *Caller,
9778      SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
9779
9780  /// Given a implicit special member, infer its CUDA target from the
9781  /// calls it needs to make to underlying base/field special members.
9782  /// \param ClassDecl the class for which the member is being created.
9783  /// \param CSM the kind of special member.
9784  /// \param MemberDecl the special member itself.
9785  /// \param ConstRHS true if this is a copy operation with a const object on
9786  ///        its RHS.
9787  /// \param Diagnose true if this call should emit diagnostics.
9788  /// \return true if there was an error inferring.
9789  /// The result of this call is implicit CUDA target attribute(s) attached to
9790  /// the member declaration.
9791  bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
9792                                               CXXSpecialMember CSM,
9793                                               CXXMethodDecl *MemberDecl,
9794                                               bool ConstRHS,
9795                                               bool Diagnose);
9796
9797  /// \return true if \p CD can be considered empty according to CUDA
9798  /// (E.2.3.1 in CUDA 7.5 Programming guide).
9799  bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
9800  bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
9801
9802  /// Check whether NewFD is a valid overload for CUDA. Emits
9803  /// diagnostics and invalidates NewFD if not.
9804  void checkCUDATargetOverload(FunctionDecl *NewFD,
9805                               const LookupResult &Previous);
9806  /// Copies target attributes from the template TD to the function FD.
9807  void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
9808
9809  /// \name Code completion
9810  //@{
9811  /// \brief Describes the context in which code completion occurs.
9812  enum ParserCompletionContext {
9813    /// \brief Code completion occurs at top-level or namespace context.
9814    PCC_Namespace,
9815    /// \brief Code completion occurs within a class, struct, or union.
9816    PCC_Class,
9817    /// \brief Code completion occurs within an Objective-C interface, protocol,
9818    /// or category.
9819    PCC_ObjCInterface,
9820    /// \brief Code completion occurs within an Objective-C implementation or
9821    /// category implementation
9822    PCC_ObjCImplementation,
9823    /// \brief Code completion occurs within the list of instance variables
9824    /// in an Objective-C interface, protocol, category, or implementation.
9825    PCC_ObjCInstanceVariableList,
9826    /// \brief Code completion occurs following one or more template
9827    /// headers.
9828    PCC_Template,
9829    /// \brief Code completion occurs following one or more template
9830    /// headers within a class.
9831    PCC_MemberTemplate,
9832    /// \brief Code completion occurs within an expression.
9833    PCC_Expression,
9834    /// \brief Code completion occurs within a statement, which may
9835    /// also be an expression or a declaration.
9836    PCC_Statement,
9837    /// \brief Code completion occurs at the beginning of the
9838    /// initialization statement (or expression) in a for loop.
9839    PCC_ForInit,
9840    /// \brief Code completion occurs within the condition of an if,
9841    /// while, switch, or for statement.
9842    PCC_Condition,
9843    /// \brief Code completion occurs within the body of a function on a
9844    /// recovery path, where we do not have a specific handle on our position
9845    /// in the grammar.
9846    PCC_RecoveryInFunction,
9847    /// \brief Code completion occurs where only a type is permitted.
9848    PCC_Type,
9849    /// \brief Code completion occurs in a parenthesized expression, which
9850    /// might also be a type cast.
9851    PCC_ParenthesizedExpression,
9852    /// \brief Code completion occurs within a sequence of declaration
9853    /// specifiers within a function, method, or block.
9854    PCC_LocalDeclarationSpecifiers
9855  };
9856
9857  void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
9858  void CodeCompleteOrdinaryName(Scope *S,
9859                                ParserCompletionContext CompletionContext);
9860  void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
9861                            bool AllowNonIdentifiers,
9862                            bool AllowNestedNameSpecifiers);
9863
9864  struct CodeCompleteExpressionData;
9865  void CodeCompleteExpression(Scope *S,
9866                              const CodeCompleteExpressionData &Data);
9867  void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
9868                                       SourceLocation OpLoc, bool IsArrow,
9869                                       bool IsBaseExprStatement);
9870  void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
9871  void CodeCompleteTag(Scope *S, unsigned TagSpec);
9872  void CodeCompleteTypeQualifiers(DeclSpec &DS);
9873  void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
9874                                      const VirtSpecifiers *VS = nullptr);
9875  void CodeCompleteBracketDeclarator(Scope *S);
9876  void CodeCompleteCase(Scope *S);
9877  void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
9878  void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
9879                               ArrayRef<Expr *> Args);
9880  void CodeCompleteInitializer(Scope *S, Decl *D);
9881  void CodeCompleteReturn(Scope *S);
9882  void CodeCompleteAfterIf(Scope *S);
9883  void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
9884
9885  void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
9886                               bool EnteringContext);
9887  void CodeCompleteUsing(Scope *S);
9888  void CodeCompleteUsingDirective(Scope *S);
9889  void CodeCompleteNamespaceDecl(Scope *S);
9890  void CodeCompleteNamespaceAliasDecl(Scope *S);
9891  void CodeCompleteOperatorName(Scope *S);
9892  void CodeCompleteConstructorInitializer(
9893                                Decl *Constructor,
9894                                ArrayRef<CXXCtorInitializer *> Initializers);
9895
9896  void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
9897                                    bool AfterAmpersand);
9898
9899  void CodeCompleteObjCAtDirective(Scope *S);
9900  void CodeCompleteObjCAtVisibility(Scope *S);
9901  void CodeCompleteObjCAtStatement(Scope *S);
9902  void CodeCompleteObjCAtExpression(Scope *S);
9903  void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
9904  void CodeCompleteObjCPropertyGetter(Scope *S);
9905  void CodeCompleteObjCPropertySetter(Scope *S);
9906  void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
9907                                   bool IsParameter);
9908  void CodeCompleteObjCMessageReceiver(Scope *S);
9909  void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
9910                                    ArrayRef<IdentifierInfo *> SelIdents,
9911                                    bool AtArgumentExpression);
9912  void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
9913                                    ArrayRef<IdentifierInfo *> SelIdents,
9914                                    bool AtArgumentExpression,
9915                                    bool IsSuper = false);
9916  void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
9917                                       ArrayRef<IdentifierInfo *> SelIdents,
9918                                       bool AtArgumentExpression,
9919                                       ObjCInterfaceDecl *Super = nullptr);
9920  void CodeCompleteObjCForCollection(Scope *S,
9921                                     DeclGroupPtrTy IterationVar);
9922  void CodeCompleteObjCSelector(Scope *S,
9923                                ArrayRef<IdentifierInfo *> SelIdents);
9924  void CodeCompleteObjCProtocolReferences(
9925                                         ArrayRef<IdentifierLocPair> Protocols);
9926  void CodeCompleteObjCProtocolDecl(Scope *S);
9927  void CodeCompleteObjCInterfaceDecl(Scope *S);
9928  void CodeCompleteObjCSuperclass(Scope *S,
9929                                  IdentifierInfo *ClassName,
9930                                  SourceLocation ClassNameLoc);
9931  void CodeCompleteObjCImplementationDecl(Scope *S);
9932  void CodeCompleteObjCInterfaceCategory(Scope *S,
9933                                         IdentifierInfo *ClassName,
9934                                         SourceLocation ClassNameLoc);
9935  void CodeCompleteObjCImplementationCategory(Scope *S,
9936                                              IdentifierInfo *ClassName,
9937                                              SourceLocation ClassNameLoc);
9938  void CodeCompleteObjCPropertyDefinition(Scope *S);
9939  void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
9940                                              IdentifierInfo *PropertyName);
9941  void CodeCompleteObjCMethodDecl(Scope *S,
9942                                  bool IsInstanceMethod,
9943                                  ParsedType ReturnType);
9944  void CodeCompleteObjCMethodDeclSelector(Scope *S,
9945                                          bool IsInstanceMethod,
9946                                          bool AtParameterName,
9947                                          ParsedType ReturnType,
9948                                          ArrayRef<IdentifierInfo *> SelIdents);
9949  void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
9950                                            SourceLocation ClassNameLoc,
9951                                            bool IsBaseExprStatement);
9952  void CodeCompletePreprocessorDirective(bool InConditional);
9953  void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
9954  void CodeCompletePreprocessorMacroName(bool IsDefinition);
9955  void CodeCompletePreprocessorExpression();
9956  void CodeCompletePreprocessorMacroArgument(Scope *S,
9957                                             IdentifierInfo *Macro,
9958                                             MacroInfo *MacroInfo,
9959                                             unsigned Argument);
9960  void CodeCompleteNaturalLanguage();
9961  void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
9962                                   CodeCompletionTUInfo &CCTUInfo,
9963                  SmallVectorImpl<CodeCompletionResult> &Results);
9964  //@}
9965
9966  //===--------------------------------------------------------------------===//
9967  // Extra semantic analysis beyond the C type system
9968
9969public:
9970  SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
9971                                                unsigned ByteNo) const;
9972
9973private:
9974  void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
9975                        const ArraySubscriptExpr *ASE=nullptr,
9976                        bool AllowOnePastEnd=true, bool IndexNegated=false);
9977  void CheckArrayAccess(const Expr *E);
9978  // Used to grab the relevant information from a FormatAttr and a
9979  // FunctionDeclaration.
9980  struct FormatStringInfo {
9981    unsigned FormatIdx;
9982    unsigned FirstDataArg;
9983    bool HasVAListArg;
9984  };
9985
9986  static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
9987                                  FormatStringInfo *FSI);
9988  bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
9989                         const FunctionProtoType *Proto);
9990  bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
9991                           ArrayRef<const Expr *> Args);
9992  bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
9993                        const FunctionProtoType *Proto);
9994  bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
9995  void CheckConstructorCall(FunctionDecl *FDecl,
9996                            ArrayRef<const Expr *> Args,
9997                            const FunctionProtoType *Proto,
9998                            SourceLocation Loc);
9999
10000  void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
10001                 const Expr *ThisArg, ArrayRef<const Expr *> Args,
10002                 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
10003                 VariadicCallType CallType);
10004
10005  bool CheckObjCString(Expr *Arg);
10006  ExprResult CheckOSLogFormatStringArg(Expr *Arg);
10007
10008  ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
10009                                      unsigned BuiltinID, CallExpr *TheCall);
10010
10011  bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
10012                                    unsigned MaxWidth);
10013  bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10014  bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10015
10016  bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10017  bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10018  bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10019  bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
10020  bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
10021  bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10022  bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10023
10024  bool SemaBuiltinVAStartImpl(CallExpr *TheCall);
10025  bool SemaBuiltinVAStart(CallExpr *TheCall);
10026  bool SemaBuiltinMSVAStart(CallExpr *TheCall);
10027  bool SemaBuiltinVAStartARM(CallExpr *Call);
10028  bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
10029  bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
10030  bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
10031
10032public:
10033  // Used by C++ template instantiation.
10034  ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
10035  ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
10036                                   SourceLocation BuiltinLoc,
10037                                   SourceLocation RParenLoc);
10038
10039private:
10040  bool SemaBuiltinPrefetch(CallExpr *TheCall);
10041  bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
10042  bool SemaBuiltinAssume(CallExpr *TheCall);
10043  bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
10044  bool SemaBuiltinLongjmp(CallExpr *TheCall);
10045  bool SemaBuiltinSetjmp(CallExpr *TheCall);
10046  ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
10047  ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
10048  ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
10049                                     AtomicExpr::AtomicOp Op);
10050  bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
10051                              llvm::APSInt &Result);
10052  bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
10053                                   int Low, int High);
10054  bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
10055                                      unsigned Multiple);
10056  bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
10057                                int ArgNum, unsigned ExpectedFieldNum,
10058                                bool AllowName);
10059public:
10060  enum FormatStringType {
10061    FST_Scanf,
10062    FST_Printf,
10063    FST_NSString,
10064    FST_Strftime,
10065    FST_Strfmon,
10066    FST_Kprintf,
10067    FST_FreeBSDKPrintf,
10068    FST_OSTrace,
10069    FST_OSLog,
10070    FST_Unknown
10071  };
10072  static FormatStringType GetFormatStringType(const FormatAttr *Format);
10073
10074  bool FormatStringHasSArg(const StringLiteral *FExpr);
10075
10076  static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
10077
10078private:
10079  bool CheckFormatArguments(const FormatAttr *Format,
10080                            ArrayRef<const Expr *> Args,
10081                            bool IsCXXMember,
10082                            VariadicCallType CallType,
10083                            SourceLocation Loc, SourceRange Range,
10084                            llvm::SmallBitVector &CheckedVarArgs);
10085  bool CheckFormatArguments(ArrayRef<const Expr *> Args,
10086                            bool HasVAListArg, unsigned format_idx,
10087                            unsigned firstDataArg, FormatStringType Type,
10088                            VariadicCallType CallType,
10089                            SourceLocation Loc, SourceRange range,
10090                            llvm::SmallBitVector &CheckedVarArgs);
10091
10092  void CheckAbsoluteValueFunction(const CallExpr *Call,
10093                                  const FunctionDecl *FDecl);
10094
10095  void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
10096
10097  void CheckMemaccessArguments(const CallExpr *Call,
10098                               unsigned BId,
10099                               IdentifierInfo *FnName);
10100
10101  void CheckStrlcpycatArguments(const CallExpr *Call,
10102                                IdentifierInfo *FnName);
10103
10104  void CheckStrncatArguments(const CallExpr *Call,
10105                             IdentifierInfo *FnName);
10106
10107  void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10108                          SourceLocation ReturnLoc,
10109                          bool isObjCMethod = false,
10110                          const AttrVec *Attrs = nullptr,
10111                          const FunctionDecl *FD = nullptr);
10112
10113  void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
10114  void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
10115  void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
10116  void CheckForIntOverflow(Expr *E);
10117  void CheckUnsequencedOperations(Expr *E);
10118
10119  /// \brief Perform semantic checks on a completed expression. This will either
10120  /// be a full-expression or a default argument expression.
10121  void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
10122                          bool IsConstexpr = false);
10123
10124  void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
10125                                   Expr *Init);
10126
10127  /// Check if there is a field shadowing.
10128  void CheckShadowInheritedFields(const SourceLocation &Loc,
10129                                  DeclarationName FieldName,
10130                                  const CXXRecordDecl *RD);
10131
10132  /// \brief Check if the given expression contains 'break' or 'continue'
10133  /// statement that produces control flow different from GCC.
10134  void CheckBreakContinueBinding(Expr *E);
10135
10136  /// \brief Check whether receiver is mutable ObjC container which
10137  /// attempts to add itself into the container
10138  void CheckObjCCircularContainer(ObjCMessageExpr *Message);
10139
10140  void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
10141  void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
10142                                 bool DeleteWasArrayForm);
10143public:
10144  /// \brief Register a magic integral constant to be used as a type tag.
10145  void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10146                                  uint64_t MagicValue, QualType Type,
10147                                  bool LayoutCompatible, bool MustBeNull);
10148
10149  struct TypeTagData {
10150    TypeTagData() {}
10151
10152    TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
10153        Type(Type), LayoutCompatible(LayoutCompatible),
10154        MustBeNull(MustBeNull)
10155    {}
10156
10157    QualType Type;
10158
10159    /// If true, \c Type should be compared with other expression's types for
10160    /// layout-compatibility.
10161    unsigned LayoutCompatible : 1;
10162    unsigned MustBeNull : 1;
10163  };
10164
10165  /// A pair of ArgumentKind identifier and magic value.  This uniquely
10166  /// identifies the magic value.
10167  typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
10168
10169private:
10170  /// \brief A map from magic value to type information.
10171  std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
10172      TypeTagForDatatypeMagicValues;
10173
10174  /// \brief Peform checks on a call of a function with argument_with_type_tag
10175  /// or pointer_with_type_tag attributes.
10176  void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10177                                const Expr * const *ExprArgs);
10178
10179  /// \brief Check if we are taking the address of a packed field
10180  /// as this may be a problem if the pointer value is dereferenced.
10181  void CheckAddressOfPackedMember(Expr *rhs);
10182
10183  /// \brief The parser's current scope.
10184  ///
10185  /// The parser maintains this state here.
10186  Scope *CurScope;
10187
10188  mutable IdentifierInfo *Ident_super;
10189  mutable IdentifierInfo *Ident___float128;
10190
10191  /// Nullability type specifiers.
10192  IdentifierInfo *Ident__Nonnull = nullptr;
10193  IdentifierInfo *Ident__Nullable = nullptr;
10194  IdentifierInfo *Ident__Null_unspecified = nullptr;
10195
10196  IdentifierInfo *Ident_NSError = nullptr;
10197
10198protected:
10199  friend class Parser;
10200  friend class InitializationSequence;
10201  friend class ASTReader;
10202  friend class ASTDeclReader;
10203  friend class ASTWriter;
10204
10205public:
10206  /// Retrieve the keyword associated
10207  IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
10208
10209  /// The struct behind the CFErrorRef pointer.
10210  RecordDecl *CFError = nullptr;
10211
10212  /// Retrieve the identifier "NSError".
10213  IdentifierInfo *getNSErrorIdent();
10214
10215  /// \brief Retrieve the parser's current scope.
10216  ///
10217  /// This routine must only be used when it is certain that semantic analysis
10218  /// and the parser are in precisely the same context, which is not the case
10219  /// when, e.g., we are performing any kind of template instantiation.
10220  /// Therefore, the only safe places to use this scope are in the parser
10221  /// itself and in routines directly invoked from the parser and *never* from
10222  /// template substitution or instantiation.
10223  Scope *getCurScope() const { return CurScope; }
10224
10225  void incrementMSManglingNumber() const {
10226    return CurScope->incrementMSManglingNumber();
10227  }
10228
10229  IdentifierInfo *getSuperIdentifier() const;
10230  IdentifierInfo *getFloat128Identifier() const;
10231
10232  Decl *getObjCDeclContext() const;
10233
10234  DeclContext *getCurLexicalContext() const {
10235    return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
10236  }
10237
10238  /// \brief The diagnostic we should emit for \c D, or \c AR_Available.
10239  ///
10240  /// \param D The declaration to check. Note that this may be altered to point
10241  /// to another declaration that \c D gets it's availability from. i.e., we
10242  /// walk the list of typedefs to find an availability attribute.
10243  ///
10244  /// \param Message If non-null, this will be populated with the message from
10245  /// the availability attribute that is selected.
10246  AvailabilityResult ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D,
10247                                                      std::string *Message);
10248
10249  const DeclContext *getCurObjCLexicalContext() const {
10250    const DeclContext *DC = getCurLexicalContext();
10251    // A category implicitly has the attribute of the interface.
10252    if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
10253      DC = CatD->getClassInterface();
10254    return DC;
10255  }
10256
10257  /// \brief To be used for checking whether the arguments being passed to
10258  /// function exceeds the number of parameters expected for it.
10259  static bool TooManyArguments(size_t NumParams, size_t NumArgs,
10260                               bool PartialOverloading = false) {
10261    // We check whether we're just after a comma in code-completion.
10262    if (NumArgs > 0 && PartialOverloading)
10263      return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
10264    return NumArgs > NumParams;
10265  }
10266
10267  // Emitting members of dllexported classes is delayed until the class
10268  // (including field initializers) is fully parsed.
10269  SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
10270
10271private:
10272  /// \brief Helper class that collects misaligned member designations and
10273  /// their location info for delayed diagnostics.
10274  struct MisalignedMember {
10275    Expr *E;
10276    RecordDecl *RD;
10277    ValueDecl *MD;
10278    CharUnits Alignment;
10279
10280    MisalignedMember() : E(), RD(), MD(), Alignment() {}
10281    MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
10282                     CharUnits Alignment)
10283        : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
10284    explicit MisalignedMember(Expr *E)
10285        : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
10286
10287    bool operator==(const MisalignedMember &m) { return this->E == m.E; }
10288  };
10289  /// \brief Small set of gathered accesses to potentially misaligned members
10290  /// due to the packed attribute.
10291  SmallVector<MisalignedMember, 4> MisalignedMembers;
10292
10293  /// \brief Adds an expression to the set of gathered misaligned members.
10294  void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
10295                                     CharUnits Alignment);
10296
10297public:
10298  /// \brief Diagnoses the current set of gathered accesses. This typically
10299  /// happens at full expression level. The set is cleared after emitting the
10300  /// diagnostics.
10301  void DiagnoseMisalignedMembers();
10302
10303  /// \brief This function checks if the expression is in the sef of potentially
10304  /// misaligned members and it is converted to some pointer type T with lower
10305  /// or equal alignment requirements. If so it removes it. This is used when
10306  /// we do not want to diagnose such misaligned access (e.g. in conversions to
10307  /// void*).
10308  void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
10309
10310  /// \brief This function calls Action when it determines that E designates a
10311  /// misaligned member due to the packed attribute. This is used to emit
10312  /// local diagnostics like in reference binding.
10313  void RefersToMemberWithReducedAlignment(
10314      Expr *E,
10315      llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
10316          Action);
10317};
10318
10319/// \brief RAII object that enters a new expression evaluation context.
10320class EnterExpressionEvaluationContext {
10321  Sema &Actions;
10322  bool Entered = true;
10323
10324public:
10325
10326  EnterExpressionEvaluationContext(Sema &Actions,
10327                                   Sema::ExpressionEvaluationContext NewContext,
10328                                   Decl *LambdaContextDecl = nullptr,
10329                                   bool IsDecltype = false,
10330                                   bool ShouldEnter = true)
10331      : Actions(Actions), Entered(ShouldEnter) {
10332    if (Entered)
10333      Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
10334                                              IsDecltype);
10335  }
10336  EnterExpressionEvaluationContext(Sema &Actions,
10337                                   Sema::ExpressionEvaluationContext NewContext,
10338                                   Sema::ReuseLambdaContextDecl_t,
10339                                   bool IsDecltype = false)
10340    : Actions(Actions) {
10341    Actions.PushExpressionEvaluationContext(NewContext,
10342                                            Sema::ReuseLambdaContextDecl,
10343                                            IsDecltype);
10344  }
10345
10346  enum InitListTag { InitList };
10347  EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
10348                                   bool ShouldEnter = true)
10349      : Actions(Actions), Entered(false) {
10350    // In C++11 onwards, narrowing checks are performed on the contents of
10351    // braced-init-lists, even when they occur within unevaluated operands.
10352    // Therefore we still need to instantiate constexpr functions used in such
10353    // a context.
10354    if (ShouldEnter && Actions.isUnevaluatedContext() &&
10355        Actions.getLangOpts().CPlusPlus11) {
10356      Actions.PushExpressionEvaluationContext(
10357          Sema::ExpressionEvaluationContext::UnevaluatedList, nullptr, false);
10358      Entered = true;
10359    }
10360  }
10361
10362  ~EnterExpressionEvaluationContext() {
10363    if (Entered)
10364      Actions.PopExpressionEvaluationContext();
10365  }
10366};
10367
10368DeductionFailureInfo
10369MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
10370                         sema::TemplateDeductionInfo &Info);
10371
10372/// \brief Contains a late templated function.
10373/// Will be parsed at the end of the translation unit, used by Sema & Parser.
10374struct LateParsedTemplate {
10375  CachedTokens Toks;
10376  /// \brief The template function declaration to be late parsed.
10377  Decl *D;
10378};
10379
10380} // end namespace clang
10381
10382namespace llvm {
10383// Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
10384// SourceLocation.
10385template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
10386  using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
10387  using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
10388
10389  static FunctionDeclAndLoc getEmptyKey() {
10390    return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
10391  }
10392
10393  static FunctionDeclAndLoc getTombstoneKey() {
10394    return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
10395  }
10396
10397  static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
10398    return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
10399                        FDL.Loc.getRawEncoding());
10400  }
10401
10402  static bool isEqual(const FunctionDeclAndLoc &LHS,
10403                      const FunctionDeclAndLoc &RHS) {
10404    return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
10405  }
10406};
10407} // namespace llvm
10408
10409#endif
10410