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