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