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