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