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