]> granicus.if.org Git - clang/blob - include/clang/Sema/Sema.h
[OPENMP] Initial support for 'task_reduction' clause.
[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 EmitAvailabilityWarning(AvailabilityResult AR,
3885                                const NamedDecl *ReferringDecl,
3886                                const NamedDecl *OffendingDecl,
3887                                StringRef Message, SourceLocation Loc,
3888                                const ObjCInterfaceDecl *UnknownObjCClass,
3889                                const ObjCPropertyDecl *ObjCProperty,
3890                                bool ObjCPropertyAccess);
3891
3892   bool makeUnavailableInSystemHeader(SourceLocation loc,
3893                                      UnavailableAttr::ImplicitReason reason);
3894
3895   /// \brief Issue any -Wunguarded-availability warnings in \c FD
3896   void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
3897
3898   //===--------------------------------------------------------------------===//
3899   // Expression Parsing Callbacks: SemaExpr.cpp.
3900
3901   bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
3902   bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
3903                          const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
3904                          bool ObjCPropertyAccess = false,
3905                          bool AvoidPartialAvailabilityChecks = false);
3906   void NoteDeletedFunction(FunctionDecl *FD);
3907   void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
3908   std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
3909   bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
3910                                         ObjCMethodDecl *Getter,
3911                                         SourceLocation Loc);
3912   void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
3913                              ArrayRef<Expr *> Args);
3914
3915   void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3916                                        Decl *LambdaContextDecl = nullptr,
3917                                        bool IsDecltype = false);
3918   enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
3919   void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
3920                                        ReuseLambdaContextDecl_t,
3921                                        bool IsDecltype = false);
3922   void PopExpressionEvaluationContext();
3923
3924   void DiscardCleanupsInEvaluationContext();
3925
3926   ExprResult TransformToPotentiallyEvaluated(Expr *E);
3927   ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
3928
3929   ExprResult ActOnConstantExpression(ExprResult Res);
3930
3931   // Functions for marking a declaration referenced.  These functions also
3932   // contain the relevant logic for marking if a reference to a function or
3933   // variable is an odr-use (in the C++11 sense).  There are separate variants
3934   // for expressions referring to a decl; these exist because odr-use marking
3935   // needs to be delayed for some constant variables when we build one of the
3936   // named expressions.
3937   //
3938   // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
3939   // should usually be true. This only needs to be set to false if the lack of
3940   // odr-use cannot be determined from the current context (for instance,
3941   // because the name denotes a virtual function and was written without an
3942   // explicit nested-name-specifier).
3943   void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
3944   void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
3945                               bool MightBeOdrUse = true);
3946   void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
3947   void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
3948   void MarkMemberReferenced(MemberExpr *E);
3949
3950   void UpdateMarkingForLValueToRValue(Expr *E);
3951   void CleanupVarDeclMarking();
3952
3953   enum TryCaptureKind {
3954     TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
3955   };
3956
3957   /// \brief Try to capture the given variable.
3958   ///
3959   /// \param Var The variable to capture.
3960   ///
3961   /// \param Loc The location at which the capture occurs.
3962   ///
3963   /// \param Kind The kind of capture, which may be implicit (for either a
3964   /// block or a lambda), or explicit by-value or by-reference (for a lambda).
3965   ///
3966   /// \param EllipsisLoc The location of the ellipsis, if one is provided in
3967   /// an explicit lambda capture.
3968   ///
3969   /// \param BuildAndDiagnose Whether we are actually supposed to add the
3970   /// captures or diagnose errors. If false, this routine merely check whether
3971   /// the capture can occur without performing the capture itself or complaining
3972   /// if the variable cannot be captured.
3973   ///
3974   /// \param CaptureType Will be set to the type of the field used to capture
3975   /// this variable in the innermost block or lambda. Only valid when the
3976   /// variable can be captured.
3977   ///
3978   /// \param DeclRefType Will be set to the type of a reference to the capture
3979   /// from within the current scope. Only valid when the variable can be
3980   /// captured.
3981   ///
3982   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
3983   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
3984   /// This is useful when enclosing lambdas must speculatively capture
3985   /// variables that may or may not be used in certain specializations of
3986   /// a nested generic lambda.
3987   ///
3988   /// \returns true if an error occurred (i.e., the variable cannot be
3989   /// captured) and false if the capture succeeded.
3990   bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
3991                           SourceLocation EllipsisLoc, bool BuildAndDiagnose,
3992                           QualType &CaptureType,
3993                           QualType &DeclRefType,
3994                           const unsigned *const FunctionScopeIndexToStopAt);
3995
3996   /// \brief Try to capture the given variable.
3997   bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
3998                           TryCaptureKind Kind = TryCapture_Implicit,
3999                           SourceLocation EllipsisLoc = SourceLocation());
4000
4001   /// \brief Checks if the variable must be captured.
4002   bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
4003
4004   /// \brief Given a variable, determine the type that a reference to that
4005   /// variable will have in the given scope.
4006   QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
4007
4008   /// Mark all of the declarations referenced within a particular AST node as
4009   /// referenced. Used when template instantiation instantiates a non-dependent
4010   /// type -- entities referenced by the type are now referenced.
4011   void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
4012   void MarkDeclarationsReferencedInExpr(Expr *E,
4013                                         bool SkipLocalVariables = false);
4014
4015   /// \brief Try to recover by turning the given expression into a
4016   /// call.  Returns true if recovery was attempted or an error was
4017   /// emitted; this may also leave the ExprResult invalid.
4018   bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
4019                             bool ForceComplain = false,
4020                             bool (*IsPlausibleResult)(QualType) = nullptr);
4021
4022   /// \brief Figure out if an expression could be turned into a call.
4023   bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
4024                      UnresolvedSetImpl &NonTemplateOverloads);
4025
4026   /// \brief Conditionally issue a diagnostic based on the current
4027   /// evaluation context.
4028   ///
4029   /// \param Statement If Statement is non-null, delay reporting the
4030   /// diagnostic until the function body is parsed, and then do a basic
4031   /// reachability analysis to determine if the statement is reachable.
4032   /// If it is unreachable, the diagnostic will not be emitted.
4033   bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
4034                            const PartialDiagnostic &PD);
4035
4036   // Primary Expressions.
4037   SourceRange getExprRange(Expr *E) const;
4038
4039   ExprResult ActOnIdExpression(
4040       Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4041       UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
4042       std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
4043       bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
4044
4045   void DecomposeUnqualifiedId(const UnqualifiedId &Id,
4046                               TemplateArgumentListInfo &Buffer,
4047                               DeclarationNameInfo &NameInfo,
4048                               const TemplateArgumentListInfo *&TemplateArgs);
4049
4050   bool
4051   DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
4052                       std::unique_ptr<CorrectionCandidateCallback> CCC,
4053                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
4054                       ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
4055
4056   ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
4057                                 IdentifierInfo *II,
4058                                 bool AllowBuiltinCreation=false);
4059
4060   ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
4061                                         SourceLocation TemplateKWLoc,
4062                                         const DeclarationNameInfo &NameInfo,
4063                                         bool isAddressOfOperand,
4064                                 const TemplateArgumentListInfo *TemplateArgs);
4065
4066   ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
4067                               ExprValueKind VK,
4068                               SourceLocation Loc,
4069                               const CXXScopeSpec *SS = nullptr);
4070   ExprResult
4071   BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
4072                    const DeclarationNameInfo &NameInfo,
4073                    const CXXScopeSpec *SS = nullptr,
4074                    NamedDecl *FoundD = nullptr,
4075                    const TemplateArgumentListInfo *TemplateArgs = nullptr);
4076   ExprResult
4077   BuildAnonymousStructUnionMemberReference(
4078       const CXXScopeSpec &SS,
4079       SourceLocation nameLoc,
4080       IndirectFieldDecl *indirectField,
4081       DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
4082       Expr *baseObjectExpr = nullptr,
4083       SourceLocation opLoc = SourceLocation());
4084
4085   ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
4086                                              SourceLocation TemplateKWLoc,
4087                                              LookupResult &R,
4088                                 const TemplateArgumentListInfo *TemplateArgs,
4089                                              const Scope *S);
4090   ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
4091                                      SourceLocation TemplateKWLoc,
4092                                      LookupResult &R,
4093                                 const TemplateArgumentListInfo *TemplateArgs,
4094                                      bool IsDefiniteInstance,
4095                                      const Scope *S);
4096   bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
4097                                   const LookupResult &R,
4098                                   bool HasTrailingLParen);
4099
4100   ExprResult
4101   BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
4102                                     const DeclarationNameInfo &NameInfo,
4103                                     bool IsAddressOfOperand, const Scope *S,
4104                                     TypeSourceInfo **RecoveryTSI = nullptr);
4105
4106   ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
4107                                        SourceLocation TemplateKWLoc,
4108                                 const DeclarationNameInfo &NameInfo,
4109                                 const TemplateArgumentListInfo *TemplateArgs);
4110
4111   ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
4112                                       LookupResult &R,
4113                                       bool NeedsADL,
4114                                       bool AcceptInvalidDecl = false);
4115   ExprResult BuildDeclarationNameExpr(
4116       const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
4117       NamedDecl *FoundD = nullptr,
4118       const TemplateArgumentListInfo *TemplateArgs = nullptr,
4119       bool AcceptInvalidDecl = false);
4120
4121   ExprResult BuildLiteralOperatorCall(LookupResult &R,
4122                       DeclarationNameInfo &SuffixInfo,
4123                       ArrayRef<Expr *> Args,
4124                       SourceLocation LitEndLoc,
4125                       TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
4126
4127   ExprResult BuildPredefinedExpr(SourceLocation Loc,
4128                                  PredefinedExpr::IdentType IT);
4129   ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
4130   ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
4131
4132   bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
4133
4134   ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
4135   ExprResult ActOnCharacterConstant(const Token &Tok,
4136                                     Scope *UDLScope = nullptr);
4137   ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
4138   ExprResult ActOnParenListExpr(SourceLocation L,
4139                                 SourceLocation R,
4140                                 MultiExprArg Val);
4141
4142   /// ActOnStringLiteral - The specified tokens were lexed as pasted string
4143   /// fragments (e.g. "foo" "bar" L"baz").
4144   ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
4145                                 Scope *UDLScope = nullptr);
4146
4147   ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
4148                                        SourceLocation DefaultLoc,
4149                                        SourceLocation RParenLoc,
4150                                        Expr *ControllingExpr,
4151                                        ArrayRef<ParsedType> ArgTypes,
4152                                        ArrayRef<Expr *> ArgExprs);
4153   ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
4154                                         SourceLocation DefaultLoc,
4155                                         SourceLocation RParenLoc,
4156                                         Expr *ControllingExpr,
4157                                         ArrayRef<TypeSourceInfo *> Types,
4158                                         ArrayRef<Expr *> Exprs);
4159
4160   // Binary/Unary Operators.  'Tok' is the token for the operator.
4161   ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
4162                                   Expr *InputExpr);
4163   ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
4164                           UnaryOperatorKind Opc, Expr *Input);
4165   ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4166                           tok::TokenKind Op, Expr *Input);
4167
4168   QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
4169
4170   ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4171                                             SourceLocation OpLoc,
4172                                             UnaryExprOrTypeTrait ExprKind,
4173                                             SourceRange R);
4174   ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4175                                             UnaryExprOrTypeTrait ExprKind);
4176   ExprResult
4177     ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4178                                   UnaryExprOrTypeTrait ExprKind,
4179                                   bool IsType, void *TyOrEx,
4180                                   SourceRange ArgRange);
4181
4182   ExprResult CheckPlaceholderExpr(Expr *E);
4183   bool CheckVecStepExpr(Expr *E);
4184
4185   bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
4186   bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
4187                                         SourceRange ExprRange,
4188                                         UnaryExprOrTypeTrait ExprKind);
4189   ExprResult ActOnSizeofParameterPackExpr(Scope *S,
4190                                           SourceLocation OpLoc,
4191                                           IdentifierInfo &Name,
4192                                           SourceLocation NameLoc,
4193                                           SourceLocation RParenLoc);
4194   ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4195                                  tok::TokenKind Kind, Expr *Input);
4196
4197   ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
4198                                      Expr *Idx, SourceLocation RLoc);
4199   ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4200                                              Expr *Idx, SourceLocation RLoc);
4201   ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4202                                       Expr *LowerBound, SourceLocation ColonLoc,
4203                                       Expr *Length, SourceLocation RBLoc);
4204
4205   // This struct is for use by ActOnMemberAccess to allow
4206   // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
4207   // changing the access operator from a '.' to a '->' (to see if that is the
4208   // change needed to fix an error about an unknown member, e.g. when the class
4209   // defines a custom operator->).
4210   struct ActOnMemberAccessExtraArgs {
4211     Scope *S;
4212     UnqualifiedId &Id;
4213     Decl *ObjCImpDecl;
4214   };
4215
4216   ExprResult BuildMemberReferenceExpr(
4217       Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
4218       CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4219       NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
4220       const TemplateArgumentListInfo *TemplateArgs,
4221       const Scope *S,
4222       ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4223
4224   ExprResult
4225   BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
4226                            bool IsArrow, const CXXScopeSpec &SS,
4227                            SourceLocation TemplateKWLoc,
4228                            NamedDecl *FirstQualifierInScope, LookupResult &R,
4229                            const TemplateArgumentListInfo *TemplateArgs,
4230                            const Scope *S,
4231                            bool SuppressQualifierCheck = false,
4232                            ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
4233
4234   ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
4235                                      SourceLocation OpLoc,
4236                                      const CXXScopeSpec &SS, FieldDecl *Field,
4237                                      DeclAccessPair FoundDecl,
4238                                      const DeclarationNameInfo &MemberNameInfo);
4239
4240   ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
4241
4242   bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
4243                                      const CXXScopeSpec &SS,
4244                                      const LookupResult &R);
4245
4246   ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
4247                                       bool IsArrow, SourceLocation OpLoc,
4248                                       const CXXScopeSpec &SS,
4249                                       SourceLocation TemplateKWLoc,
4250                                       NamedDecl *FirstQualifierInScope,
4251                                const DeclarationNameInfo &NameInfo,
4252                                const TemplateArgumentListInfo *TemplateArgs);
4253
4254   ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
4255                                    SourceLocation OpLoc,
4256                                    tok::TokenKind OpKind,
4257                                    CXXScopeSpec &SS,
4258                                    SourceLocation TemplateKWLoc,
4259                                    UnqualifiedId &Member,
4260                                    Decl *ObjCImpDecl);
4261
4262   void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
4263   bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4264                                FunctionDecl *FDecl,
4265                                const FunctionProtoType *Proto,
4266                                ArrayRef<Expr *> Args,
4267                                SourceLocation RParenLoc,
4268                                bool ExecConfig = false);
4269   void CheckStaticArrayArgument(SourceLocation CallLoc,
4270                                 ParmVarDecl *Param,
4271                                 const Expr *ArgExpr);
4272
4273   /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4274   /// This provides the location of the left/right parens and a list of comma
4275   /// locations.
4276   ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4277                            MultiExprArg ArgExprs, SourceLocation RParenLoc,
4278                            Expr *ExecConfig = nullptr,
4279                            bool IsExecConfig = false);
4280   ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4281                                    SourceLocation LParenLoc,
4282                                    ArrayRef<Expr *> Arg,
4283                                    SourceLocation RParenLoc,
4284                                    Expr *Config = nullptr,
4285                                    bool IsExecConfig = false);
4286
4287   ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4288                                      MultiExprArg ExecConfig,
4289                                      SourceLocation GGGLoc);
4290
4291   ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4292                            Declarator &D, ParsedType &Ty,
4293                            SourceLocation RParenLoc, Expr *CastExpr);
4294   ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
4295                                  TypeSourceInfo *Ty,
4296                                  SourceLocation RParenLoc,
4297                                  Expr *Op);
4298   CastKind PrepareScalarCast(ExprResult &src, QualType destType);
4299
4300   /// \brief Build an altivec or OpenCL literal.
4301   ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
4302                                 SourceLocation RParenLoc, Expr *E,
4303                                 TypeSourceInfo *TInfo);
4304
4305   ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
4306
4307   ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
4308                                   ParsedType Ty,
4309                                   SourceLocation RParenLoc,
4310                                   Expr *InitExpr);
4311
4312   ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
4313                                       TypeSourceInfo *TInfo,
4314                                       SourceLocation RParenLoc,
4315                                       Expr *LiteralExpr);
4316
4317   ExprResult ActOnInitList(SourceLocation LBraceLoc,
4318                            MultiExprArg InitArgList,
4319                            SourceLocation RBraceLoc);
4320
4321   ExprResult ActOnDesignatedInitializer(Designation &Desig,
4322                                         SourceLocation Loc,
4323                                         bool GNUSyntax,
4324                                         ExprResult Init);
4325
4326 private:
4327   static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
4328
4329 public:
4330   ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
4331                         tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
4332   ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
4333                         BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
4334   ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
4335                                 Expr *LHSExpr, Expr *RHSExpr);
4336
4337   void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
4338
4339   /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
4340   /// in the case of a the GNU conditional expr extension.
4341   ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
4342                                 SourceLocation ColonLoc,
4343                                 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
4344
4345   /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4346   ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
4347                             LabelDecl *TheDecl);
4348
4349   void ActOnStartStmtExpr();
4350   ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
4351                            SourceLocation RPLoc); // "({..})"
4352   void ActOnStmtExprError();
4353
4354   // __builtin_offsetof(type, identifier(.identifier|[expr])*)
4355   struct OffsetOfComponent {
4356     SourceLocation LocStart, LocEnd;
4357     bool isBrackets;  // true if [expr], false if .ident
4358     union {
4359       IdentifierInfo *IdentInfo;
4360       Expr *E;
4361     } U;
4362   };
4363
4364   /// __builtin_offsetof(type, a.b[123][456].c)
4365   ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
4366                                   TypeSourceInfo *TInfo,
4367                                   ArrayRef<OffsetOfComponent> Components,
4368                                   SourceLocation RParenLoc);
4369   ExprResult ActOnBuiltinOffsetOf(Scope *S,
4370                                   SourceLocation BuiltinLoc,
4371                                   SourceLocation TypeLoc,
4372                                   ParsedType ParsedArgTy,
4373                                   ArrayRef<OffsetOfComponent> Components,
4374                                   SourceLocation RParenLoc);
4375
4376   // __builtin_choose_expr(constExpr, expr1, expr2)
4377   ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
4378                              Expr *CondExpr, Expr *LHSExpr,
4379                              Expr *RHSExpr, SourceLocation RPLoc);
4380
4381   // __builtin_va_arg(expr, type)
4382   ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
4383                         SourceLocation RPLoc);
4384   ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
4385                             TypeSourceInfo *TInfo, SourceLocation RPLoc);
4386
4387   // __null
4388   ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
4389
4390   bool CheckCaseExpression(Expr *E);
4391
4392   /// \brief Describes the result of an "if-exists" condition check.
4393   enum IfExistsResult {
4394     /// \brief The symbol exists.
4395     IER_Exists,
4396
4397     /// \brief The symbol does not exist.
4398     IER_DoesNotExist,
4399
4400     /// \brief The name is a dependent name, so the results will differ
4401     /// from one instantiation to the next.
4402     IER_Dependent,
4403
4404     /// \brief An error occurred.
4405     IER_Error
4406   };
4407
4408   IfExistsResult
4409   CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
4410                                const DeclarationNameInfo &TargetNameInfo);
4411
4412   IfExistsResult
4413   CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
4414                                bool IsIfExists, CXXScopeSpec &SS,
4415                                UnqualifiedId &Name);
4416
4417   StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4418                                         bool IsIfExists,
4419                                         NestedNameSpecifierLoc QualifierLoc,
4420                                         DeclarationNameInfo NameInfo,
4421                                         Stmt *Nested);
4422   StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4423                                         bool IsIfExists,
4424                                         CXXScopeSpec &SS, UnqualifiedId &Name,
4425                                         Stmt *Nested);
4426
4427   //===------------------------- "Block" Extension ------------------------===//
4428
4429   /// ActOnBlockStart - This callback is invoked when a block literal is
4430   /// started.
4431   void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
4432
4433   /// ActOnBlockArguments - This callback allows processing of block arguments.
4434   /// If there are no arguments, this is still invoked.
4435   void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
4436                            Scope *CurScope);
4437
4438   /// ActOnBlockError - If there is an error parsing a block, this callback
4439   /// is invoked to pop the information about the block from the action impl.
4440   void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
4441
4442   /// ActOnBlockStmtExpr - This is called when the body of a block statement
4443   /// literal was successfully completed.  ^(int x){...}
4444   ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
4445                                 Scope *CurScope);
4446
4447   //===---------------------------- Clang Extensions ----------------------===//
4448
4449   /// __builtin_convertvector(...)
4450   ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4451                                     SourceLocation BuiltinLoc,
4452                                     SourceLocation RParenLoc);
4453
4454   //===---------------------------- OpenCL Features -----------------------===//
4455
4456   /// __builtin_astype(...)
4457   ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4458                              SourceLocation BuiltinLoc,
4459                              SourceLocation RParenLoc);
4460
4461   //===---------------------------- C++ Features --------------------------===//
4462
4463   // Act on C++ namespaces
4464   Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
4465                                SourceLocation NamespaceLoc,
4466                                SourceLocation IdentLoc,
4467                                IdentifierInfo *Ident,
4468                                SourceLocation LBrace,
4469                                AttributeList *AttrList,
4470                                UsingDirectiveDecl * &UsingDecl);
4471   void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
4472
4473   NamespaceDecl *getStdNamespace() const;
4474   NamespaceDecl *getOrCreateStdNamespace();
4475
4476   NamespaceDecl *lookupStdExperimentalNamespace();
4477
4478   CXXRecordDecl *getStdBadAlloc() const;
4479   EnumDecl *getStdAlignValT() const;
4480
4481   /// \brief Tests whether Ty is an instance of std::initializer_list and, if
4482   /// it is and Element is not NULL, assigns the element type to Element.
4483   bool isStdInitializerList(QualType Ty, QualType *Element);
4484
4485   /// \brief Looks for the std::initializer_list template and instantiates it
4486   /// with Element, or emits an error if it's not found.
4487   ///
4488   /// \returns The instantiated template, or null on error.
4489   QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
4490
4491   /// \brief Determine whether Ctor is an initializer-list constructor, as
4492   /// defined in [dcl.init.list]p2.
4493   bool isInitListConstructor(const FunctionDecl *Ctor);
4494
4495   Decl *ActOnUsingDirective(Scope *CurScope,
4496                             SourceLocation UsingLoc,
4497                             SourceLocation NamespcLoc,
4498                             CXXScopeSpec &SS,
4499                             SourceLocation IdentLoc,
4500                             IdentifierInfo *NamespcName,
4501                             AttributeList *AttrList);
4502
4503   void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
4504
4505   Decl *ActOnNamespaceAliasDef(Scope *CurScope,
4506                                SourceLocation NamespaceLoc,
4507                                SourceLocation AliasLoc,
4508                                IdentifierInfo *Alias,
4509                                CXXScopeSpec &SS,
4510                                SourceLocation IdentLoc,
4511                                IdentifierInfo *Ident);
4512
4513   void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
4514   bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
4515                             const LookupResult &PreviousDecls,
4516                             UsingShadowDecl *&PrevShadow);
4517   UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
4518                                         NamedDecl *Target,
4519                                         UsingShadowDecl *PrevDecl);
4520
4521   bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4522                                    bool HasTypenameKeyword,
4523                                    const CXXScopeSpec &SS,
4524                                    SourceLocation NameLoc,
4525                                    const LookupResult &Previous);
4526   bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
4527                                bool HasTypename,
4528                                const CXXScopeSpec &SS,
4529                                const DeclarationNameInfo &NameInfo,
4530                                SourceLocation NameLoc);
4531
4532   NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4533                                    SourceLocation UsingLoc,
4534                                    bool HasTypenameKeyword,
4535                                    SourceLocation TypenameLoc,
4536                                    CXXScopeSpec &SS,
4537                                    DeclarationNameInfo NameInfo,
4538                                    SourceLocation EllipsisLoc,
4539                                    AttributeList *AttrList,
4540                                    bool IsInstantiation);
4541   NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
4542                                 ArrayRef<NamedDecl *> Expansions);
4543
4544   bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
4545
4546   /// Given a derived-class using shadow declaration for a constructor and the
4547   /// correspnding base class constructor, find or create the implicit
4548   /// synthesized derived class constructor to use for this initialization.
4549   CXXConstructorDecl *
4550   findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
4551                             ConstructorUsingShadowDecl *DerivedShadow);
4552
4553   Decl *ActOnUsingDeclaration(Scope *CurScope,
4554                               AccessSpecifier AS,
4555                               SourceLocation UsingLoc,
4556                               SourceLocation TypenameLoc,
4557                               CXXScopeSpec &SS,
4558                               UnqualifiedId &Name,
4559                               SourceLocation EllipsisLoc,
4560                               AttributeList *AttrList);
4561   Decl *ActOnAliasDeclaration(Scope *CurScope,
4562                               AccessSpecifier AS,
4563                               MultiTemplateParamsArg TemplateParams,
4564                               SourceLocation UsingLoc,
4565                               UnqualifiedId &Name,
4566                               AttributeList *AttrList,
4567                               TypeResult Type,
4568                               Decl *DeclFromDeclSpec);
4569
4570   /// BuildCXXConstructExpr - Creates a complete call to a constructor,
4571   /// including handling of its default argument expressions.
4572   ///
4573   /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
4574   ExprResult
4575   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4576                         NamedDecl *FoundDecl,
4577                         CXXConstructorDecl *Constructor, MultiExprArg Exprs,
4578                         bool HadMultipleCandidates, bool IsListInitialization,
4579                         bool IsStdInitListInitialization,
4580                         bool RequiresZeroInit, unsigned ConstructKind,
4581                         SourceRange ParenRange);
4582
4583   /// Build a CXXConstructExpr whose constructor has already been resolved if
4584   /// it denotes an inherited constructor.
4585   ExprResult
4586   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4587                         CXXConstructorDecl *Constructor, bool Elidable,
4588                         MultiExprArg Exprs,
4589                         bool HadMultipleCandidates, bool IsListInitialization,
4590                         bool IsStdInitListInitialization,
4591                         bool RequiresZeroInit, unsigned ConstructKind,
4592                         SourceRange ParenRange);
4593
4594   // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
4595   // the constructor can be elidable?
4596   ExprResult
4597   BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4598                         NamedDecl *FoundDecl,
4599                         CXXConstructorDecl *Constructor, bool Elidable,
4600                         MultiExprArg Exprs, bool HadMultipleCandidates,
4601                         bool IsListInitialization,
4602                         bool IsStdInitListInitialization, bool RequiresZeroInit,
4603                         unsigned ConstructKind, SourceRange ParenRange);
4604
4605   ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
4606
4607
4608   /// Instantiate or parse a C++ default argument expression as necessary.
4609   /// Return true on error.
4610   bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4611                               ParmVarDecl *Param);
4612
4613   /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
4614   /// the default expr if needed.
4615   ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4616                                     FunctionDecl *FD,
4617                                     ParmVarDecl *Param);
4618
4619   /// FinalizeVarWithDestructor - Prepare for calling destructor on the
4620   /// constructed variable.
4621   void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
4622
4623   /// \brief Helper class that collects exception specifications for
4624   /// implicitly-declared special member functions.
4625   class ImplicitExceptionSpecification {
4626     // Pointer to allow copying
4627     Sema *Self;
4628     // We order exception specifications thus:
4629     // noexcept is the most restrictive, but is only used in C++11.
4630     // throw() comes next.
4631     // Then a throw(collected exceptions)
4632     // Finally no specification, which is expressed as noexcept(false).
4633     // throw(...) is used instead if any called function uses it.
4634     ExceptionSpecificationType ComputedEST;
4635     llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
4636     SmallVector<QualType, 4> Exceptions;
4637
4638     void ClearExceptions() {
4639       ExceptionsSeen.clear();
4640       Exceptions.clear();
4641     }
4642
4643   public:
4644     explicit ImplicitExceptionSpecification(Sema &Self)
4645       : Self(&Self), ComputedEST(EST_BasicNoexcept) {
4646       if (!Self.getLangOpts().CPlusPlus11)
4647         ComputedEST = EST_DynamicNone;
4648     }
4649
4650     /// \brief Get the computed exception specification type.
4651     ExceptionSpecificationType getExceptionSpecType() const {
4652       assert(ComputedEST != EST_ComputedNoexcept &&
4653              "noexcept(expr) should not be a possible result");
4654       return ComputedEST;
4655     }
4656
4657     /// \brief The number of exceptions in the exception specification.
4658     unsigned size() const { return Exceptions.size(); }
4659
4660     /// \brief The set of exceptions in the exception specification.
4661     const QualType *data() const { return Exceptions.data(); }
4662
4663     /// \brief Integrate another called method into the collected data.
4664     void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
4665
4666     /// \brief Integrate an invoked expression into the collected data.
4667     void CalledExpr(Expr *E);
4668
4669     /// \brief Overwrite an EPI's exception specification with this
4670     /// computed exception specification.
4671     FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
4672       FunctionProtoType::ExceptionSpecInfo ESI;
4673       ESI.Type = getExceptionSpecType();
4674       if (ESI.Type == EST_Dynamic) {
4675         ESI.Exceptions = Exceptions;
4676       } else if (ESI.Type == EST_None) {
4677         /// C++11 [except.spec]p14:
4678         ///   The exception-specification is noexcept(false) if the set of
4679         ///   potential exceptions of the special member function contains "any"
4680         ESI.Type = EST_ComputedNoexcept;
4681         ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
4682                                                      tok::kw_false).get();
4683       }
4684       return ESI;
4685     }
4686   };
4687
4688   /// \brief Determine what sort of exception specification a defaulted
4689   /// copy constructor of a class will have.
4690   ImplicitExceptionSpecification
4691   ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
4692                                            CXXMethodDecl *MD);
4693
4694   /// \brief Determine what sort of exception specification a defaulted
4695   /// default constructor of a class will have, and whether the parameter
4696   /// will be const.
4697   ImplicitExceptionSpecification
4698   ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
4699
4700   /// \brief Determine what sort of exception specification a defautled
4701   /// copy assignment operator of a class will have, and whether the
4702   /// parameter will be const.
4703   ImplicitExceptionSpecification
4704   ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
4705
4706   /// \brief Determine what sort of exception specification a defaulted move
4707   /// constructor of a class will have.
4708   ImplicitExceptionSpecification
4709   ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
4710
4711   /// \brief Determine what sort of exception specification a defaulted move
4712   /// assignment operator of a class will have.
4713   ImplicitExceptionSpecification
4714   ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
4715
4716   /// \brief Determine what sort of exception specification a defaulted
4717   /// destructor of a class will have.
4718   ImplicitExceptionSpecification
4719   ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
4720
4721   /// \brief Determine what sort of exception specification an inheriting
4722   /// constructor of a class will have.
4723   ImplicitExceptionSpecification
4724   ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
4725                                      CXXConstructorDecl *CD);
4726
4727   /// \brief Evaluate the implicit exception specification for a defaulted
4728   /// special member function.
4729   void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
4730
4731   /// \brief Check the given exception-specification and update the
4732   /// exception specification information with the results.
4733   void checkExceptionSpecification(bool IsTopLevel,
4734                                    ExceptionSpecificationType EST,
4735                                    ArrayRef<ParsedType> DynamicExceptions,
4736                                    ArrayRef<SourceRange> DynamicExceptionRanges,
4737                                    Expr *NoexceptExpr,
4738                                    SmallVectorImpl<QualType> &Exceptions,
4739                                    FunctionProtoType::ExceptionSpecInfo &ESI);
4740
4741   /// \brief Determine if we're in a case where we need to (incorrectly) eagerly
4742   /// parse an exception specification to work around a libstdc++ bug.
4743   bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
4744
4745   /// \brief Add an exception-specification to the given member function
4746   /// (or member function template). The exception-specification was parsed
4747   /// after the method itself was declared.
4748   void actOnDelayedExceptionSpecification(Decl *Method,
4749          ExceptionSpecificationType EST,
4750          SourceRange SpecificationRange,
4751          ArrayRef<ParsedType> DynamicExceptions,
4752          ArrayRef<SourceRange> DynamicExceptionRanges,
4753          Expr *NoexceptExpr);
4754
4755   class InheritedConstructorInfo;
4756
4757   /// \brief Determine if a special member function should have a deleted
4758   /// definition when it is defaulted.
4759   bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4760                                  InheritedConstructorInfo *ICI = nullptr,
4761                                  bool Diagnose = false);
4762
4763   /// \brief Declare the implicit default constructor for the given class.
4764   ///
4765   /// \param ClassDecl The class declaration into which the implicit
4766   /// default constructor will be added.
4767   ///
4768   /// \returns The implicitly-declared default constructor.
4769   CXXConstructorDecl *DeclareImplicitDefaultConstructor(
4770                                                      CXXRecordDecl *ClassDecl);
4771
4772   /// DefineImplicitDefaultConstructor - Checks for feasibility of
4773   /// defining this constructor as the default constructor.
4774   void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4775                                         CXXConstructorDecl *Constructor);
4776
4777   /// \brief Declare the implicit destructor for the given class.
4778   ///
4779   /// \param ClassDecl The class declaration into which the implicit
4780   /// destructor will be added.
4781   ///
4782   /// \returns The implicitly-declared destructor.
4783   CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
4784
4785   /// DefineImplicitDestructor - Checks for feasibility of
4786   /// defining this destructor as the default destructor.
4787   void DefineImplicitDestructor(SourceLocation CurrentLocation,
4788                                 CXXDestructorDecl *Destructor);
4789
4790   /// \brief Build an exception spec for destructors that don't have one.
4791   ///
4792   /// C++11 says that user-defined destructors with no exception spec get one
4793   /// that looks as if the destructor was implicitly declared.
4794   void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
4795                                      CXXDestructorDecl *Destructor);
4796
4797   /// \brief Define the specified inheriting constructor.
4798   void DefineInheritingConstructor(SourceLocation UseLoc,
4799                                    CXXConstructorDecl *Constructor);
4800
4801   /// \brief Declare the implicit copy constructor for the given class.
4802   ///
4803   /// \param ClassDecl The class declaration into which the implicit
4804   /// copy constructor will be added.
4805   ///
4806   /// \returns The implicitly-declared copy constructor.
4807   CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
4808
4809   /// DefineImplicitCopyConstructor - Checks for feasibility of
4810   /// defining this constructor as the copy constructor.
4811   void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4812                                      CXXConstructorDecl *Constructor);
4813
4814   /// \brief Declare the implicit move constructor for the given class.
4815   ///
4816   /// \param ClassDecl The Class declaration into which the implicit
4817   /// move constructor will be added.
4818   ///
4819   /// \returns The implicitly-declared move constructor, or NULL if it wasn't
4820   /// declared.
4821   CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
4822
4823   /// DefineImplicitMoveConstructor - Checks for feasibility of
4824   /// defining this constructor as the move constructor.
4825   void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
4826                                      CXXConstructorDecl *Constructor);
4827
4828   /// \brief Declare the implicit copy assignment operator for the given class.
4829   ///
4830   /// \param ClassDecl The class declaration into which the implicit
4831   /// copy assignment operator will be added.
4832   ///
4833   /// \returns The implicitly-declared copy assignment operator.
4834   CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
4835
4836   /// \brief Defines an implicitly-declared copy assignment operator.
4837   void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4838                                     CXXMethodDecl *MethodDecl);
4839
4840   /// \brief Declare the implicit move assignment operator for the given class.
4841   ///
4842   /// \param ClassDecl The Class declaration into which the implicit
4843   /// move assignment operator will be added.
4844   ///
4845   /// \returns The implicitly-declared move assignment operator, or NULL if it
4846   /// wasn't declared.
4847   CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
4848
4849   /// \brief Defines an implicitly-declared move assignment operator.
4850   void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
4851                                     CXXMethodDecl *MethodDecl);
4852
4853   /// \brief Force the declaration of any implicitly-declared members of this
4854   /// class.
4855   void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
4856
4857   /// \brief Check a completed declaration of an implicit special member.
4858   void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
4859
4860   /// \brief Determine whether the given function is an implicitly-deleted
4861   /// special member function.
4862   bool isImplicitlyDeleted(FunctionDecl *FD);
4863
4864   /// \brief Check whether 'this' shows up in the type of a static member
4865   /// function after the (naturally empty) cv-qualifier-seq would be.
4866   ///
4867   /// \returns true if an error occurred.
4868   bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
4869
4870   /// \brief Whether this' shows up in the exception specification of a static
4871   /// member function.
4872   bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
4873
4874   /// \brief Check whether 'this' shows up in the attributes of the given
4875   /// static member function.
4876   ///
4877   /// \returns true if an error occurred.
4878   bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
4879
4880   /// MaybeBindToTemporary - If the passed in expression has a record type with
4881   /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
4882   /// it simply returns the passed in expression.
4883   ExprResult MaybeBindToTemporary(Expr *E);
4884
4885   bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
4886                                MultiExprArg ArgsPtr,
4887                                SourceLocation Loc,
4888                                SmallVectorImpl<Expr*> &ConvertedArgs,
4889                                bool AllowExplicit = false,
4890                                bool IsListInitialization = false);
4891
4892   ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
4893                                           SourceLocation NameLoc,
4894                                           IdentifierInfo &Name);
4895
4896   ParsedType getDestructorName(SourceLocation TildeLoc,
4897                                IdentifierInfo &II, SourceLocation NameLoc,
4898                                Scope *S, CXXScopeSpec &SS,
4899                                ParsedType ObjectType,
4900                                bool EnteringContext);
4901
4902   ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
4903                                           ParsedType ObjectType);
4904
4905   // Checks that reinterpret casts don't have undefined behavior.
4906   void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
4907                                       bool IsDereference, SourceRange Range);
4908
4909   /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
4910   ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
4911                                tok::TokenKind Kind,
4912                                SourceLocation LAngleBracketLoc,
4913                                Declarator &D,
4914                                SourceLocation RAngleBracketLoc,
4915                                SourceLocation LParenLoc,
4916                                Expr *E,
4917                                SourceLocation RParenLoc);
4918
4919   ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
4920                                tok::TokenKind Kind,
4921                                TypeSourceInfo *Ty,
4922                                Expr *E,
4923                                SourceRange AngleBrackets,
4924                                SourceRange Parens);
4925
4926   ExprResult BuildCXXTypeId(QualType TypeInfoType,
4927                             SourceLocation TypeidLoc,
4928                             TypeSourceInfo *Operand,
4929                             SourceLocation RParenLoc);
4930   ExprResult BuildCXXTypeId(QualType TypeInfoType,
4931                             SourceLocation TypeidLoc,
4932                             Expr *Operand,
4933                             SourceLocation RParenLoc);
4934
4935   /// ActOnCXXTypeid - Parse typeid( something ).
4936   ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
4937                             SourceLocation LParenLoc, bool isType,
4938                             void *TyOrExpr,
4939                             SourceLocation RParenLoc);
4940
4941   ExprResult BuildCXXUuidof(QualType TypeInfoType,
4942                             SourceLocation TypeidLoc,
4943                             TypeSourceInfo *Operand,
4944                             SourceLocation RParenLoc);
4945   ExprResult BuildCXXUuidof(QualType TypeInfoType,
4946                             SourceLocation TypeidLoc,
4947                             Expr *Operand,
4948                             SourceLocation RParenLoc);
4949
4950   /// ActOnCXXUuidof - Parse __uuidof( something ).
4951   ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
4952                             SourceLocation LParenLoc, bool isType,
4953                             void *TyOrExpr,
4954                             SourceLocation RParenLoc);
4955
4956   /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
4957   ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4958                               tok::TokenKind Operator,
4959                               SourceLocation EllipsisLoc, Expr *RHS,
4960                               SourceLocation RParenLoc);
4961   ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
4962                               BinaryOperatorKind Operator,
4963                               SourceLocation EllipsisLoc, Expr *RHS,
4964                               SourceLocation RParenLoc);
4965   ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
4966                                    BinaryOperatorKind Operator);
4967
4968   //// ActOnCXXThis -  Parse 'this' pointer.
4969   ExprResult ActOnCXXThis(SourceLocation loc);
4970
4971   /// \brief Try to retrieve the type of the 'this' pointer.
4972   ///
4973   /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
4974   QualType getCurrentThisType();
4975
4976   /// \brief When non-NULL, the C++ 'this' expression is allowed despite the
4977   /// current context not being a non-static member function. In such cases,
4978   /// this provides the type used for 'this'.
4979   QualType CXXThisTypeOverride;
4980
4981   /// \brief RAII object used to temporarily allow the C++ 'this' expression
4982   /// to be used, with the given qualifiers on the current class type.
4983   class CXXThisScopeRAII {
4984     Sema &S;
4985     QualType OldCXXThisTypeOverride;
4986     bool Enabled;
4987
4988   public:
4989     /// \brief Introduce a new scope where 'this' may be allowed (when enabled),
4990     /// using the given declaration (which is either a class template or a
4991     /// class) along with the given qualifiers.
4992     /// along with the qualifiers placed on '*this'.
4993     CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
4994                      bool Enabled = true);
4995
4996     ~CXXThisScopeRAII();
4997   };
4998
4999   /// \brief Make sure the value of 'this' is actually available in the current
5000   /// context, if it is a potentially evaluated context.
5001   ///
5002   /// \param Loc The location at which the capture of 'this' occurs.
5003   ///
5004   /// \param Explicit Whether 'this' is explicitly captured in a lambda
5005   /// capture list.
5006   ///
5007   /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
5008   /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
5009   /// This is useful when enclosing lambdas must speculatively capture
5010   /// 'this' that may or may not be used in certain specializations of
5011   /// a nested generic lambda (depending on whether the name resolves to
5012   /// a non-static member function or a static function).
5013   /// \return returns 'true' if failed, 'false' if success.
5014   bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
5015       bool BuildAndDiagnose = true,
5016       const unsigned *const FunctionScopeIndexToStopAt = nullptr,
5017       bool ByCopy = false);
5018
5019   /// \brief Determine whether the given type is the type of *this that is used
5020   /// outside of the body of a member function for a type that is currently
5021   /// being defined.
5022   bool isThisOutsideMemberFunctionBody(QualType BaseType);
5023
5024   /// ActOnCXXBoolLiteral - Parse {true,false} literals.
5025   ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5026
5027
5028   /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
5029   ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
5030
5031   ExprResult
5032   ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
5033                                  SourceLocation AtLoc, SourceLocation RParen);
5034
5035   /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
5036   ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
5037
5038   //// ActOnCXXThrow -  Parse throw expressions.
5039   ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
5040   ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
5041                            bool IsThrownVarInScope);
5042   bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
5043
5044   /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
5045   /// Can be interpreted either as function-style casting ("int(x)")
5046   /// or class type construction ("ClassType(x,y,z)")
5047   /// or creation of a value-initialized type ("int()").
5048   ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
5049                                        SourceLocation LParenLoc,
5050                                        MultiExprArg Exprs,
5051                                        SourceLocation RParenLoc);
5052
5053   ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
5054                                        SourceLocation LParenLoc,
5055                                        MultiExprArg Exprs,
5056                                        SourceLocation RParenLoc);
5057
5058   /// ActOnCXXNew - Parsed a C++ 'new' expression.
5059   ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
5060                          SourceLocation PlacementLParen,
5061                          MultiExprArg PlacementArgs,
5062                          SourceLocation PlacementRParen,
5063                          SourceRange TypeIdParens, Declarator &D,
5064                          Expr *Initializer);
5065   ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
5066                          SourceLocation PlacementLParen,
5067                          MultiExprArg PlacementArgs,
5068                          SourceLocation PlacementRParen,
5069                          SourceRange TypeIdParens,
5070                          QualType AllocType,
5071                          TypeSourceInfo *AllocTypeInfo,
5072                          Expr *ArraySize,
5073                          SourceRange DirectInitRange,
5074                          Expr *Initializer);
5075
5076   bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
5077                           SourceRange R);
5078   bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
5079                                bool UseGlobal, QualType AllocType, bool IsArray,
5080                                bool &PassAlignment, MultiExprArg PlaceArgs,
5081                                FunctionDecl *&OperatorNew,
5082                                FunctionDecl *&OperatorDelete);
5083   void DeclareGlobalNewDelete();
5084   void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
5085                                        ArrayRef<QualType> Params);
5086
5087   bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
5088                                 DeclarationName Name, FunctionDecl* &Operator,
5089                                 bool Diagnose = true);
5090   FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
5091                                               bool CanProvideSize,
5092                                               bool Overaligned,
5093                                               DeclarationName Name);
5094   FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
5095                                                       CXXRecordDecl *RD);
5096
5097   /// ActOnCXXDelete - Parsed a C++ 'delete' expression
5098   ExprResult ActOnCXXDelete(SourceLocation StartLoc,
5099                             bool UseGlobal, bool ArrayForm,
5100                             Expr *Operand);
5101   void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
5102                             bool IsDelete, bool CallCanBeVirtual,
5103                             bool WarnOnNonAbstractTypes,
5104                             SourceLocation DtorLoc);
5105
5106   ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
5107                                Expr *Operand, SourceLocation RParen);
5108   ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5109                                   SourceLocation RParen);
5110
5111   /// \brief Parsed one of the type trait support pseudo-functions.
5112   ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5113                             ArrayRef<ParsedType> Args,
5114                             SourceLocation RParenLoc);
5115   ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5116                             ArrayRef<TypeSourceInfo *> Args,
5117                             SourceLocation RParenLoc);
5118
5119   /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
5120   /// pseudo-functions.
5121   ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5122                                  SourceLocation KWLoc,
5123                                  ParsedType LhsTy,
5124                                  Expr *DimExpr,
5125                                  SourceLocation RParen);
5126
5127   ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
5128                                  SourceLocation KWLoc,
5129                                  TypeSourceInfo *TSInfo,
5130                                  Expr *DimExpr,
5131                                  SourceLocation RParen);
5132
5133   /// ActOnExpressionTrait - Parsed one of the unary type trait support
5134   /// pseudo-functions.
5135   ExprResult ActOnExpressionTrait(ExpressionTrait OET,
5136                                   SourceLocation KWLoc,
5137                                   Expr *Queried,
5138                                   SourceLocation RParen);
5139
5140   ExprResult BuildExpressionTrait(ExpressionTrait OET,
5141                                   SourceLocation KWLoc,
5142                                   Expr *Queried,
5143                                   SourceLocation RParen);
5144
5145   ExprResult ActOnStartCXXMemberReference(Scope *S,
5146                                           Expr *Base,
5147                                           SourceLocation OpLoc,
5148                                           tok::TokenKind OpKind,
5149                                           ParsedType &ObjectType,
5150                                           bool &MayBePseudoDestructor);
5151
5152   ExprResult BuildPseudoDestructorExpr(Expr *Base,
5153                                        SourceLocation OpLoc,
5154                                        tok::TokenKind OpKind,
5155                                        const CXXScopeSpec &SS,
5156                                        TypeSourceInfo *ScopeType,
5157                                        SourceLocation CCLoc,
5158                                        SourceLocation TildeLoc,
5159                                      PseudoDestructorTypeStorage DestroyedType);
5160
5161   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5162                                        SourceLocation OpLoc,
5163                                        tok::TokenKind OpKind,
5164                                        CXXScopeSpec &SS,
5165                                        UnqualifiedId &FirstTypeName,
5166                                        SourceLocation CCLoc,
5167                                        SourceLocation TildeLoc,
5168                                        UnqualifiedId &SecondTypeName);
5169
5170   ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5171                                        SourceLocation OpLoc,
5172                                        tok::TokenKind OpKind,
5173                                        SourceLocation TildeLoc,
5174                                        const DeclSpec& DS);
5175
5176   /// MaybeCreateExprWithCleanups - If the current full-expression
5177   /// requires any cleanups, surround it with a ExprWithCleanups node.
5178   /// Otherwise, just returns the passed-in expression.
5179   Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
5180   Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
5181   ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
5182
5183   MaterializeTemporaryExpr *
5184   CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
5185                                  bool BoundToLvalueReference);
5186
5187   ExprResult ActOnFinishFullExpr(Expr *Expr) {
5188     return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
5189                                           : SourceLocation());
5190   }
5191   ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
5192                                  bool DiscardedValue = false,
5193                                  bool IsConstexpr = false,
5194                                  bool IsLambdaInitCaptureInitializer = false);
5195   StmtResult ActOnFinishFullStmt(Stmt *Stmt);
5196
5197   // Marks SS invalid if it represents an incomplete type.
5198   bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
5199
5200   DeclContext *computeDeclContext(QualType T);
5201   DeclContext *computeDeclContext(const CXXScopeSpec &SS,
5202                                   bool EnteringContext = false);
5203   bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
5204   CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
5205
5206   /// \brief The parser has parsed a global nested-name-specifier '::'.
5207   ///
5208   /// \param CCLoc The location of the '::'.
5209   ///
5210   /// \param SS The nested-name-specifier, which will be updated in-place
5211   /// to reflect the parsed nested-name-specifier.
5212   ///
5213   /// \returns true if an error occurred, false otherwise.
5214   bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
5215
5216   /// \brief The parser has parsed a '__super' nested-name-specifier.
5217   ///
5218   /// \param SuperLoc The location of the '__super' keyword.
5219   ///
5220   /// \param ColonColonLoc The location of the '::'.
5221   ///
5222   /// \param SS The nested-name-specifier, which will be updated in-place
5223   /// to reflect the parsed nested-name-specifier.
5224   ///
5225   /// \returns true if an error occurred, false otherwise.
5226   bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
5227                                 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
5228
5229   bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
5230                                        bool *CanCorrect = nullptr);
5231   NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
5232
5233   /// \brief Keeps information about an identifier in a nested-name-spec.
5234   ///
5235   struct NestedNameSpecInfo {
5236     /// \brief The type of the object, if we're parsing nested-name-specifier in
5237     /// a member access expression.
5238     ParsedType ObjectType;
5239
5240     /// \brief The identifier preceding the '::'.
5241     IdentifierInfo *Identifier;
5242
5243     /// \brief The location of the identifier.
5244     SourceLocation IdentifierLoc;
5245
5246     /// \brief The location of the '::'.
5247     SourceLocation CCLoc;
5248
5249     /// \brief Creates info object for the most typical case.
5250     NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5251              SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
5252       : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
5253         CCLoc(ColonColonLoc) {
5254     }
5255
5256     NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
5257                        SourceLocation ColonColonLoc, QualType ObjectType)
5258       : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
5259         IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
5260     }
5261   };
5262
5263   bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
5264                                     NestedNameSpecInfo &IdInfo);
5265
5266   bool BuildCXXNestedNameSpecifier(Scope *S,
5267                                    NestedNameSpecInfo &IdInfo,
5268                                    bool EnteringContext,
5269                                    CXXScopeSpec &SS,
5270                                    NamedDecl *ScopeLookupResult,
5271                                    bool ErrorRecoveryLookup,
5272                                    bool *IsCorrectedToColon = nullptr,
5273                                    bool OnlyNamespace = false);
5274
5275   /// \brief The parser has parsed a nested-name-specifier 'identifier::'.
5276   ///
5277   /// \param S The scope in which this nested-name-specifier occurs.
5278   ///
5279   /// \param IdInfo Parser information about an identifier in the
5280   /// nested-name-spec.
5281   ///
5282   /// \param EnteringContext Whether we're entering the context nominated by
5283   /// this nested-name-specifier.
5284   ///
5285   /// \param SS The nested-name-specifier, which is both an input
5286   /// parameter (the nested-name-specifier before this type) and an
5287   /// output parameter (containing the full nested-name-specifier,
5288   /// including this new type).
5289   ///
5290   /// \param ErrorRecoveryLookup If true, then this method is called to improve
5291   /// error recovery. In this case do not emit error message.
5292   ///
5293   /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
5294   /// are allowed.  The bool value pointed by this parameter is set to 'true'
5295   /// if the identifier is treated as if it was followed by ':', not '::'.
5296   ///
5297   /// \param OnlyNamespace If true, only considers namespaces in lookup.
5298   ///
5299   /// \returns true if an error occurred, false otherwise.
5300   bool ActOnCXXNestedNameSpecifier(Scope *S,
5301                                    NestedNameSpecInfo &IdInfo,
5302                                    bool EnteringContext,
5303                                    CXXScopeSpec &SS,
5304                                    bool ErrorRecoveryLookup = false,
5305                                    bool *IsCorrectedToColon = nullptr,
5306                                    bool OnlyNamespace = false);
5307
5308   ExprResult ActOnDecltypeExpression(Expr *E);
5309
5310   bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
5311                                            const DeclSpec &DS,
5312                                            SourceLocation ColonColonLoc);
5313
5314   bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
5315                                  NestedNameSpecInfo &IdInfo,
5316                                  bool EnteringContext);
5317
5318   /// \brief The parser has parsed a nested-name-specifier
5319   /// 'template[opt] template-name < template-args >::'.
5320   ///
5321   /// \param S The scope in which this nested-name-specifier occurs.
5322   ///
5323   /// \param SS The nested-name-specifier, which is both an input
5324   /// parameter (the nested-name-specifier before this type) and an
5325   /// output parameter (containing the full nested-name-specifier,
5326   /// including this new type).
5327   ///
5328   /// \param TemplateKWLoc the location of the 'template' keyword, if any.
5329   /// \param TemplateName the template name.
5330   /// \param TemplateNameLoc The location of the template name.
5331   /// \param LAngleLoc The location of the opening angle bracket  ('<').
5332   /// \param TemplateArgs The template arguments.
5333   /// \param RAngleLoc The location of the closing angle bracket  ('>').
5334   /// \param CCLoc The location of the '::'.
5335   ///
5336   /// \param EnteringContext Whether we're entering the context of the
5337   /// nested-name-specifier.
5338   ///
5339   ///
5340   /// \returns true if an error occurred, false otherwise.
5341   bool ActOnCXXNestedNameSpecifier(Scope *S,
5342                                    CXXScopeSpec &SS,
5343                                    SourceLocation TemplateKWLoc,
5344                                    TemplateTy TemplateName,
5345                                    SourceLocation TemplateNameLoc,
5346                                    SourceLocation LAngleLoc,
5347                                    ASTTemplateArgsPtr TemplateArgs,
5348                                    SourceLocation RAngleLoc,
5349                                    SourceLocation CCLoc,
5350                                    bool EnteringContext);
5351
5352   /// \brief Given a C++ nested-name-specifier, produce an annotation value
5353   /// that the parser can use later to reconstruct the given
5354   /// nested-name-specifier.
5355   ///
5356   /// \param SS A nested-name-specifier.
5357   ///
5358   /// \returns A pointer containing all of the information in the
5359   /// nested-name-specifier \p SS.
5360   void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
5361
5362   /// \brief Given an annotation pointer for a nested-name-specifier, restore
5363   /// the nested-name-specifier structure.
5364   ///
5365   /// \param Annotation The annotation pointer, produced by
5366   /// \c SaveNestedNameSpecifierAnnotation().
5367   ///
5368   /// \param AnnotationRange The source range corresponding to the annotation.
5369   ///
5370   /// \param SS The nested-name-specifier that will be updated with the contents
5371   /// of the annotation pointer.
5372   void RestoreNestedNameSpecifierAnnotation(void *Annotation,
5373                                             SourceRange AnnotationRange,
5374                                             CXXScopeSpec &SS);
5375
5376   bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5377
5378   /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
5379   /// scope or nested-name-specifier) is parsed, part of a declarator-id.
5380   /// After this method is called, according to [C++ 3.4.3p3], names should be
5381   /// looked up in the declarator-id's scope, until the declarator is parsed and
5382   /// ActOnCXXExitDeclaratorScope is called.
5383   /// The 'SS' should be a non-empty valid CXXScopeSpec.
5384   bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
5385
5386   /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
5387   /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
5388   /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
5389   /// Used to indicate that names should revert to being looked up in the
5390   /// defining scope.
5391   void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
5392
5393   /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
5394   /// initializer for the declaration 'Dcl'.
5395   /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5396   /// static data member of class X, names should be looked up in the scope of
5397   /// class X.
5398   void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
5399
5400   /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
5401   /// initializer for the declaration 'Dcl'.
5402   void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
5403
5404   /// \brief Create a new lambda closure type.
5405   CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
5406                                          TypeSourceInfo *Info,
5407                                          bool KnownDependent,
5408                                          LambdaCaptureDefault CaptureDefault);
5409
5410   /// \brief Start the definition of a lambda expression.
5411   CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
5412                                        SourceRange IntroducerRange,
5413                                        TypeSourceInfo *MethodType,
5414                                        SourceLocation EndLoc,
5415                                        ArrayRef<ParmVarDecl *> Params,
5416                                        bool IsConstexprSpecified);
5417
5418   /// \brief Endow the lambda scope info with the relevant properties.
5419   void buildLambdaScope(sema::LambdaScopeInfo *LSI,
5420                         CXXMethodDecl *CallOperator,
5421                         SourceRange IntroducerRange,
5422                         LambdaCaptureDefault CaptureDefault,
5423                         SourceLocation CaptureDefaultLoc,
5424                         bool ExplicitParams,
5425                         bool ExplicitResultType,
5426                         bool Mutable);
5427
5428   /// \brief Perform initialization analysis of the init-capture and perform
5429   /// any implicit conversions such as an lvalue-to-rvalue conversion if
5430   /// not being used to initialize a reference.
5431   ParsedType actOnLambdaInitCaptureInitialization(
5432       SourceLocation Loc, bool ByRef, IdentifierInfo *Id,
5433       LambdaCaptureInitKind InitKind, Expr *&Init) {
5434     return ParsedType::make(buildLambdaInitCaptureInitialization(
5435         Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init));
5436   }
5437   QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef,
5438                                                 IdentifierInfo *Id,
5439                                                 bool DirectInit, Expr *&Init);
5440
5441   /// \brief Create a dummy variable within the declcontext of the lambda's
5442   ///  call operator, for name lookup purposes for a lambda init capture.
5443   ///
5444   ///  CodeGen handles emission of lambda captures, ignoring these dummy
5445   ///  variables appropriately.
5446   VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
5447                                           QualType InitCaptureType,
5448                                           IdentifierInfo *Id,
5449                                           unsigned InitStyle, Expr *Init);
5450
5451   /// \brief Build the implicit field for an init-capture.
5452   FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
5453
5454   /// \brief Note that we have finished the explicit captures for the
5455   /// given lambda.
5456   void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
5457
5458   /// \brief Introduce the lambda parameters into scope.
5459   void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
5460
5461   /// \brief Deduce a block or lambda's return type based on the return
5462   /// statements present in the body.
5463   void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
5464
5465   /// ActOnStartOfLambdaDefinition - This is called just before we start
5466   /// parsing the body of a lambda; it analyzes the explicit captures and
5467   /// arguments, and sets up various data-structures for the body of the
5468   /// lambda.
5469   void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
5470                                     Declarator &ParamInfo, Scope *CurScope);
5471
5472   /// ActOnLambdaError - If there is an error parsing a lambda, this callback
5473   /// is invoked to pop the information about the lambda.
5474   void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
5475                         bool IsInstantiation = false);
5476
5477   /// ActOnLambdaExpr - This is called when the body of a lambda expression
5478   /// was successfully completed.
5479   ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
5480                              Scope *CurScope);
5481
5482   /// \brief Does copying/destroying the captured variable have side effects?
5483   bool CaptureHasSideEffects(const sema::LambdaScopeInfo::Capture &From);
5484
5485   /// \brief Diagnose if an explicit lambda capture is unused.
5486   void DiagnoseUnusedLambdaCapture(const sema::LambdaScopeInfo::Capture &From);
5487
5488   /// \brief Complete a lambda-expression having processed and attached the
5489   /// lambda body.
5490   ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
5491                              sema::LambdaScopeInfo *LSI);
5492
5493   /// \brief Define the "body" of the conversion from a lambda object to a
5494   /// function pointer.
5495   ///
5496   /// This routine doesn't actually define a sensible body; rather, it fills
5497   /// in the initialization expression needed to copy the lambda object into
5498   /// the block, and IR generation actually generates the real body of the
5499   /// block pointer conversion.
5500   void DefineImplicitLambdaToFunctionPointerConversion(
5501          SourceLocation CurrentLoc, CXXConversionDecl *Conv);
5502
5503   /// \brief Define the "body" of the conversion from a lambda object to a
5504   /// block pointer.
5505   ///
5506   /// This routine doesn't actually define a sensible body; rather, it fills
5507   /// in the initialization expression needed to copy the lambda object into
5508   /// the block, and IR generation actually generates the real body of the
5509   /// block pointer conversion.
5510   void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
5511                                                     CXXConversionDecl *Conv);
5512
5513   ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
5514                                            SourceLocation ConvLocation,
5515                                            CXXConversionDecl *Conv,
5516                                            Expr *Src);
5517
5518   // ParseObjCStringLiteral - Parse Objective-C string literals.
5519   ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
5520                                     ArrayRef<Expr *> Strings);
5521
5522   ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
5523
5524   /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
5525   /// numeric literal expression. Type of the expression will be "NSNumber *"
5526   /// or "id" if NSNumber is unavailable.
5527   ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
5528   ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
5529                                   bool Value);
5530   ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
5531
5532   /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
5533   /// '@' prefixed parenthesized expression. The type of the expression will
5534   /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
5535   /// of ValueType, which is allowed to be a built-in numeric type, "char *",
5536   /// "const char *" or C structure with attribute 'objc_boxable'.
5537   ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
5538
5539   ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
5540                                           Expr *IndexExpr,
5541                                           ObjCMethodDecl *getterMethod,
5542                                           ObjCMethodDecl *setterMethod);
5543
5544   ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
5545                                MutableArrayRef<ObjCDictionaryElement> Elements);
5546
5547   ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
5548                                   TypeSourceInfo *EncodedTypeInfo,
5549                                   SourceLocation RParenLoc);
5550   ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
5551                                     CXXConversionDecl *Method,
5552                                     bool HadMultipleCandidates);
5553
5554   ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
5555                                        SourceLocation EncodeLoc,
5556                                        SourceLocation LParenLoc,
5557                                        ParsedType Ty,
5558                                        SourceLocation RParenLoc);
5559
5560   /// ParseObjCSelectorExpression - Build selector expression for \@selector
5561   ExprResult ParseObjCSelectorExpression(Selector Sel,
5562                                          SourceLocation AtLoc,
5563                                          SourceLocation SelLoc,
5564                                          SourceLocation LParenLoc,
5565                                          SourceLocation RParenLoc,
5566                                          bool WarnMultipleSelectors);
5567
5568   /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
5569   ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
5570                                          SourceLocation AtLoc,
5571                                          SourceLocation ProtoLoc,
5572                                          SourceLocation LParenLoc,
5573                                          SourceLocation ProtoIdLoc,
5574                                          SourceLocation RParenLoc);
5575
5576   //===--------------------------------------------------------------------===//
5577   // C++ Declarations
5578   //
5579   Decl *ActOnStartLinkageSpecification(Scope *S,
5580                                        SourceLocation ExternLoc,
5581                                        Expr *LangStr,
5582                                        SourceLocation LBraceLoc);
5583   Decl *ActOnFinishLinkageSpecification(Scope *S,
5584                                         Decl *LinkageSpec,
5585                                         SourceLocation RBraceLoc);
5586
5587
5588   //===--------------------------------------------------------------------===//
5589   // C++ Classes
5590   //
5591   bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
5592                           const CXXScopeSpec *SS = nullptr);
5593   bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
5594
5595   bool ActOnAccessSpecifier(AccessSpecifier Access,
5596                             SourceLocation ASLoc,
5597                             SourceLocation ColonLoc,
5598                             AttributeList *Attrs = nullptr);
5599
5600   NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
5601                                  Declarator &D,
5602                                  MultiTemplateParamsArg TemplateParameterLists,
5603                                  Expr *BitfieldWidth, const VirtSpecifiers &VS,
5604                                  InClassInitStyle InitStyle);
5605
5606   void ActOnStartCXXInClassMemberInitializer();
5607   void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
5608                                               SourceLocation EqualLoc,
5609                                               Expr *Init);
5610
5611   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5612                                     Scope *S,
5613                                     CXXScopeSpec &SS,
5614                                     IdentifierInfo *MemberOrBase,
5615                                     ParsedType TemplateTypeTy,
5616                                     const DeclSpec &DS,
5617                                     SourceLocation IdLoc,
5618                                     SourceLocation LParenLoc,
5619                                     ArrayRef<Expr *> Args,
5620                                     SourceLocation RParenLoc,
5621                                     SourceLocation EllipsisLoc);
5622
5623   MemInitResult ActOnMemInitializer(Decl *ConstructorD,
5624                                     Scope *S,
5625                                     CXXScopeSpec &SS,
5626                                     IdentifierInfo *MemberOrBase,
5627                                     ParsedType TemplateTypeTy,
5628                                     const DeclSpec &DS,
5629                                     SourceLocation IdLoc,
5630                                     Expr *InitList,
5631                                     SourceLocation EllipsisLoc);
5632
5633   MemInitResult BuildMemInitializer(Decl *ConstructorD,
5634                                     Scope *S,
5635                                     CXXScopeSpec &SS,
5636                                     IdentifierInfo *MemberOrBase,
5637                                     ParsedType TemplateTypeTy,
5638                                     const DeclSpec &DS,
5639                                     SourceLocation IdLoc,
5640                                     Expr *Init,
5641                                     SourceLocation EllipsisLoc);
5642
5643   MemInitResult BuildMemberInitializer(ValueDecl *Member,
5644                                        Expr *Init,
5645                                        SourceLocation IdLoc);
5646
5647   MemInitResult BuildBaseInitializer(QualType BaseType,
5648                                      TypeSourceInfo *BaseTInfo,
5649                                      Expr *Init,
5650                                      CXXRecordDecl *ClassDecl,
5651                                      SourceLocation EllipsisLoc);
5652
5653   MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
5654                                            Expr *Init,
5655                                            CXXRecordDecl *ClassDecl);
5656
5657   bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5658                                 CXXCtorInitializer *Initializer);
5659
5660   bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5661                            ArrayRef<CXXCtorInitializer *> Initializers = None);
5662
5663   void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
5664
5665
5666   /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
5667   /// mark all the non-trivial destructors of its members and bases as
5668   /// referenced.
5669   void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
5670                                               CXXRecordDecl *Record);
5671
5672   /// \brief The list of classes whose vtables have been used within
5673   /// this translation unit, and the source locations at which the
5674   /// first use occurred.
5675   typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
5676
5677   /// \brief The list of vtables that are required but have not yet been
5678   /// materialized.
5679   SmallVector<VTableUse, 16> VTableUses;
5680
5681   /// \brief The set of classes whose vtables have been used within
5682   /// this translation unit, and a bit that will be true if the vtable is
5683   /// required to be emitted (otherwise, it should be emitted only if needed
5684   /// by code generation).
5685   llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
5686
5687   /// \brief Load any externally-stored vtable uses.
5688   void LoadExternalVTableUses();
5689
5690   /// \brief Note that the vtable for the given class was used at the
5691   /// given location.
5692   void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
5693                       bool DefinitionRequired = false);
5694
5695   /// \brief Mark the exception specifications of all virtual member functions
5696   /// in the given class as needed.
5697   void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
5698                                              const CXXRecordDecl *RD);
5699
5700   /// MarkVirtualMembersReferenced - Will mark all members of the given
5701   /// CXXRecordDecl referenced.
5702   void MarkVirtualMembersReferenced(SourceLocation Loc,
5703                                     const CXXRecordDecl *RD);
5704
5705   /// \brief Define all of the vtables that have been used in this
5706   /// translation unit and reference any virtual members used by those
5707   /// vtables.
5708   ///
5709   /// \returns true if any work was done, false otherwise.
5710   bool DefineUsedVTables();
5711
5712   void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
5713
5714   void ActOnMemInitializers(Decl *ConstructorDecl,
5715                             SourceLocation ColonLoc,
5716                             ArrayRef<CXXCtorInitializer*> MemInits,
5717                             bool AnyErrors);
5718
5719   /// \brief Check class-level dllimport/dllexport attribute. The caller must
5720   /// ensure that referenceDLLExportedClassMethods is called some point later
5721   /// when all outer classes of Class are complete.
5722   void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
5723
5724   void referenceDLLExportedClassMethods();
5725
5726   void propagateDLLAttrToBaseClassTemplate(
5727       CXXRecordDecl *Class, Attr *ClassAttr,
5728       ClassTemplateSpecializationDecl *BaseTemplateSpec,
5729       SourceLocation BaseLoc);
5730
5731   void CheckCompletedCXXClass(CXXRecordDecl *Record);
5732   void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5733                                          Decl *TagDecl,
5734                                          SourceLocation LBrac,
5735                                          SourceLocation RBrac,
5736                                          AttributeList *AttrList);
5737   void ActOnFinishCXXMemberDecls();
5738   void ActOnFinishCXXNonNestedClass(Decl *D);
5739
5740   void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
5741   unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
5742   void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
5743   void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5744   void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
5745   void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
5746   void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
5747   void ActOnFinishDelayedMemberInitializers(Decl *Record);
5748   void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
5749                                 CachedTokens &Toks);
5750   void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
5751   bool IsInsideALocalClassWithinATemplateFunction();
5752
5753   Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5754                                      Expr *AssertExpr,
5755                                      Expr *AssertMessageExpr,
5756                                      SourceLocation RParenLoc);
5757   Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
5758                                      Expr *AssertExpr,
5759                                      StringLiteral *AssertMessageExpr,
5760                                      SourceLocation RParenLoc,
5761                                      bool Failed);
5762
5763   FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
5764                                   SourceLocation FriendLoc,
5765                                   TypeSourceInfo *TSInfo);
5766   Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
5767                             MultiTemplateParamsArg TemplateParams);
5768   NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
5769                                      MultiTemplateParamsArg TemplateParams);
5770
5771   QualType CheckConstructorDeclarator(Declarator &D, QualType R,
5772                                       StorageClass& SC);
5773   void CheckConstructor(CXXConstructorDecl *Constructor);
5774   QualType CheckDestructorDeclarator(Declarator &D, QualType R,
5775                                      StorageClass& SC);
5776   bool CheckDestructor(CXXDestructorDecl *Destructor);
5777   void CheckConversionDeclarator(Declarator &D, QualType &R,
5778                                  StorageClass& SC);
5779   Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
5780   void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
5781                                      StorageClass &SC);
5782   void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
5783
5784   void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
5785   void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
5786                                                    const FunctionProtoType *T);
5787   void CheckDelayedMemberExceptionSpecs();
5788
5789   //===--------------------------------------------------------------------===//
5790   // C++ Derived Classes
5791   //
5792
5793   /// ActOnBaseSpecifier - Parsed a base specifier
5794   CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
5795                                        SourceRange SpecifierRange,
5796                                        bool Virtual, AccessSpecifier Access,
5797                                        TypeSourceInfo *TInfo,
5798                                        SourceLocation EllipsisLoc);
5799
5800   BaseResult ActOnBaseSpecifier(Decl *classdecl,
5801                                 SourceRange SpecifierRange,
5802                                 ParsedAttributes &Attrs,
5803                                 bool Virtual, AccessSpecifier Access,
5804                                 ParsedType basetype,
5805                                 SourceLocation BaseLoc,
5806                                 SourceLocation EllipsisLoc);
5807
5808   bool AttachBaseSpecifiers(CXXRecordDecl *Class,
5809                             MutableArrayRef<CXXBaseSpecifier *> Bases);
5810   void ActOnBaseSpecifiers(Decl *ClassDecl,
5811                            MutableArrayRef<CXXBaseSpecifier *> Bases);
5812
5813   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
5814   bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
5815                      CXXBasePaths &Paths);
5816
5817   // FIXME: I don't like this name.
5818   void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
5819
5820   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5821                                     SourceLocation Loc, SourceRange Range,
5822                                     CXXCastPath *BasePath = nullptr,
5823                                     bool IgnoreAccess = false);
5824   bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
5825                                     unsigned InaccessibleBaseID,
5826                                     unsigned AmbigiousBaseConvID,
5827                                     SourceLocation Loc, SourceRange Range,
5828                                     DeclarationName Name,
5829                                     CXXCastPath *BasePath,
5830                                     bool IgnoreAccess = false);
5831
5832   std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
5833
5834   bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5835                                          const CXXMethodDecl *Old);
5836
5837   /// CheckOverridingFunctionReturnType - Checks whether the return types are
5838   /// covariant, according to C++ [class.virtual]p5.
5839   bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
5840                                          const CXXMethodDecl *Old);
5841
5842   /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
5843   /// spec is a subset of base spec.
5844   bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
5845                                             const CXXMethodDecl *Old);
5846
5847   bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
5848
5849   /// CheckOverrideControl - Check C++11 override control semantics.
5850   void CheckOverrideControl(NamedDecl *D);
5851
5852   /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
5853   /// not used in the declaration of an overriding method.
5854   void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
5855
5856   /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
5857   /// overrides a virtual member function marked 'final', according to
5858   /// C++11 [class.virtual]p4.
5859   bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
5860                                               const CXXMethodDecl *Old);
5861
5862
5863   //===--------------------------------------------------------------------===//
5864   // C++ Access Control
5865   //
5866
5867   enum AccessResult {
5868     AR_accessible,
5869     AR_inaccessible,
5870     AR_dependent,
5871     AR_delayed
5872   };
5873
5874   bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
5875                                 NamedDecl *PrevMemberDecl,
5876                                 AccessSpecifier LexicalAS);
5877
5878   AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
5879                                            DeclAccessPair FoundDecl);
5880   AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
5881                                            DeclAccessPair FoundDecl);
5882   AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
5883                                      SourceRange PlacementRange,
5884                                      CXXRecordDecl *NamingClass,
5885                                      DeclAccessPair FoundDecl,
5886                                      bool Diagnose = true);
5887   AccessResult CheckConstructorAccess(SourceLocation Loc,
5888                                       CXXConstructorDecl *D,
5889                                       DeclAccessPair FoundDecl,
5890                                       const InitializedEntity &Entity,
5891                                       bool IsCopyBindingRefToTemp = false);
5892   AccessResult CheckConstructorAccess(SourceLocation Loc,
5893                                       CXXConstructorDecl *D,
5894                                       DeclAccessPair FoundDecl,
5895                                       const InitializedEntity &Entity,
5896                                       const PartialDiagnostic &PDiag);
5897   AccessResult CheckDestructorAccess(SourceLocation Loc,
5898                                      CXXDestructorDecl *Dtor,
5899                                      const PartialDiagnostic &PDiag,
5900                                      QualType objectType = QualType());
5901   AccessResult CheckFriendAccess(NamedDecl *D);
5902   AccessResult CheckMemberAccess(SourceLocation UseLoc,
5903                                  CXXRecordDecl *NamingClass,
5904                                  DeclAccessPair Found);
5905   AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
5906                                          Expr *ObjectExpr,
5907                                          Expr *ArgExpr,
5908                                          DeclAccessPair FoundDecl);
5909   AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
5910                                           DeclAccessPair FoundDecl);
5911   AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
5912                                     QualType Base, QualType Derived,
5913                                     const CXXBasePath &Path,
5914                                     unsigned DiagID,
5915                                     bool ForceCheck = false,
5916                                     bool ForceUnprivileged = false);
5917   void CheckLookupAccess(const LookupResult &R);
5918   bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
5919   bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
5920                                             AccessSpecifier access,
5921                                             QualType objectType);
5922
5923   void HandleDependentAccessCheck(const DependentDiagnostic &DD,
5924                          const MultiLevelTemplateArgumentList &TemplateArgs);
5925   void PerformDependentDiagnostics(const DeclContext *Pattern,
5926                         const MultiLevelTemplateArgumentList &TemplateArgs);
5927
5928   void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5929
5930   /// \brief When true, access checking violations are treated as SFINAE
5931   /// failures rather than hard errors.
5932   bool AccessCheckingSFINAE;
5933
5934   enum AbstractDiagSelID {
5935     AbstractNone = -1,
5936     AbstractReturnType,
5937     AbstractParamType,
5938     AbstractVariableType,
5939     AbstractFieldType,
5940     AbstractIvarType,
5941     AbstractSynthesizedIvarType,
5942     AbstractArrayType
5943   };
5944
5945   bool isAbstractType(SourceLocation Loc, QualType T);
5946   bool RequireNonAbstractType(SourceLocation Loc, QualType T,
5947                               TypeDiagnoser &Diagnoser);
5948   template <typename... Ts>
5949   bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
5950                               const Ts &...Args) {
5951     BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
5952     return RequireNonAbstractType(Loc, T, Diagnoser);
5953   }
5954
5955   void DiagnoseAbstractType(const CXXRecordDecl *RD);
5956
5957   //===--------------------------------------------------------------------===//
5958   // C++ Overloaded Operators [C++ 13.5]
5959   //
5960
5961   bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
5962
5963   bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
5964
5965   //===--------------------------------------------------------------------===//
5966   // C++ Templates [C++ 14]
5967   //
5968   void FilterAcceptableTemplateNames(LookupResult &R,
5969                                      bool AllowFunctionTemplates = true);
5970   bool hasAnyAcceptableTemplateNames(LookupResult &R,
5971                                      bool AllowFunctionTemplates = true);
5972
5973   void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
5974                           QualType ObjectType, bool EnteringContext,
5975                           bool &MemberOfUnknownSpecialization);
5976
5977   TemplateNameKind isTemplateName(Scope *S,
5978                                   CXXScopeSpec &SS,
5979                                   bool hasTemplateKeyword,
5980                                   UnqualifiedId &Name,
5981                                   ParsedType ObjectType,
5982                                   bool EnteringContext,
5983                                   TemplateTy &Template,
5984                                   bool &MemberOfUnknownSpecialization);
5985
5986   /// Determine whether a particular identifier might be the name in a C++1z
5987   /// deduction-guide declaration.
5988   bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
5989                             SourceLocation NameLoc,
5990                             ParsedTemplateTy *Template = nullptr);
5991
5992   bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
5993                                    SourceLocation IILoc,
5994                                    Scope *S,
5995                                    const CXXScopeSpec *SS,
5996                                    TemplateTy &SuggestedTemplate,
5997                                    TemplateNameKind &SuggestedKind);
5998
5999   bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
6000                                       NamedDecl *Instantiation,
6001                                       bool InstantiatedFromMember,
6002                                       const NamedDecl *Pattern,
6003                                       const NamedDecl *PatternDef,
6004                                       TemplateSpecializationKind TSK,
6005                                       bool Complain = true);
6006
6007   void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
6008   TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
6009
6010   Decl *ActOnTypeParameter(Scope *S, bool Typename,
6011                            SourceLocation EllipsisLoc,
6012                            SourceLocation KeyLoc,
6013                            IdentifierInfo *ParamName,
6014                            SourceLocation ParamNameLoc,
6015                            unsigned Depth, unsigned Position,
6016                            SourceLocation EqualLoc,
6017                            ParsedType DefaultArg);
6018
6019   QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
6020                                              SourceLocation Loc);
6021   QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
6022
6023   Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
6024                                       unsigned Depth,
6025                                       unsigned Position,
6026                                       SourceLocation EqualLoc,
6027                                       Expr *DefaultArg);
6028   Decl *ActOnTemplateTemplateParameter(Scope *S,
6029                                        SourceLocation TmpLoc,
6030                                        TemplateParameterList *Params,
6031                                        SourceLocation EllipsisLoc,
6032                                        IdentifierInfo *ParamName,
6033                                        SourceLocation ParamNameLoc,
6034                                        unsigned Depth,
6035                                        unsigned Position,
6036                                        SourceLocation EqualLoc,
6037                                        ParsedTemplateArgument DefaultArg);
6038
6039   TemplateParameterList *
6040   ActOnTemplateParameterList(unsigned Depth,
6041                              SourceLocation ExportLoc,
6042                              SourceLocation TemplateLoc,
6043                              SourceLocation LAngleLoc,
6044                              ArrayRef<Decl *> Params,
6045                              SourceLocation RAngleLoc,
6046                              Expr *RequiresClause);
6047
6048   /// \brief The context in which we are checking a template parameter list.
6049   enum TemplateParamListContext {
6050     TPC_ClassTemplate,
6051     TPC_VarTemplate,
6052     TPC_FunctionTemplate,
6053     TPC_ClassTemplateMember,
6054     TPC_FriendClassTemplate,
6055     TPC_FriendFunctionTemplate,
6056     TPC_FriendFunctionTemplateDefinition,
6057     TPC_TypeAliasTemplate
6058   };
6059
6060   bool CheckTemplateParameterList(TemplateParameterList *NewParams,
6061                                   TemplateParameterList *OldParams,
6062                                   TemplateParamListContext TPC);
6063   TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
6064       SourceLocation DeclStartLoc, SourceLocation DeclLoc,
6065       const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
6066       ArrayRef<TemplateParameterList *> ParamLists,
6067       bool IsFriend, bool &IsMemberSpecialization, bool &Invalid);
6068
6069   DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
6070                                 SourceLocation KWLoc, CXXScopeSpec &SS,
6071                                 IdentifierInfo *Name, SourceLocation NameLoc,
6072                                 AttributeList *Attr,
6073                                 TemplateParameterList *TemplateParams,
6074                                 AccessSpecifier AS,
6075                                 SourceLocation ModulePrivateLoc,
6076                                 SourceLocation FriendLoc,
6077                                 unsigned NumOuterTemplateParamLists,
6078                             TemplateParameterList **OuterTemplateParamLists,
6079                                 SkipBodyInfo *SkipBody = nullptr);
6080
6081   TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
6082                                                     QualType NTTPType,
6083                                                     SourceLocation Loc);
6084
6085   void translateTemplateArguments(const ASTTemplateArgsPtr &In,
6086                                   TemplateArgumentListInfo &Out);
6087
6088   void NoteAllFoundTemplates(TemplateName Name);
6089
6090   QualType CheckTemplateIdType(TemplateName Template,
6091                                SourceLocation TemplateLoc,
6092                               TemplateArgumentListInfo &TemplateArgs);
6093
6094   TypeResult
6095   ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6096                       TemplateTy Template, IdentifierInfo *TemplateII,
6097                       SourceLocation TemplateIILoc,
6098                       SourceLocation LAngleLoc,
6099                       ASTTemplateArgsPtr TemplateArgs,
6100                       SourceLocation RAngleLoc,
6101                       bool IsCtorOrDtorName = false,
6102                       bool IsClassName = false);
6103
6104   /// \brief Parsed an elaborated-type-specifier that refers to a template-id,
6105   /// such as \c class T::template apply<U>.
6106   TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
6107                                     TypeSpecifierType TagSpec,
6108                                     SourceLocation TagLoc,
6109                                     CXXScopeSpec &SS,
6110                                     SourceLocation TemplateKWLoc,
6111                                     TemplateTy TemplateD,
6112                                     SourceLocation TemplateLoc,
6113                                     SourceLocation LAngleLoc,
6114                                     ASTTemplateArgsPtr TemplateArgsIn,
6115                                     SourceLocation RAngleLoc);
6116
6117   DeclResult ActOnVarTemplateSpecialization(
6118       Scope *S, Declarator &D, TypeSourceInfo *DI,
6119       SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
6120       StorageClass SC, bool IsPartialSpecialization);
6121
6122   DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
6123                                 SourceLocation TemplateLoc,
6124                                 SourceLocation TemplateNameLoc,
6125                                 const TemplateArgumentListInfo &TemplateArgs);
6126
6127   ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
6128                                 const DeclarationNameInfo &NameInfo,
6129                                 VarTemplateDecl *Template,
6130                                 SourceLocation TemplateLoc,
6131                                 const TemplateArgumentListInfo *TemplateArgs);
6132
6133   ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
6134                                  SourceLocation TemplateKWLoc,
6135                                  LookupResult &R,
6136                                  bool RequiresADL,
6137                                const TemplateArgumentListInfo *TemplateArgs);
6138
6139   ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
6140                                           SourceLocation TemplateKWLoc,
6141                                const DeclarationNameInfo &NameInfo,
6142                                const TemplateArgumentListInfo *TemplateArgs);
6143
6144   TemplateNameKind ActOnDependentTemplateName(
6145       Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
6146       UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
6147       TemplateTy &Template, bool AllowInjectedClassName = false);
6148
6149   DeclResult
6150   ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
6151                                    SourceLocation KWLoc,
6152                                    SourceLocation ModulePrivateLoc,
6153                                    TemplateIdAnnotation &TemplateId,
6154                                    AttributeList *Attr,
6155                                  MultiTemplateParamsArg TemplateParameterLists,
6156                                    SkipBodyInfo *SkipBody = nullptr);
6157
6158   bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
6159                                               TemplateDecl *PrimaryTemplate,
6160                                               unsigned NumExplicitArgs,
6161                                               ArrayRef<TemplateArgument> Args);
6162   void CheckTemplatePartialSpecialization(
6163       ClassTemplatePartialSpecializationDecl *Partial);
6164   void CheckTemplatePartialSpecialization(
6165       VarTemplatePartialSpecializationDecl *Partial);
6166
6167   Decl *ActOnTemplateDeclarator(Scope *S,
6168                                 MultiTemplateParamsArg TemplateParameterLists,
6169                                 Declarator &D);
6170
6171   bool
6172   CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6173                                          TemplateSpecializationKind NewTSK,
6174                                          NamedDecl *PrevDecl,
6175                                          TemplateSpecializationKind PrevTSK,
6176                                          SourceLocation PrevPtOfInstantiation,
6177                                          bool &SuppressNew);
6178
6179   bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6180                     const TemplateArgumentListInfo &ExplicitTemplateArgs,
6181                                                     LookupResult &Previous);
6182
6183   bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
6184                          TemplateArgumentListInfo *ExplicitTemplateArgs,
6185                                            LookupResult &Previous);
6186   bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6187   void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
6188
6189   DeclResult
6190   ActOnExplicitInstantiation(Scope *S,
6191                              SourceLocation ExternLoc,
6192                              SourceLocation TemplateLoc,
6193                              unsigned TagSpec,
6194                              SourceLocation KWLoc,
6195                              const CXXScopeSpec &SS,
6196                              TemplateTy Template,
6197                              SourceLocation TemplateNameLoc,
6198                              SourceLocation LAngleLoc,
6199                              ASTTemplateArgsPtr TemplateArgs,
6200                              SourceLocation RAngleLoc,
6201                              AttributeList *Attr);
6202
6203   DeclResult
6204   ActOnExplicitInstantiation(Scope *S,
6205                              SourceLocation ExternLoc,
6206                              SourceLocation TemplateLoc,
6207                              unsigned TagSpec,
6208                              SourceLocation KWLoc,
6209                              CXXScopeSpec &SS,
6210                              IdentifierInfo *Name,
6211                              SourceLocation NameLoc,
6212                              AttributeList *Attr);
6213
6214   DeclResult ActOnExplicitInstantiation(Scope *S,
6215                                         SourceLocation ExternLoc,
6216                                         SourceLocation TemplateLoc,
6217                                         Declarator &D);
6218
6219   TemplateArgumentLoc
6220   SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
6221                                           SourceLocation TemplateLoc,
6222                                           SourceLocation RAngleLoc,
6223                                           Decl *Param,
6224                                           SmallVectorImpl<TemplateArgument>
6225                                             &Converted,
6226                                           bool &HasDefaultArg);
6227
6228   /// \brief Specifies the context in which a particular template
6229   /// argument is being checked.
6230   enum CheckTemplateArgumentKind {
6231     /// \brief The template argument was specified in the code or was
6232     /// instantiated with some deduced template arguments.
6233     CTAK_Specified,
6234
6235     /// \brief The template argument was deduced via template argument
6236     /// deduction.
6237     CTAK_Deduced,
6238
6239     /// \brief The template argument was deduced from an array bound
6240     /// via template argument deduction.
6241     CTAK_DeducedFromArrayBound
6242   };
6243
6244   bool CheckTemplateArgument(NamedDecl *Param,
6245                              TemplateArgumentLoc &Arg,
6246                              NamedDecl *Template,
6247                              SourceLocation TemplateLoc,
6248                              SourceLocation RAngleLoc,
6249                              unsigned ArgumentPackIndex,
6250                            SmallVectorImpl<TemplateArgument> &Converted,
6251                              CheckTemplateArgumentKind CTAK = CTAK_Specified);
6252
6253   /// \brief Check that the given template arguments can be be provided to
6254   /// the given template, converting the arguments along the way.
6255   ///
6256   /// \param Template The template to which the template arguments are being
6257   /// provided.
6258   ///
6259   /// \param TemplateLoc The location of the template name in the source.
6260   ///
6261   /// \param TemplateArgs The list of template arguments. If the template is
6262   /// a template template parameter, this function may extend the set of
6263   /// template arguments to also include substituted, defaulted template
6264   /// arguments.
6265   ///
6266   /// \param PartialTemplateArgs True if the list of template arguments is
6267   /// intentionally partial, e.g., because we're checking just the initial
6268   /// set of template arguments.
6269   ///
6270   /// \param Converted Will receive the converted, canonicalized template
6271   /// arguments.
6272   ///
6273   /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
6274   /// contain the converted forms of the template arguments as written.
6275   /// Otherwise, \p TemplateArgs will not be modified.
6276   ///
6277   /// \returns true if an error occurred, false otherwise.
6278   bool CheckTemplateArgumentList(TemplateDecl *Template,
6279                                  SourceLocation TemplateLoc,
6280                                  TemplateArgumentListInfo &TemplateArgs,
6281                                  bool PartialTemplateArgs,
6282                                  SmallVectorImpl<TemplateArgument> &Converted,
6283                                  bool UpdateArgsWithConversions = true);
6284
6285   bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
6286                                  TemplateArgumentLoc &Arg,
6287                            SmallVectorImpl<TemplateArgument> &Converted);
6288
6289   bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
6290                              TypeSourceInfo *Arg);
6291   ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6292                                    QualType InstantiatedParamType, Expr *Arg,
6293                                    TemplateArgument &Converted,
6294                                CheckTemplateArgumentKind CTAK = CTAK_Specified);
6295   bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
6296                              TemplateArgumentLoc &Arg,
6297                              unsigned ArgumentPackIndex);
6298
6299   ExprResult
6300   BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6301                                           QualType ParamType,
6302                                           SourceLocation Loc);
6303   ExprResult
6304   BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6305                                               SourceLocation Loc);
6306
6307   /// \brief Enumeration describing how template parameter lists are compared
6308   /// for equality.
6309   enum TemplateParameterListEqualKind {
6310     /// \brief We are matching the template parameter lists of two templates
6311     /// that might be redeclarations.
6312     ///
6313     /// \code
6314     /// template<typename T> struct X;
6315     /// template<typename T> struct X;
6316     /// \endcode
6317     TPL_TemplateMatch,
6318
6319     /// \brief We are matching the template parameter lists of two template
6320     /// template parameters as part of matching the template parameter lists
6321     /// of two templates that might be redeclarations.
6322     ///
6323     /// \code
6324     /// template<template<int I> class TT> struct X;
6325     /// template<template<int Value> class Other> struct X;
6326     /// \endcode
6327     TPL_TemplateTemplateParmMatch,
6328
6329     /// \brief We are matching the template parameter lists of a template
6330     /// template argument against the template parameter lists of a template
6331     /// template parameter.
6332     ///
6333     /// \code
6334     /// template<template<int Value> class Metafun> struct X;
6335     /// template<int Value> struct integer_c;
6336     /// X<integer_c> xic;
6337     /// \endcode
6338     TPL_TemplateTemplateArgumentMatch
6339   };
6340
6341   bool TemplateParameterListsAreEqual(TemplateParameterList *New,
6342                                       TemplateParameterList *Old,
6343                                       bool Complain,
6344                                       TemplateParameterListEqualKind Kind,
6345                                       SourceLocation TemplateArgLoc
6346                                         = SourceLocation());
6347
6348   bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
6349
6350   /// \brief Called when the parser has parsed a C++ typename
6351   /// specifier, e.g., "typename T::type".
6352   ///
6353   /// \param S The scope in which this typename type occurs.
6354   /// \param TypenameLoc the location of the 'typename' keyword
6355   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6356   /// \param II the identifier we're retrieving (e.g., 'type' in the example).
6357   /// \param IdLoc the location of the identifier.
6358   TypeResult
6359   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6360                     const CXXScopeSpec &SS, const IdentifierInfo &II,
6361                     SourceLocation IdLoc);
6362
6363   /// \brief Called when the parser has parsed a C++ typename
6364   /// specifier that ends in a template-id, e.g.,
6365   /// "typename MetaFun::template apply<T1, T2>".
6366   ///
6367   /// \param S The scope in which this typename type occurs.
6368   /// \param TypenameLoc the location of the 'typename' keyword
6369   /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
6370   /// \param TemplateLoc the location of the 'template' keyword, if any.
6371   /// \param TemplateName The template name.
6372   /// \param TemplateII The identifier used to name the template.
6373   /// \param TemplateIILoc The location of the template name.
6374   /// \param LAngleLoc The location of the opening angle bracket  ('<').
6375   /// \param TemplateArgs The template arguments.
6376   /// \param RAngleLoc The location of the closing angle bracket  ('>').
6377   TypeResult
6378   ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6379                     const CXXScopeSpec &SS,
6380                     SourceLocation TemplateLoc,
6381                     TemplateTy TemplateName,
6382                     IdentifierInfo *TemplateII,
6383                     SourceLocation TemplateIILoc,
6384                     SourceLocation LAngleLoc,
6385                     ASTTemplateArgsPtr TemplateArgs,
6386                     SourceLocation RAngleLoc);
6387
6388   QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
6389                              SourceLocation KeywordLoc,
6390                              NestedNameSpecifierLoc QualifierLoc,
6391                              const IdentifierInfo &II,
6392                              SourceLocation IILoc);
6393
6394   TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6395                                                     SourceLocation Loc,
6396                                                     DeclarationName Name);
6397   bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
6398
6399   ExprResult RebuildExprInCurrentInstantiation(Expr *E);
6400   bool RebuildTemplateParamsInCurrentInstantiation(
6401                                                 TemplateParameterList *Params);
6402
6403   std::string
6404   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6405                                   const TemplateArgumentList &Args);
6406
6407   std::string
6408   getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6409                                   const TemplateArgument *Args,
6410                                   unsigned NumArgs);
6411
6412   //===--------------------------------------------------------------------===//
6413   // C++ Variadic Templates (C++0x [temp.variadic])
6414   //===--------------------------------------------------------------------===//
6415
6416   /// Determine whether an unexpanded parameter pack might be permitted in this
6417   /// location. Useful for error recovery.
6418   bool isUnexpandedParameterPackPermitted();
6419
6420   /// \brief The context in which an unexpanded parameter pack is
6421   /// being diagnosed.
6422   ///
6423   /// Note that the values of this enumeration line up with the first
6424   /// argument to the \c err_unexpanded_parameter_pack diagnostic.
6425   enum UnexpandedParameterPackContext {
6426     /// \brief An arbitrary expression.
6427     UPPC_Expression = 0,
6428
6429     /// \brief The base type of a class type.
6430     UPPC_BaseType,
6431
6432     /// \brief The type of an arbitrary declaration.
6433     UPPC_DeclarationType,
6434
6435     /// \brief The type of a data member.
6436     UPPC_DataMemberType,
6437
6438     /// \brief The size of a bit-field.
6439     UPPC_BitFieldWidth,
6440
6441     /// \brief The expression in a static assertion.
6442     UPPC_StaticAssertExpression,
6443
6444     /// \brief The fixed underlying type of an enumeration.
6445     UPPC_FixedUnderlyingType,
6446
6447     /// \brief The enumerator value.
6448     UPPC_EnumeratorValue,
6449
6450     /// \brief A using declaration.
6451     UPPC_UsingDeclaration,
6452
6453     /// \brief A friend declaration.
6454     UPPC_FriendDeclaration,
6455
6456     /// \brief A declaration qualifier.
6457     UPPC_DeclarationQualifier,
6458
6459     /// \brief An initializer.
6460     UPPC_Initializer,
6461
6462     /// \brief A default argument.
6463     UPPC_DefaultArgument,
6464
6465     /// \brief The type of a non-type template parameter.
6466     UPPC_NonTypeTemplateParameterType,
6467
6468     /// \brief The type of an exception.
6469     UPPC_ExceptionType,
6470
6471     /// \brief Partial specialization.
6472     UPPC_PartialSpecialization,
6473
6474     /// \brief Microsoft __if_exists.
6475     UPPC_IfExists,
6476
6477     /// \brief Microsoft __if_not_exists.
6478     UPPC_IfNotExists,
6479
6480     /// \brief Lambda expression.
6481     UPPC_Lambda,
6482
6483     /// \brief Block expression,
6484     UPPC_Block
6485   };
6486
6487   /// \brief Diagnose unexpanded parameter packs.
6488   ///
6489   /// \param Loc The location at which we should emit the diagnostic.
6490   ///
6491   /// \param UPPC The context in which we are diagnosing unexpanded
6492   /// parameter packs.
6493   ///
6494   /// \param Unexpanded the set of unexpanded parameter packs.
6495   ///
6496   /// \returns true if an error occurred, false otherwise.
6497   bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
6498                                         UnexpandedParameterPackContext UPPC,
6499                                   ArrayRef<UnexpandedParameterPack> Unexpanded);
6500
6501   /// \brief If the given type contains an unexpanded parameter pack,
6502   /// diagnose the error.
6503   ///
6504   /// \param Loc The source location where a diagnostc should be emitted.
6505   ///
6506   /// \param T The type that is being checked for unexpanded parameter
6507   /// packs.
6508   ///
6509   /// \returns true if an error occurred, false otherwise.
6510   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
6511                                        UnexpandedParameterPackContext UPPC);
6512
6513   /// \brief If the given expression contains an unexpanded parameter
6514   /// pack, diagnose the error.
6515   ///
6516   /// \param E The expression that is being checked for unexpanded
6517   /// parameter packs.
6518   ///
6519   /// \returns true if an error occurred, false otherwise.
6520   bool DiagnoseUnexpandedParameterPack(Expr *E,
6521                        UnexpandedParameterPackContext UPPC = UPPC_Expression);
6522
6523   /// \brief If the given nested-name-specifier contains an unexpanded
6524   /// parameter pack, diagnose the error.
6525   ///
6526   /// \param SS The nested-name-specifier that is being checked for
6527   /// unexpanded parameter packs.
6528   ///
6529   /// \returns true if an error occurred, false otherwise.
6530   bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
6531                                        UnexpandedParameterPackContext UPPC);
6532
6533   /// \brief If the given name contains an unexpanded parameter pack,
6534   /// diagnose the error.
6535   ///
6536   /// \param NameInfo The name (with source location information) that
6537   /// is being checked for unexpanded parameter packs.
6538   ///
6539   /// \returns true if an error occurred, false otherwise.
6540   bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
6541                                        UnexpandedParameterPackContext UPPC);
6542
6543   /// \brief If the given template name contains an unexpanded parameter pack,
6544   /// diagnose the error.
6545   ///
6546   /// \param Loc The location of the template name.
6547   ///
6548   /// \param Template The template name that is being checked for unexpanded
6549   /// parameter packs.
6550   ///
6551   /// \returns true if an error occurred, false otherwise.
6552   bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
6553                                        TemplateName Template,
6554                                        UnexpandedParameterPackContext UPPC);
6555
6556   /// \brief If the given template argument contains an unexpanded parameter
6557   /// pack, diagnose the error.
6558   ///
6559   /// \param Arg The template argument that is being checked for unexpanded
6560   /// parameter packs.
6561   ///
6562   /// \returns true if an error occurred, false otherwise.
6563   bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
6564                                        UnexpandedParameterPackContext UPPC);
6565
6566   /// \brief Collect the set of unexpanded parameter packs within the given
6567   /// template argument.
6568   ///
6569   /// \param Arg The template argument that will be traversed to find
6570   /// unexpanded parameter packs.
6571   void collectUnexpandedParameterPacks(TemplateArgument Arg,
6572                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6573
6574   /// \brief Collect the set of unexpanded parameter packs within the given
6575   /// template argument.
6576   ///
6577   /// \param Arg The template argument that will be traversed to find
6578   /// unexpanded parameter packs.
6579   void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
6580                     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6581
6582   /// \brief Collect the set of unexpanded parameter packs within the given
6583   /// type.
6584   ///
6585   /// \param T The type that will be traversed to find
6586   /// unexpanded parameter packs.
6587   void collectUnexpandedParameterPacks(QualType T,
6588                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6589
6590   /// \brief Collect the set of unexpanded parameter packs within the given
6591   /// type.
6592   ///
6593   /// \param TL The type that will be traversed to find
6594   /// unexpanded parameter packs.
6595   void collectUnexpandedParameterPacks(TypeLoc TL,
6596                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6597
6598   /// \brief Collect the set of unexpanded parameter packs within the given
6599   /// nested-name-specifier.
6600   ///
6601   /// \param NNS The nested-name-specifier that will be traversed to find
6602   /// unexpanded parameter packs.
6603   void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
6604                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6605
6606   /// \brief Collect the set of unexpanded parameter packs within the given
6607   /// name.
6608   ///
6609   /// \param NameInfo The name that will be traversed to find
6610   /// unexpanded parameter packs.
6611   void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
6612                          SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
6613
6614   /// \brief Invoked when parsing a template argument followed by an
6615   /// ellipsis, which creates a pack expansion.
6616   ///
6617   /// \param Arg The template argument preceding the ellipsis, which
6618   /// may already be invalid.
6619   ///
6620   /// \param EllipsisLoc The location of the ellipsis.
6621   ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
6622                                             SourceLocation EllipsisLoc);
6623
6624   /// \brief Invoked when parsing a type followed by an ellipsis, which
6625   /// creates a pack expansion.
6626   ///
6627   /// \param Type The type preceding the ellipsis, which will become
6628   /// the pattern of the pack expansion.
6629   ///
6630   /// \param EllipsisLoc The location of the ellipsis.
6631   TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
6632
6633   /// \brief Construct a pack expansion type from the pattern of the pack
6634   /// expansion.
6635   TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
6636                                      SourceLocation EllipsisLoc,
6637                                      Optional<unsigned> NumExpansions);
6638
6639   /// \brief Construct a pack expansion type from the pattern of the pack
6640   /// expansion.
6641   QualType CheckPackExpansion(QualType Pattern,
6642                               SourceRange PatternRange,
6643                               SourceLocation EllipsisLoc,
6644                               Optional<unsigned> NumExpansions);
6645
6646   /// \brief Invoked when parsing an expression followed by an ellipsis, which
6647   /// creates a pack expansion.
6648   ///
6649   /// \param Pattern The expression preceding the ellipsis, which will become
6650   /// the pattern of the pack expansion.
6651   ///
6652   /// \param EllipsisLoc The location of the ellipsis.
6653   ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
6654
6655   /// \brief Invoked when parsing an expression followed by an ellipsis, which
6656   /// creates a pack expansion.
6657   ///
6658   /// \param Pattern The expression preceding the ellipsis, which will become
6659   /// the pattern of the pack expansion.
6660   ///
6661   /// \param EllipsisLoc The location of the ellipsis.
6662   ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
6663                                 Optional<unsigned> NumExpansions);
6664
6665   /// \brief Determine whether we could expand a pack expansion with the
6666   /// given set of parameter packs into separate arguments by repeatedly
6667   /// transforming the pattern.
6668   ///
6669   /// \param EllipsisLoc The location of the ellipsis that identifies the
6670   /// pack expansion.
6671   ///
6672   /// \param PatternRange The source range that covers the entire pattern of
6673   /// the pack expansion.
6674   ///
6675   /// \param Unexpanded The set of unexpanded parameter packs within the
6676   /// pattern.
6677   ///
6678   /// \param ShouldExpand Will be set to \c true if the transformer should
6679   /// expand the corresponding pack expansions into separate arguments. When
6680   /// set, \c NumExpansions must also be set.
6681   ///
6682   /// \param RetainExpansion Whether the caller should add an unexpanded
6683   /// pack expansion after all of the expanded arguments. This is used
6684   /// when extending explicitly-specified template argument packs per
6685   /// C++0x [temp.arg.explicit]p9.
6686   ///
6687   /// \param NumExpansions The number of separate arguments that will be in
6688   /// the expanded form of the corresponding pack expansion. This is both an
6689   /// input and an output parameter, which can be set by the caller if the
6690   /// number of expansions is known a priori (e.g., due to a prior substitution)
6691   /// and will be set by the callee when the number of expansions is known.
6692   /// The callee must set this value when \c ShouldExpand is \c true; it may
6693   /// set this value in other cases.
6694   ///
6695   /// \returns true if an error occurred (e.g., because the parameter packs
6696   /// are to be instantiated with arguments of different lengths), false
6697   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
6698   /// must be set.
6699   bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
6700                                        SourceRange PatternRange,
6701                              ArrayRef<UnexpandedParameterPack> Unexpanded,
6702                              const MultiLevelTemplateArgumentList &TemplateArgs,
6703                                        bool &ShouldExpand,
6704                                        bool &RetainExpansion,
6705                                        Optional<unsigned> &NumExpansions);
6706
6707   /// \brief Determine the number of arguments in the given pack expansion
6708   /// type.
6709   ///
6710   /// This routine assumes that the number of arguments in the expansion is
6711   /// consistent across all of the unexpanded parameter packs in its pattern.
6712   ///
6713   /// Returns an empty Optional if the type can't be expanded.
6714   Optional<unsigned> getNumArgumentsInExpansion(QualType T,
6715       const MultiLevelTemplateArgumentList &TemplateArgs);
6716
6717   /// \brief Determine whether the given declarator contains any unexpanded
6718   /// parameter packs.
6719   ///
6720   /// This routine is used by the parser to disambiguate function declarators
6721   /// with an ellipsis prior to the ')', e.g.,
6722   ///
6723   /// \code
6724   ///   void f(T...);
6725   /// \endcode
6726   ///
6727   /// To determine whether we have an (unnamed) function parameter pack or
6728   /// a variadic function.
6729   ///
6730   /// \returns true if the declarator contains any unexpanded parameter packs,
6731   /// false otherwise.
6732   bool containsUnexpandedParameterPacks(Declarator &D);
6733
6734   /// \brief Returns the pattern of the pack expansion for a template argument.
6735   ///
6736   /// \param OrigLoc The template argument to expand.
6737   ///
6738   /// \param Ellipsis Will be set to the location of the ellipsis.
6739   ///
6740   /// \param NumExpansions Will be set to the number of expansions that will
6741   /// be generated from this pack expansion, if known a priori.
6742   TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
6743       TemplateArgumentLoc OrigLoc,
6744       SourceLocation &Ellipsis,
6745       Optional<unsigned> &NumExpansions) const;
6746
6747   /// Given a template argument that contains an unexpanded parameter pack, but
6748   /// which has already been substituted, attempt to determine the number of
6749   /// elements that will be produced once this argument is fully-expanded.
6750   ///
6751   /// This is intended for use when transforming 'sizeof...(Arg)' in order to
6752   /// avoid actually expanding the pack where possible.
6753   Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
6754
6755   //===--------------------------------------------------------------------===//
6756   // C++ Template Argument Deduction (C++ [temp.deduct])
6757   //===--------------------------------------------------------------------===//
6758
6759   /// Adjust the type \p ArgFunctionType to match the calling convention,
6760   /// noreturn, and optionally the exception specification of \p FunctionType.
6761   /// Deduction often wants to ignore these properties when matching function
6762   /// types.
6763   QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
6764                                bool AdjustExceptionSpec = false);
6765
6766   /// \brief Describes the result of template argument deduction.
6767   ///
6768   /// The TemplateDeductionResult enumeration describes the result of
6769   /// template argument deduction, as returned from
6770   /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
6771   /// structure provides additional information about the results of
6772   /// template argument deduction, e.g., the deduced template argument
6773   /// list (if successful) or the specific template parameters or
6774   /// deduced arguments that were involved in the failure.
6775   enum TemplateDeductionResult {
6776     /// \brief Template argument deduction was successful.
6777     TDK_Success = 0,
6778     /// \brief The declaration was invalid; do nothing.
6779     TDK_Invalid,
6780     /// \brief Template argument deduction exceeded the maximum template
6781     /// instantiation depth (which has already been diagnosed).
6782     TDK_InstantiationDepth,
6783     /// \brief Template argument deduction did not deduce a value
6784     /// for every template parameter.
6785     TDK_Incomplete,
6786     /// \brief Template argument deduction produced inconsistent
6787     /// deduced values for the given template parameter.
6788     TDK_Inconsistent,
6789     /// \brief Template argument deduction failed due to inconsistent
6790     /// cv-qualifiers on a template parameter type that would
6791     /// otherwise be deduced, e.g., we tried to deduce T in "const T"
6792     /// but were given a non-const "X".
6793     TDK_Underqualified,
6794     /// \brief Substitution of the deduced template argument values
6795     /// resulted in an error.
6796     TDK_SubstitutionFailure,
6797     /// \brief After substituting deduced template arguments, a dependent
6798     /// parameter type did not match the corresponding argument.
6799     TDK_DeducedMismatch,
6800     /// \brief After substituting deduced template arguments, an element of
6801     /// a dependent parameter type did not match the corresponding element
6802     /// of the corresponding argument (when deducing from an initializer list).
6803     TDK_DeducedMismatchNested,
6804     /// \brief A non-depnedent component of the parameter did not match the
6805     /// corresponding component of the argument.
6806     TDK_NonDeducedMismatch,
6807     /// \brief When performing template argument deduction for a function
6808     /// template, there were too many call arguments.
6809     TDK_TooManyArguments,
6810     /// \brief When performing template argument deduction for a function
6811     /// template, there were too few call arguments.
6812     TDK_TooFewArguments,
6813     /// \brief The explicitly-specified template arguments were not valid
6814     /// template arguments for the given template.
6815     TDK_InvalidExplicitArguments,
6816     /// \brief Checking non-dependent argument conversions failed.
6817     TDK_NonDependentConversionFailure,
6818     /// \brief Deduction failed; that's all we know.
6819     TDK_MiscellaneousDeductionFailure,
6820     /// \brief CUDA Target attributes do not match.
6821     TDK_CUDATargetMismatch
6822   };
6823
6824   TemplateDeductionResult
6825   DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
6826                           const TemplateArgumentList &TemplateArgs,
6827                           sema::TemplateDeductionInfo &Info);
6828
6829   TemplateDeductionResult
6830   DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
6831                           const TemplateArgumentList &TemplateArgs,
6832                           sema::TemplateDeductionInfo &Info);
6833
6834   TemplateDeductionResult SubstituteExplicitTemplateArguments(
6835       FunctionTemplateDecl *FunctionTemplate,
6836       TemplateArgumentListInfo &ExplicitTemplateArgs,
6837       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6838       SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
6839       sema::TemplateDeductionInfo &Info);
6840
6841   /// brief A function argument from which we performed template argument
6842   // deduction for a call.
6843   struct OriginalCallArg {
6844     OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
6845                     unsigned ArgIdx, QualType OriginalArgType)
6846         : OriginalParamType(OriginalParamType),
6847           DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
6848           OriginalArgType(OriginalArgType) {}
6849
6850     QualType OriginalParamType;
6851     bool DecomposedParam;
6852     unsigned ArgIdx;
6853     QualType OriginalArgType;
6854   };
6855
6856   TemplateDeductionResult FinishTemplateArgumentDeduction(
6857       FunctionTemplateDecl *FunctionTemplate,
6858       SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6859       unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
6860       sema::TemplateDeductionInfo &Info,
6861       SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
6862       bool PartialOverloading = false,
6863       llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
6864
6865   TemplateDeductionResult DeduceTemplateArguments(
6866       FunctionTemplateDecl *FunctionTemplate,
6867       TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6868       FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
6869       bool PartialOverloading,
6870       llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
6871
6872   TemplateDeductionResult
6873   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6874                           TemplateArgumentListInfo *ExplicitTemplateArgs,
6875                           QualType ArgFunctionType,
6876                           FunctionDecl *&Specialization,
6877                           sema::TemplateDeductionInfo &Info,
6878                           bool IsAddressOfFunction = false);
6879
6880   TemplateDeductionResult
6881   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6882                           QualType ToType,
6883                           CXXConversionDecl *&Specialization,
6884                           sema::TemplateDeductionInfo &Info);
6885
6886   TemplateDeductionResult
6887   DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
6888                           TemplateArgumentListInfo *ExplicitTemplateArgs,
6889                           FunctionDecl *&Specialization,
6890                           sema::TemplateDeductionInfo &Info,
6891                           bool IsAddressOfFunction = false);
6892
6893   /// \brief Substitute Replacement for \p auto in \p TypeWithAuto
6894   QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
6895   /// \brief Substitute Replacement for auto in TypeWithAuto
6896   TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
6897                                           QualType Replacement);
6898   /// \brief Completely replace the \c auto in \p TypeWithAuto by
6899   /// \p Replacement. This does not retain any \c auto type sugar.
6900   QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
6901
6902   /// \brief Result type of DeduceAutoType.
6903   enum DeduceAutoResult {
6904     DAR_Succeeded,
6905     DAR_Failed,
6906     DAR_FailedAlreadyDiagnosed
6907   };
6908
6909   DeduceAutoResult
6910   DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
6911                  Optional<unsigned> DependentDeductionDepth = None);
6912   DeduceAutoResult
6913   DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
6914                  Optional<unsigned> DependentDeductionDepth = None);
6915   void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
6916   bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
6917                         bool Diagnose = true);
6918
6919   /// \brief Declare implicit deduction guides for a class template if we've
6920   /// not already done so.
6921   void DeclareImplicitDeductionGuides(TemplateDecl *Template,
6922                                       SourceLocation Loc);
6923
6924   QualType DeduceTemplateSpecializationFromInitializer(
6925       TypeSourceInfo *TInfo, const InitializedEntity &Entity,
6926       const InitializationKind &Kind, MultiExprArg Init);
6927
6928   QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
6929                                         QualType Type, TypeSourceInfo *TSI,
6930                                         SourceRange Range, bool DirectInit,
6931                                         Expr *Init);
6932
6933   TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
6934
6935   bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
6936                                         SourceLocation ReturnLoc,
6937                                         Expr *&RetExpr, AutoType *AT);
6938
6939   FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
6940                                                    FunctionTemplateDecl *FT2,
6941                                                    SourceLocation Loc,
6942                                            TemplatePartialOrderingContext TPOC,
6943                                                    unsigned NumCallArguments1,
6944                                                    unsigned NumCallArguments2);
6945   UnresolvedSetIterator
6946   getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
6947                      TemplateSpecCandidateSet &FailedCandidates,
6948                      SourceLocation Loc,
6949                      const PartialDiagnostic &NoneDiag,
6950                      const PartialDiagnostic &AmbigDiag,
6951                      const PartialDiagnostic &CandidateDiag,
6952                      bool Complain = true, QualType TargetType = QualType());
6953
6954   ClassTemplatePartialSpecializationDecl *
6955   getMoreSpecializedPartialSpecialization(
6956                                   ClassTemplatePartialSpecializationDecl *PS1,
6957                                   ClassTemplatePartialSpecializationDecl *PS2,
6958                                   SourceLocation Loc);
6959
6960   bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
6961                                     sema::TemplateDeductionInfo &Info);
6962
6963   VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
6964       VarTemplatePartialSpecializationDecl *PS1,
6965       VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
6966
6967   bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
6968                                     sema::TemplateDeductionInfo &Info);
6969
6970   bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
6971       TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc);
6972
6973   void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
6974                                   bool OnlyDeduced,
6975                                   unsigned Depth,
6976                                   llvm::SmallBitVector &Used);
6977   void MarkDeducedTemplateParameters(
6978                                   const FunctionTemplateDecl *FunctionTemplate,
6979                                   llvm::SmallBitVector &Deduced) {
6980     return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
6981   }
6982   static void MarkDeducedTemplateParameters(ASTContext &Ctx,
6983                                   const FunctionTemplateDecl *FunctionTemplate,
6984                                   llvm::SmallBitVector &Deduced);
6985
6986   //===--------------------------------------------------------------------===//
6987   // C++ Template Instantiation
6988   //
6989
6990   MultiLevelTemplateArgumentList
6991   getTemplateInstantiationArgs(NamedDecl *D,
6992                                const TemplateArgumentList *Innermost = nullptr,
6993                                bool RelativeToPrimary = false,
6994                                const FunctionDecl *Pattern = nullptr);
6995
6996   /// A context in which code is being synthesized (where a source location
6997   /// alone is not sufficient to identify the context). This covers template
6998   /// instantiation and various forms of implicitly-generated functions.
6999   struct CodeSynthesisContext {
7000     /// \brief The kind of template instantiation we are performing
7001     enum SynthesisKind {
7002       /// We are instantiating a template declaration. The entity is
7003       /// the declaration we're instantiating (e.g., a CXXRecordDecl).
7004       TemplateInstantiation,
7005
7006       /// We are instantiating a default argument for a template
7007       /// parameter. The Entity is the template parameter whose argument is
7008       /// being instantiated, the Template is the template, and the
7009       /// TemplateArgs/NumTemplateArguments provide the template arguments as
7010       /// specified.
7011       DefaultTemplateArgumentInstantiation,
7012
7013       /// We are instantiating a default argument for a function.
7014       /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
7015       /// provides the template arguments as specified.
7016       DefaultFunctionArgumentInstantiation,
7017
7018       /// We are substituting explicit template arguments provided for
7019       /// a function template. The entity is a FunctionTemplateDecl.
7020       ExplicitTemplateArgumentSubstitution,
7021
7022       /// We are substituting template argument determined as part of
7023       /// template argument deduction for either a class template
7024       /// partial specialization or a function template. The
7025       /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
7026       /// a TemplateDecl.
7027       DeducedTemplateArgumentSubstitution,
7028
7029       /// We are substituting prior template arguments into a new
7030       /// template parameter. The template parameter itself is either a
7031       /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
7032       PriorTemplateArgumentSubstitution,
7033
7034       /// We are checking the validity of a default template argument that
7035       /// has been used when naming a template-id.
7036       DefaultTemplateArgumentChecking,
7037
7038       /// We are instantiating the exception specification for a function
7039       /// template which was deferred until it was needed.
7040       ExceptionSpecInstantiation,
7041
7042       /// We are declaring an implicit special member function.
7043       DeclaringSpecialMember,
7044
7045       /// We are defining a synthesized function (such as a defaulted special
7046       /// member).
7047       DefiningSynthesizedFunction,
7048     } Kind;
7049
7050     /// \brief Was the enclosing context a non-instantiation SFINAE context?
7051     bool SavedInNonInstantiationSFINAEContext;
7052
7053     /// \brief The point of instantiation or synthesis within the source code.
7054     SourceLocation PointOfInstantiation;
7055
7056     /// \brief The entity that is being synthesized.
7057     Decl *Entity;
7058
7059     /// \brief The template (or partial specialization) in which we are
7060     /// performing the instantiation, for substitutions of prior template
7061     /// arguments.
7062     NamedDecl *Template;
7063
7064     /// \brief The list of template arguments we are substituting, if they
7065     /// are not part of the entity.
7066     const TemplateArgument *TemplateArgs;
7067
7068     // FIXME: Wrap this union around more members, or perhaps store the
7069     // kind-specific members in the RAII object owning the context.
7070     union {
7071       /// \brief The number of template arguments in TemplateArgs.
7072       unsigned NumTemplateArgs;
7073
7074       /// \brief The special member being declared or defined.
7075       CXXSpecialMember SpecialMember;
7076     };
7077
7078     ArrayRef<TemplateArgument> template_arguments() const {
7079       assert(Kind != DeclaringSpecialMember);
7080       return {TemplateArgs, NumTemplateArgs};
7081     }
7082
7083     /// \brief The template deduction info object associated with the
7084     /// substitution or checking of explicit or deduced template arguments.
7085     sema::TemplateDeductionInfo *DeductionInfo;
7086
7087     /// \brief The source range that covers the construct that cause
7088     /// the instantiation, e.g., the template-id that causes a class
7089     /// template instantiation.
7090     SourceRange InstantiationRange;
7091
7092     CodeSynthesisContext()
7093       : Kind(TemplateInstantiation), Entity(nullptr), Template(nullptr),
7094         TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
7095
7096     /// \brief Determines whether this template is an actual instantiation
7097     /// that should be counted toward the maximum instantiation depth.
7098     bool isInstantiationRecord() const;
7099   };
7100
7101   /// \brief List of active code synthesis contexts.
7102   ///
7103   /// This vector is treated as a stack. As synthesis of one entity requires
7104   /// synthesis of another, additional contexts are pushed onto the stack.
7105   SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
7106
7107   /// Specializations whose definitions are currently being instantiated.
7108   llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
7109
7110   /// Non-dependent types used in templates that have already been instantiated
7111   /// by some template instantiation.
7112   llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
7113
7114   /// \brief Extra modules inspected when performing a lookup during a template
7115   /// instantiation. Computed lazily.
7116   SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
7117
7118   /// \brief Cache of additional modules that should be used for name lookup
7119   /// within the current template instantiation. Computed lazily; use
7120   /// getLookupModules() to get a complete set.
7121   llvm::DenseSet<Module*> LookupModulesCache;
7122
7123   /// \brief Get the set of additional modules that should be checked during
7124   /// name lookup. A module and its imports become visible when instanting a
7125   /// template defined within it.
7126   llvm::DenseSet<Module*> &getLookupModules();
7127
7128   /// \brief Map from the most recent declaration of a namespace to the most
7129   /// recent visible declaration of that namespace.
7130   llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
7131
7132   /// \brief Whether we are in a SFINAE context that is not associated with
7133   /// template instantiation.
7134   ///
7135   /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
7136   /// of a template instantiation or template argument deduction.
7137   bool InNonInstantiationSFINAEContext;
7138
7139   /// \brief The number of \p CodeSynthesisContexts that are not template
7140   /// instantiations and, therefore, should not be counted as part of the
7141   /// instantiation depth.
7142   ///
7143   /// When the instantiation depth reaches the user-configurable limit
7144   /// \p LangOptions::InstantiationDepth we will abort instantiation.
7145   // FIXME: Should we have a similar limit for other forms of synthesis?
7146   unsigned NonInstantiationEntries;
7147
7148   /// \brief The depth of the context stack at the point when the most recent
7149   /// error or warning was produced.
7150   ///
7151   /// This value is used to suppress printing of redundant context stacks
7152   /// when there are multiple errors or warnings in the same instantiation.
7153   // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
7154   unsigned LastEmittedCodeSynthesisContextDepth = 0;
7155
7156   /// \brief The current index into pack expansion arguments that will be
7157   /// used for substitution of parameter packs.
7158   ///
7159   /// The pack expansion index will be -1 to indicate that parameter packs
7160   /// should be instantiated as themselves. Otherwise, the index specifies
7161   /// which argument within the parameter pack will be used for substitution.
7162   int ArgumentPackSubstitutionIndex;
7163
7164   /// \brief RAII object used to change the argument pack substitution index
7165   /// within a \c Sema object.
7166   ///
7167   /// See \c ArgumentPackSubstitutionIndex for more information.
7168   class ArgumentPackSubstitutionIndexRAII {
7169     Sema &Self;
7170     int OldSubstitutionIndex;
7171
7172   public:
7173     ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
7174       : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
7175       Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
7176     }
7177
7178     ~ArgumentPackSubstitutionIndexRAII() {
7179       Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
7180     }
7181   };
7182
7183   friend class ArgumentPackSubstitutionRAII;
7184
7185   /// \brief For each declaration that involved template argument deduction, the
7186   /// set of diagnostics that were suppressed during that template argument
7187   /// deduction.
7188   ///
7189   /// FIXME: Serialize this structure to the AST file.
7190   typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
7191     SuppressedDiagnosticsMap;
7192   SuppressedDiagnosticsMap SuppressedDiagnostics;
7193
7194   /// \brief A stack object to be created when performing template
7195   /// instantiation.
7196   ///
7197   /// Construction of an object of type \c InstantiatingTemplate
7198   /// pushes the current instantiation onto the stack of active
7199   /// instantiations. If the size of this stack exceeds the maximum
7200   /// number of recursive template instantiations, construction
7201   /// produces an error and evaluates true.
7202   ///
7203   /// Destruction of this object will pop the named instantiation off
7204   /// the stack.
7205   struct InstantiatingTemplate {
7206     /// \brief Note that we are instantiating a class template,
7207     /// function template, variable template, alias template,
7208     /// or a member thereof.
7209     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7210                           Decl *Entity,
7211                           SourceRange InstantiationRange = SourceRange());
7212
7213     struct ExceptionSpecification {};
7214     /// \brief Note that we are instantiating an exception specification
7215     /// of a function template.
7216     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7217                           FunctionDecl *Entity, ExceptionSpecification,
7218                           SourceRange InstantiationRange = SourceRange());
7219
7220     /// \brief Note that we are instantiating a default argument in a
7221     /// template-id.
7222     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7223                           TemplateParameter Param, TemplateDecl *Template,
7224                           ArrayRef<TemplateArgument> TemplateArgs,
7225                           SourceRange InstantiationRange = SourceRange());
7226
7227     /// \brief Note that we are substituting either explicitly-specified or
7228     /// deduced template arguments during function template argument deduction.
7229     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7230                           FunctionTemplateDecl *FunctionTemplate,
7231                           ArrayRef<TemplateArgument> TemplateArgs,
7232                           CodeSynthesisContext::SynthesisKind Kind,
7233                           sema::TemplateDeductionInfo &DeductionInfo,
7234                           SourceRange InstantiationRange = SourceRange());
7235
7236     /// \brief Note that we are instantiating as part of template
7237     /// argument deduction for a class template declaration.
7238     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7239                           TemplateDecl *Template,
7240                           ArrayRef<TemplateArgument> TemplateArgs,
7241                           sema::TemplateDeductionInfo &DeductionInfo,
7242                           SourceRange InstantiationRange = SourceRange());
7243
7244     /// \brief Note that we are instantiating as part of template
7245     /// argument deduction for a class template partial
7246     /// specialization.
7247     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7248                           ClassTemplatePartialSpecializationDecl *PartialSpec,
7249                           ArrayRef<TemplateArgument> TemplateArgs,
7250                           sema::TemplateDeductionInfo &DeductionInfo,
7251                           SourceRange InstantiationRange = SourceRange());
7252
7253     /// \brief Note that we are instantiating as part of template
7254     /// argument deduction for a variable template partial
7255     /// specialization.
7256     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7257                           VarTemplatePartialSpecializationDecl *PartialSpec,
7258                           ArrayRef<TemplateArgument> TemplateArgs,
7259                           sema::TemplateDeductionInfo &DeductionInfo,
7260                           SourceRange InstantiationRange = SourceRange());
7261
7262     /// \brief Note that we are instantiating a default argument for a function
7263     /// parameter.
7264     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7265                           ParmVarDecl *Param,
7266                           ArrayRef<TemplateArgument> TemplateArgs,
7267                           SourceRange InstantiationRange = SourceRange());
7268
7269     /// \brief Note that we are substituting prior template arguments into a
7270     /// non-type parameter.
7271     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7272                           NamedDecl *Template,
7273                           NonTypeTemplateParmDecl *Param,
7274                           ArrayRef<TemplateArgument> TemplateArgs,
7275                           SourceRange InstantiationRange);
7276
7277     /// \brief Note that we are substituting prior template arguments into a
7278     /// template template parameter.
7279     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7280                           NamedDecl *Template,
7281                           TemplateTemplateParmDecl *Param,
7282                           ArrayRef<TemplateArgument> TemplateArgs,
7283                           SourceRange InstantiationRange);
7284
7285     /// \brief Note that we are checking the default template argument
7286     /// against the template parameter for a given template-id.
7287     InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
7288                           TemplateDecl *Template,
7289                           NamedDecl *Param,
7290                           ArrayRef<TemplateArgument> TemplateArgs,
7291                           SourceRange InstantiationRange);
7292
7293
7294     /// \brief Note that we have finished instantiating this template.
7295     void Clear();
7296
7297     ~InstantiatingTemplate() { Clear(); }
7298
7299     /// \brief Determines whether we have exceeded the maximum
7300     /// recursive template instantiations.
7301     bool isInvalid() const { return Invalid; }
7302
7303     /// \brief Determine whether we are already instantiating this
7304     /// specialization in some surrounding active instantiation.
7305     bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
7306
7307   private:
7308     Sema &SemaRef;
7309     bool Invalid;
7310     bool AlreadyInstantiating;
7311     bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
7312                                  SourceRange InstantiationRange);
7313
7314     InstantiatingTemplate(
7315         Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
7316         SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
7317         Decl *Entity, NamedDecl *Template = nullptr,
7318         ArrayRef<TemplateArgument> TemplateArgs = None,
7319         sema::TemplateDeductionInfo *DeductionInfo = nullptr);
7320
7321     InstantiatingTemplate(const InstantiatingTemplate&) = delete;
7322
7323     InstantiatingTemplate&
7324     operator=(const InstantiatingTemplate&) = delete;
7325   };
7326
7327   void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
7328   void popCodeSynthesisContext();
7329
7330   /// Determine whether we are currently performing template instantiation.
7331   bool inTemplateInstantiation() const {
7332     return CodeSynthesisContexts.size() > NonInstantiationEntries;
7333   }
7334
7335   void PrintContextStack() {
7336     if (!CodeSynthesisContexts.empty() &&
7337         CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
7338       PrintInstantiationStack();
7339       LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
7340     }
7341     if (PragmaAttributeCurrentTargetDecl)
7342       PrintPragmaAttributeInstantiationPoint();
7343   }
7344   void PrintInstantiationStack();
7345
7346   void PrintPragmaAttributeInstantiationPoint();
7347
7348   /// \brief Determines whether we are currently in a context where
7349   /// template argument substitution failures are not considered
7350   /// errors.
7351   ///
7352   /// \returns An empty \c Optional if we're not in a SFINAE context.
7353   /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
7354   /// template-deduction context object, which can be used to capture
7355   /// diagnostics that will be suppressed.
7356   Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
7357
7358   /// \brief Determines whether we are currently in a context that
7359   /// is not evaluated as per C++ [expr] p5.
7360   bool isUnevaluatedContext() const {
7361     assert(!ExprEvalContexts.empty() &&
7362            "Must be in an expression evaluation context");
7363     return ExprEvalContexts.back().isUnevaluated();
7364   }
7365
7366   /// \brief RAII class used to determine whether SFINAE has
7367   /// trapped any errors that occur during template argument
7368   /// deduction.
7369   class SFINAETrap {
7370     Sema &SemaRef;
7371     unsigned PrevSFINAEErrors;
7372     bool PrevInNonInstantiationSFINAEContext;
7373     bool PrevAccessCheckingSFINAE;
7374
7375   public:
7376     explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
7377       : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
7378         PrevInNonInstantiationSFINAEContext(
7379                                       SemaRef.InNonInstantiationSFINAEContext),
7380         PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
7381     {
7382       if (!SemaRef.isSFINAEContext())
7383         SemaRef.InNonInstantiationSFINAEContext = true;
7384       SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
7385     }
7386
7387     ~SFINAETrap() {
7388       SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
7389       SemaRef.InNonInstantiationSFINAEContext
7390         = PrevInNonInstantiationSFINAEContext;
7391       SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
7392     }
7393
7394     /// \brief Determine whether any SFINAE errors have been trapped.
7395     bool hasErrorOccurred() const {
7396       return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
7397     }
7398   };
7399
7400   /// \brief RAII class used to indicate that we are performing provisional
7401   /// semantic analysis to determine the validity of a construct, so
7402   /// typo-correction and diagnostics in the immediate context (not within
7403   /// implicitly-instantiated templates) should be suppressed.
7404   class TentativeAnalysisScope {
7405     Sema &SemaRef;
7406     // FIXME: Using a SFINAETrap for this is a hack.
7407     SFINAETrap Trap;
7408     bool PrevDisableTypoCorrection;
7409   public:
7410     explicit TentativeAnalysisScope(Sema &SemaRef)
7411         : SemaRef(SemaRef), Trap(SemaRef, true),
7412           PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
7413       SemaRef.DisableTypoCorrection = true;
7414     }
7415     ~TentativeAnalysisScope() {
7416       SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
7417     }
7418   };
7419
7420   /// \brief The current instantiation scope used to store local
7421   /// variables.
7422   LocalInstantiationScope *CurrentInstantiationScope;
7423
7424   /// \brief Tracks whether we are in a context where typo correction is
7425   /// disabled.
7426   bool DisableTypoCorrection;
7427
7428   /// \brief The number of typos corrected by CorrectTypo.
7429   unsigned TyposCorrected;
7430
7431   typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
7432   typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
7433
7434   /// \brief A cache containing identifiers for which typo correction failed and
7435   /// their locations, so that repeated attempts to correct an identifier in a
7436   /// given location are ignored if typo correction already failed for it.
7437   IdentifierSourceLocations TypoCorrectionFailures;
7438
7439   /// \brief Worker object for performing CFG-based warnings.
7440   sema::AnalysisBasedWarnings AnalysisWarnings;
7441   threadSafety::BeforeSet *ThreadSafetyDeclCache;
7442
7443   /// \brief An entity for which implicit template instantiation is required.
7444   ///
7445   /// The source location associated with the declaration is the first place in
7446   /// the source code where the declaration was "used". It is not necessarily
7447   /// the point of instantiation (which will be either before or after the
7448   /// namespace-scope declaration that triggered this implicit instantiation),
7449   /// However, it is the location that diagnostics should generally refer to,
7450   /// because users will need to know what code triggered the instantiation.
7451   typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
7452
7453   /// \brief The queue of implicit template instantiations that are required
7454   /// but have not yet been performed.
7455   std::deque<PendingImplicitInstantiation> PendingInstantiations;
7456
7457   class GlobalEagerInstantiationScope {
7458   public:
7459     GlobalEagerInstantiationScope(Sema &S, bool Enabled)
7460         : S(S), Enabled(Enabled) {
7461       if (!Enabled) return;
7462
7463       SavedPendingInstantiations.swap(S.PendingInstantiations);
7464       SavedVTableUses.swap(S.VTableUses);
7465     }
7466
7467     void perform() {
7468       if (Enabled) {
7469         S.DefineUsedVTables();
7470         S.PerformPendingInstantiations();
7471       }
7472     }
7473
7474     ~GlobalEagerInstantiationScope() {
7475       if (!Enabled) return;
7476
7477       // Restore the set of pending vtables.
7478       assert(S.VTableUses.empty() &&
7479              "VTableUses should be empty before it is discarded.");
7480       S.VTableUses.swap(SavedVTableUses);
7481
7482       // Restore the set of pending implicit instantiations.
7483       assert(S.PendingInstantiations.empty() &&
7484              "PendingInstantiations should be empty before it is discarded.");
7485       S.PendingInstantiations.swap(SavedPendingInstantiations);
7486     }
7487
7488   private:
7489     Sema &S;
7490     SmallVector<VTableUse, 16> SavedVTableUses;
7491     std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
7492     bool Enabled;
7493   };
7494
7495   /// \brief The queue of implicit template instantiations that are required
7496   /// and must be performed within the current local scope.
7497   ///
7498   /// This queue is only used for member functions of local classes in
7499   /// templates, which must be instantiated in the same scope as their
7500   /// enclosing function, so that they can reference function-local
7501   /// types, static variables, enumerators, etc.
7502   std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
7503
7504   class LocalEagerInstantiationScope {
7505   public:
7506     LocalEagerInstantiationScope(Sema &S) : S(S) {
7507       SavedPendingLocalImplicitInstantiations.swap(
7508           S.PendingLocalImplicitInstantiations);
7509     }
7510
7511     void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
7512
7513     ~LocalEagerInstantiationScope() {
7514       assert(S.PendingLocalImplicitInstantiations.empty() &&
7515              "there shouldn't be any pending local implicit instantiations");
7516       SavedPendingLocalImplicitInstantiations.swap(
7517           S.PendingLocalImplicitInstantiations);
7518     }
7519
7520   private:
7521     Sema &S;
7522     std::deque<PendingImplicitInstantiation>
7523         SavedPendingLocalImplicitInstantiations;
7524   };
7525
7526   /// A helper class for building up ExtParameterInfos.
7527   class ExtParameterInfoBuilder {
7528     SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
7529     bool HasInteresting = false;
7530
7531   public:
7532     /// Set the ExtParameterInfo for the parameter at the given index,
7533     ///
7534     void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
7535       assert(Infos.size() <= index);
7536       Infos.resize(index);
7537       Infos.push_back(info);
7538
7539       if (!HasInteresting)
7540         HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
7541     }
7542
7543     /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
7544     /// ExtParameterInfo array we've built up.
7545     const FunctionProtoType::ExtParameterInfo *
7546     getPointerOrNull(unsigned numParams) {
7547       if (!HasInteresting) return nullptr;
7548       Infos.resize(numParams);
7549       return Infos.data();
7550     }
7551   };
7552
7553   void PerformPendingInstantiations(bool LocalOnly = false);
7554
7555   TypeSourceInfo *SubstType(TypeSourceInfo *T,
7556                             const MultiLevelTemplateArgumentList &TemplateArgs,
7557                             SourceLocation Loc, DeclarationName Entity,
7558                             bool AllowDeducedTST = false);
7559
7560   QualType SubstType(QualType T,
7561                      const MultiLevelTemplateArgumentList &TemplateArgs,
7562                      SourceLocation Loc, DeclarationName Entity);
7563
7564   TypeSourceInfo *SubstType(TypeLoc TL,
7565                             const MultiLevelTemplateArgumentList &TemplateArgs,
7566                             SourceLocation Loc, DeclarationName Entity);
7567
7568   TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
7569                             const MultiLevelTemplateArgumentList &TemplateArgs,
7570                                         SourceLocation Loc,
7571                                         DeclarationName Entity,
7572                                         CXXRecordDecl *ThisContext,
7573                                         unsigned ThisTypeQuals);
7574   void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
7575                           const MultiLevelTemplateArgumentList &Args);
7576   bool SubstExceptionSpec(SourceLocation Loc,
7577                           FunctionProtoType::ExceptionSpecInfo &ESI,
7578                           SmallVectorImpl<QualType> &ExceptionStorage,
7579                           const MultiLevelTemplateArgumentList &Args);
7580   ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
7581                             const MultiLevelTemplateArgumentList &TemplateArgs,
7582                                 int indexAdjustment,
7583                                 Optional<unsigned> NumExpansions,
7584                                 bool ExpectParameterPack);
7585   bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
7586                       const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
7587                       const MultiLevelTemplateArgumentList &TemplateArgs,
7588                       SmallVectorImpl<QualType> &ParamTypes,
7589                       SmallVectorImpl<ParmVarDecl *> *OutParams,
7590                       ExtParameterInfoBuilder &ParamInfos);
7591   ExprResult SubstExpr(Expr *E,
7592                        const MultiLevelTemplateArgumentList &TemplateArgs);
7593
7594   /// \brief Substitute the given template arguments into a list of
7595   /// expressions, expanding pack expansions if required.
7596   ///
7597   /// \param Exprs The list of expressions to substitute into.
7598   ///
7599   /// \param IsCall Whether this is some form of call, in which case
7600   /// default arguments will be dropped.
7601   ///
7602   /// \param TemplateArgs The set of template arguments to substitute.
7603   ///
7604   /// \param Outputs Will receive all of the substituted arguments.
7605   ///
7606   /// \returns true if an error occurred, false otherwise.
7607   bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
7608                   const MultiLevelTemplateArgumentList &TemplateArgs,
7609                   SmallVectorImpl<Expr *> &Outputs);
7610
7611   StmtResult SubstStmt(Stmt *S,
7612                        const MultiLevelTemplateArgumentList &TemplateArgs);
7613
7614   Decl *SubstDecl(Decl *D, DeclContext *Owner,
7615                   const MultiLevelTemplateArgumentList &TemplateArgs);
7616
7617   ExprResult SubstInitializer(Expr *E,
7618                        const MultiLevelTemplateArgumentList &TemplateArgs,
7619                        bool CXXDirectInit);
7620
7621   bool
7622   SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
7623                       CXXRecordDecl *Pattern,
7624                       const MultiLevelTemplateArgumentList &TemplateArgs);
7625
7626   bool
7627   InstantiateClass(SourceLocation PointOfInstantiation,
7628                    CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
7629                    const MultiLevelTemplateArgumentList &TemplateArgs,
7630                    TemplateSpecializationKind TSK,
7631                    bool Complain = true);
7632
7633   bool InstantiateEnum(SourceLocation PointOfInstantiation,
7634                        EnumDecl *Instantiation, EnumDecl *Pattern,
7635                        const MultiLevelTemplateArgumentList &TemplateArgs,
7636                        TemplateSpecializationKind TSK);
7637
7638   bool InstantiateInClassInitializer(
7639       SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
7640       FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
7641
7642   struct LateInstantiatedAttribute {
7643     const Attr *TmplAttr;
7644     LocalInstantiationScope *Scope;
7645     Decl *NewDecl;
7646
7647     LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
7648                               Decl *D)
7649       : TmplAttr(A), Scope(S), NewDecl(D)
7650     { }
7651   };
7652   typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
7653
7654   void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
7655                         const Decl *Pattern, Decl *Inst,
7656                         LateInstantiatedAttrVec *LateAttrs = nullptr,
7657                         LocalInstantiationScope *OuterMostScope = nullptr);
7658
7659   void
7660   InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
7661                           const Decl *Pattern, Decl *Inst,
7662                           LateInstantiatedAttrVec *LateAttrs = nullptr,
7663                           LocalInstantiationScope *OuterMostScope = nullptr);
7664
7665   bool usesPartialOrExplicitSpecialization(
7666       SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
7667
7668   bool
7669   InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
7670                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
7671                            TemplateSpecializationKind TSK,
7672                            bool Complain = true);
7673
7674   void InstantiateClassMembers(SourceLocation PointOfInstantiation,
7675                                CXXRecordDecl *Instantiation,
7676                             const MultiLevelTemplateArgumentList &TemplateArgs,
7677                                TemplateSpecializationKind TSK);
7678
7679   void InstantiateClassTemplateSpecializationMembers(
7680                                           SourceLocation PointOfInstantiation,
7681                            ClassTemplateSpecializationDecl *ClassTemplateSpec,
7682                                                 TemplateSpecializationKind TSK);
7683
7684   NestedNameSpecifierLoc
7685   SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
7686                            const MultiLevelTemplateArgumentList &TemplateArgs);
7687
7688   DeclarationNameInfo
7689   SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
7690                            const MultiLevelTemplateArgumentList &TemplateArgs);
7691   TemplateName
7692   SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
7693                     SourceLocation Loc,
7694                     const MultiLevelTemplateArgumentList &TemplateArgs);
7695   bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
7696              TemplateArgumentListInfo &Result,
7697              const MultiLevelTemplateArgumentList &TemplateArgs);
7698
7699   void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
7700                                 FunctionDecl *Function);
7701   void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
7702                                      FunctionDecl *Function,
7703                                      bool Recursive = false,
7704                                      bool DefinitionRequired = false,
7705                                      bool AtEndOfTU = false);
7706   VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
7707       VarTemplateDecl *VarTemplate, VarDecl *FromVar,
7708       const TemplateArgumentList &TemplateArgList,
7709       const TemplateArgumentListInfo &TemplateArgsInfo,
7710       SmallVectorImpl<TemplateArgument> &Converted,
7711       SourceLocation PointOfInstantiation, void *InsertPos,
7712       LateInstantiatedAttrVec *LateAttrs = nullptr,
7713       LocalInstantiationScope *StartingScope = nullptr);
7714   VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
7715       VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
7716       const MultiLevelTemplateArgumentList &TemplateArgs);
7717   void
7718   BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
7719                              const MultiLevelTemplateArgumentList &TemplateArgs,
7720                              LateInstantiatedAttrVec *LateAttrs,
7721                              DeclContext *Owner,
7722                              LocalInstantiationScope *StartingScope,
7723                              bool InstantiatingVarTemplate = false);
7724   void InstantiateVariableInitializer(
7725       VarDecl *Var, VarDecl *OldVar,
7726       const MultiLevelTemplateArgumentList &TemplateArgs);
7727   void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
7728                                      VarDecl *Var, bool Recursive = false,
7729                                      bool DefinitionRequired = false,
7730                                      bool AtEndOfTU = false);
7731   void InstantiateStaticDataMemberDefinition(
7732                                      SourceLocation PointOfInstantiation,
7733                                      VarDecl *Var,
7734                                      bool Recursive = false,
7735                                      bool DefinitionRequired = false);
7736
7737   void InstantiateMemInitializers(CXXConstructorDecl *New,
7738                                   const CXXConstructorDecl *Tmpl,
7739                             const MultiLevelTemplateArgumentList &TemplateArgs);
7740
7741   NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
7742                           const MultiLevelTemplateArgumentList &TemplateArgs,
7743                           bool FindingInstantiatedContext = false);
7744   DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
7745                           const MultiLevelTemplateArgumentList &TemplateArgs);
7746
7747   // Objective-C declarations.
7748   enum ObjCContainerKind {
7749     OCK_None = -1,
7750     OCK_Interface = 0,
7751     OCK_Protocol,
7752     OCK_Category,
7753     OCK_ClassExtension,
7754     OCK_Implementation,
7755     OCK_CategoryImplementation
7756   };
7757   ObjCContainerKind getObjCContainerKind() const;
7758
7759   DeclResult actOnObjCTypeParam(Scope *S,
7760                                 ObjCTypeParamVariance variance,
7761                                 SourceLocation varianceLoc,
7762                                 unsigned index,
7763                                 IdentifierInfo *paramName,
7764                                 SourceLocation paramLoc,
7765                                 SourceLocation colonLoc,
7766                                 ParsedType typeBound);
7767
7768   ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
7769                                             ArrayRef<Decl *> typeParams,
7770                                             SourceLocation rAngleLoc);
7771   void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
7772
7773   Decl *ActOnStartClassInterface(Scope *S,
7774                                  SourceLocation AtInterfaceLoc,
7775                                  IdentifierInfo *ClassName,
7776                                  SourceLocation ClassLoc,
7777                                  ObjCTypeParamList *typeParamList,
7778                                  IdentifierInfo *SuperName,
7779                                  SourceLocation SuperLoc,
7780                                  ArrayRef<ParsedType> SuperTypeArgs,
7781                                  SourceRange SuperTypeArgsRange,
7782                                  Decl * const *ProtoRefs,
7783                                  unsigned NumProtoRefs,
7784                                  const SourceLocation *ProtoLocs,
7785                                  SourceLocation EndProtoLoc,
7786                                  AttributeList *AttrList);
7787
7788   void ActOnSuperClassOfClassInterface(Scope *S,
7789                                        SourceLocation AtInterfaceLoc,
7790                                        ObjCInterfaceDecl *IDecl,
7791                                        IdentifierInfo *ClassName,
7792                                        SourceLocation ClassLoc,
7793                                        IdentifierInfo *SuperName,
7794                                        SourceLocation SuperLoc,
7795                                        ArrayRef<ParsedType> SuperTypeArgs,
7796                                        SourceRange SuperTypeArgsRange);
7797
7798   void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
7799                                SmallVectorImpl<SourceLocation> &ProtocolLocs,
7800                                IdentifierInfo *SuperName,
7801                                SourceLocation SuperLoc);
7802
7803   Decl *ActOnCompatibilityAlias(
7804                     SourceLocation AtCompatibilityAliasLoc,
7805                     IdentifierInfo *AliasName,  SourceLocation AliasLocation,
7806                     IdentifierInfo *ClassName, SourceLocation ClassLocation);
7807
7808   bool CheckForwardProtocolDeclarationForCircularDependency(
7809     IdentifierInfo *PName,
7810     SourceLocation &PLoc, SourceLocation PrevLoc,
7811     const ObjCList<ObjCProtocolDecl> &PList);
7812
7813   Decl *ActOnStartProtocolInterface(
7814                     SourceLocation AtProtoInterfaceLoc,
7815                     IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
7816                     Decl * const *ProtoRefNames, unsigned NumProtoRefs,
7817                     const SourceLocation *ProtoLocs,
7818                     SourceLocation EndProtoLoc,
7819                     AttributeList *AttrList);
7820
7821   Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
7822                                     IdentifierInfo *ClassName,
7823                                     SourceLocation ClassLoc,
7824                                     ObjCTypeParamList *typeParamList,
7825                                     IdentifierInfo *CategoryName,
7826                                     SourceLocation CategoryLoc,
7827                                     Decl * const *ProtoRefs,
7828                                     unsigned NumProtoRefs,
7829                                     const SourceLocation *ProtoLocs,
7830                                     SourceLocation EndProtoLoc,
7831                                     AttributeList *AttrList);
7832
7833   Decl *ActOnStartClassImplementation(
7834                     SourceLocation AtClassImplLoc,
7835                     IdentifierInfo *ClassName, SourceLocation ClassLoc,
7836                     IdentifierInfo *SuperClassname,
7837                     SourceLocation SuperClassLoc);
7838
7839   Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
7840                                          IdentifierInfo *ClassName,
7841                                          SourceLocation ClassLoc,
7842                                          IdentifierInfo *CatName,
7843                                          SourceLocation CatLoc);
7844
7845   DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
7846                                                ArrayRef<Decl *> Decls);
7847
7848   DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
7849                    IdentifierInfo **IdentList,
7850                    SourceLocation *IdentLocs,
7851                    ArrayRef<ObjCTypeParamList *> TypeParamLists,
7852                    unsigned NumElts);
7853
7854   DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
7855                                         ArrayRef<IdentifierLocPair> IdentList,
7856                                         AttributeList *attrList);
7857
7858   void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
7859                                ArrayRef<IdentifierLocPair> ProtocolId,
7860                                SmallVectorImpl<Decl *> &Protocols);
7861
7862   void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
7863                                     SourceLocation ProtocolLoc,
7864                                     IdentifierInfo *TypeArgId,
7865                                     SourceLocation TypeArgLoc,
7866                                     bool SelectProtocolFirst = false);
7867
7868   /// Given a list of identifiers (and their locations), resolve the
7869   /// names to either Objective-C protocol qualifiers or type
7870   /// arguments, as appropriate.
7871   void actOnObjCTypeArgsOrProtocolQualifiers(
7872          Scope *S,
7873          ParsedType baseType,
7874          SourceLocation lAngleLoc,
7875          ArrayRef<IdentifierInfo *> identifiers,
7876          ArrayRef<SourceLocation> identifierLocs,
7877          SourceLocation rAngleLoc,
7878          SourceLocation &typeArgsLAngleLoc,
7879          SmallVectorImpl<ParsedType> &typeArgs,
7880          SourceLocation &typeArgsRAngleLoc,
7881          SourceLocation &protocolLAngleLoc,
7882          SmallVectorImpl<Decl *> &protocols,
7883          SourceLocation &protocolRAngleLoc,
7884          bool warnOnIncompleteProtocols);
7885
7886   /// Build a an Objective-C protocol-qualified 'id' type where no
7887   /// base type was specified.
7888   TypeResult actOnObjCProtocolQualifierType(
7889                SourceLocation lAngleLoc,
7890                ArrayRef<Decl *> protocols,
7891                ArrayRef<SourceLocation> protocolLocs,
7892                SourceLocation rAngleLoc);
7893
7894   /// Build a specialized and/or protocol-qualified Objective-C type.
7895   TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
7896                Scope *S,
7897                SourceLocation Loc,
7898                ParsedType BaseType,
7899                SourceLocation TypeArgsLAngleLoc,
7900                ArrayRef<ParsedType> TypeArgs,
7901                SourceLocation TypeArgsRAngleLoc,
7902                SourceLocation ProtocolLAngleLoc,
7903                ArrayRef<Decl *> Protocols,
7904                ArrayRef<SourceLocation> ProtocolLocs,
7905                SourceLocation ProtocolRAngleLoc);
7906
7907   /// Build an Objective-C type parameter type.
7908   QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
7909                                   SourceLocation ProtocolLAngleLoc,
7910                                   ArrayRef<ObjCProtocolDecl *> Protocols,
7911                                   ArrayRef<SourceLocation> ProtocolLocs,
7912                                   SourceLocation ProtocolRAngleLoc,
7913                                   bool FailOnError = false);
7914
7915   /// Build an Objective-C object pointer type.
7916   QualType BuildObjCObjectType(QualType BaseType,
7917                                SourceLocation Loc,
7918                                SourceLocation TypeArgsLAngleLoc,
7919                                ArrayRef<TypeSourceInfo *> TypeArgs,
7920                                SourceLocation TypeArgsRAngleLoc,
7921                                SourceLocation ProtocolLAngleLoc,
7922                                ArrayRef<ObjCProtocolDecl *> Protocols,
7923                                ArrayRef<SourceLocation> ProtocolLocs,
7924                                SourceLocation ProtocolRAngleLoc,
7925                                bool FailOnError = false);
7926
7927   /// Check the application of the Objective-C '__kindof' qualifier to
7928   /// the given type.
7929   bool checkObjCKindOfType(QualType &type, SourceLocation loc);
7930
7931   /// Ensure attributes are consistent with type.
7932   /// \param [in, out] Attributes The attributes to check; they will
7933   /// be modified to be consistent with \p PropertyTy.
7934   void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
7935                                    SourceLocation Loc,
7936                                    unsigned &Attributes,
7937                                    bool propertyInPrimaryClass);
7938
7939   /// Process the specified property declaration and create decls for the
7940   /// setters and getters as needed.
7941   /// \param property The property declaration being processed
7942   void ProcessPropertyDecl(ObjCPropertyDecl *property);
7943
7944
7945   void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
7946                                 ObjCPropertyDecl *SuperProperty,
7947                                 const IdentifierInfo *Name,
7948                                 bool OverridingProtocolProperty);
7949
7950   void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
7951                                         ObjCInterfaceDecl *ID);
7952
7953   Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
7954                    ArrayRef<Decl *> allMethods = None,
7955                    ArrayRef<DeclGroupPtrTy> allTUVars = None);
7956
7957   Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
7958                       SourceLocation LParenLoc,
7959                       FieldDeclarator &FD, ObjCDeclSpec &ODS,
7960                       Selector GetterSel, Selector SetterSel,
7961                       tok::ObjCKeywordKind MethodImplKind,
7962                       DeclContext *lexicalDC = nullptr);
7963
7964   Decl *ActOnPropertyImplDecl(Scope *S,
7965                               SourceLocation AtLoc,
7966                               SourceLocation PropertyLoc,
7967                               bool ImplKind,
7968                               IdentifierInfo *PropertyId,
7969                               IdentifierInfo *PropertyIvar,
7970                               SourceLocation PropertyIvarLoc,
7971                               ObjCPropertyQueryKind QueryKind);
7972
7973   enum ObjCSpecialMethodKind {
7974     OSMK_None,
7975     OSMK_Alloc,
7976     OSMK_New,
7977     OSMK_Copy,
7978     OSMK_RetainingInit,
7979     OSMK_NonRetainingInit
7980   };
7981
7982   struct ObjCArgInfo {
7983     IdentifierInfo *Name;
7984     SourceLocation NameLoc;
7985     // The Type is null if no type was specified, and the DeclSpec is invalid
7986     // in this case.
7987     ParsedType Type;
7988     ObjCDeclSpec DeclSpec;
7989
7990     /// ArgAttrs - Attribute list for this argument.
7991     AttributeList *ArgAttrs;
7992   };
7993
7994   Decl *ActOnMethodDeclaration(
7995     Scope *S,
7996     SourceLocation BeginLoc, // location of the + or -.
7997     SourceLocation EndLoc,   // location of the ; or {.
7998     tok::TokenKind MethodType,
7999     ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
8000     ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
8001     // optional arguments. The number of types/arguments is obtained
8002     // from the Sel.getNumArgs().
8003     ObjCArgInfo *ArgInfo,
8004     DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
8005     AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
8006     bool isVariadic, bool MethodDefinition);
8007
8008   ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
8009                                               const ObjCObjectPointerType *OPT,
8010                                               bool IsInstance);
8011   ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
8012                                            bool IsInstance);
8013
8014   bool CheckARCMethodDecl(ObjCMethodDecl *method);
8015   bool inferObjCARCLifetime(ValueDecl *decl);
8016
8017   ExprResult
8018   HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
8019                             Expr *BaseExpr,
8020                             SourceLocation OpLoc,
8021                             DeclarationName MemberName,
8022                             SourceLocation MemberLoc,
8023                             SourceLocation SuperLoc, QualType SuperType,
8024                             bool Super);
8025
8026   ExprResult
8027   ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
8028                             IdentifierInfo &propertyName,
8029                             SourceLocation receiverNameLoc,
8030                             SourceLocation propertyNameLoc);
8031
8032   ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
8033
8034   /// \brief Describes the kind of message expression indicated by a message
8035   /// send that starts with an identifier.
8036   enum ObjCMessageKind {
8037     /// \brief The message is sent to 'super'.
8038     ObjCSuperMessage,
8039     /// \brief The message is an instance message.
8040     ObjCInstanceMessage,
8041     /// \brief The message is a class message, and the identifier is a type
8042     /// name.
8043     ObjCClassMessage
8044   };
8045
8046   ObjCMessageKind getObjCMessageKind(Scope *S,
8047                                      IdentifierInfo *Name,
8048                                      SourceLocation NameLoc,
8049                                      bool IsSuper,
8050                                      bool HasTrailingDot,
8051                                      ParsedType &ReceiverType);
8052
8053   ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
8054                                Selector Sel,
8055                                SourceLocation LBracLoc,
8056                                ArrayRef<SourceLocation> SelectorLocs,
8057                                SourceLocation RBracLoc,
8058                                MultiExprArg Args);
8059
8060   ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
8061                                QualType ReceiverType,
8062                                SourceLocation SuperLoc,
8063                                Selector Sel,
8064                                ObjCMethodDecl *Method,
8065                                SourceLocation LBracLoc,
8066                                ArrayRef<SourceLocation> SelectorLocs,
8067                                SourceLocation RBracLoc,
8068                                MultiExprArg Args,
8069                                bool isImplicit = false);
8070
8071   ExprResult BuildClassMessageImplicit(QualType ReceiverType,
8072                                        bool isSuperReceiver,
8073                                        SourceLocation Loc,
8074                                        Selector Sel,
8075                                        ObjCMethodDecl *Method,
8076                                        MultiExprArg Args);
8077
8078   ExprResult ActOnClassMessage(Scope *S,
8079                                ParsedType Receiver,
8080                                Selector Sel,
8081                                SourceLocation LBracLoc,
8082                                ArrayRef<SourceLocation> SelectorLocs,
8083                                SourceLocation RBracLoc,
8084                                MultiExprArg Args);
8085
8086   ExprResult BuildInstanceMessage(Expr *Receiver,
8087                                   QualType ReceiverType,
8088                                   SourceLocation SuperLoc,
8089                                   Selector Sel,
8090                                   ObjCMethodDecl *Method,
8091                                   SourceLocation LBracLoc,
8092                                   ArrayRef<SourceLocation> SelectorLocs,
8093                                   SourceLocation RBracLoc,
8094                                   MultiExprArg Args,
8095                                   bool isImplicit = false);
8096
8097   ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
8098                                           QualType ReceiverType,
8099                                           SourceLocation Loc,
8100                                           Selector Sel,
8101                                           ObjCMethodDecl *Method,
8102                                           MultiExprArg Args);
8103
8104   ExprResult ActOnInstanceMessage(Scope *S,
8105                                   Expr *Receiver,
8106                                   Selector Sel,
8107                                   SourceLocation LBracLoc,
8108                                   ArrayRef<SourceLocation> SelectorLocs,
8109                                   SourceLocation RBracLoc,
8110                                   MultiExprArg Args);
8111
8112   ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
8113                                   ObjCBridgeCastKind Kind,
8114                                   SourceLocation BridgeKeywordLoc,
8115                                   TypeSourceInfo *TSInfo,
8116                                   Expr *SubExpr);
8117
8118   ExprResult ActOnObjCBridgedCast(Scope *S,
8119                                   SourceLocation LParenLoc,
8120                                   ObjCBridgeCastKind Kind,
8121                                   SourceLocation BridgeKeywordLoc,
8122                                   ParsedType Type,
8123                                   SourceLocation RParenLoc,
8124                                   Expr *SubExpr);
8125
8126   void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
8127
8128   void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
8129
8130   bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
8131                                      CastKind &Kind);
8132
8133   bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
8134                                         QualType DestType, QualType SrcType,
8135                                         ObjCInterfaceDecl *&RelatedClass,
8136                                         ObjCMethodDecl *&ClassMethod,
8137                                         ObjCMethodDecl *&InstanceMethod,
8138                                         TypedefNameDecl *&TDNDecl,
8139                                         bool CfToNs, bool Diagnose = true);
8140
8141   bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
8142                                          QualType DestType, QualType SrcType,
8143                                          Expr *&SrcExpr, bool Diagnose = true);
8144
8145   bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
8146                                           bool Diagnose = true);
8147
8148   bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
8149
8150   /// \brief Check whether the given new method is a valid override of the
8151   /// given overridden method, and set any properties that should be inherited.
8152   void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
8153                                const ObjCMethodDecl *Overridden);
8154
8155   /// \brief Describes the compatibility of a result type with its method.
8156   enum ResultTypeCompatibilityKind {
8157     RTC_Compatible,
8158     RTC_Incompatible,
8159     RTC_Unknown
8160   };
8161
8162   void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
8163                                 ObjCInterfaceDecl *CurrentClass,
8164                                 ResultTypeCompatibilityKind RTC);
8165
8166   enum PragmaOptionsAlignKind {
8167     POAK_Native,  // #pragma options align=native
8168     POAK_Natural, // #pragma options align=natural
8169     POAK_Packed,  // #pragma options align=packed
8170     POAK_Power,   // #pragma options align=power
8171     POAK_Mac68k,  // #pragma options align=mac68k
8172     POAK_Reset    // #pragma options align=reset
8173   };
8174
8175   /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
8176   void ActOnPragmaClangSection(SourceLocation PragmaLoc,
8177                                PragmaClangSectionAction Action,
8178                                PragmaClangSectionKind SecKind, StringRef SecName);
8179
8180   /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
8181   void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
8182                                SourceLocation PragmaLoc);
8183
8184   /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
8185   void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
8186                        StringRef SlotLabel, Expr *Alignment);
8187
8188   /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
8189   void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
8190
8191   /// ActOnPragmaMSComment - Called on well formed
8192   /// \#pragma comment(kind, "arg").
8193   void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
8194                             StringRef Arg);
8195
8196   /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
8197   /// pointers_to_members(representation method[, general purpose
8198   /// representation]).
8199   void ActOnPragmaMSPointersToMembers(
8200       LangOptions::PragmaMSPointersToMembersKind Kind,
8201       SourceLocation PragmaLoc);
8202
8203   /// \brief Called on well formed \#pragma vtordisp().
8204   void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
8205                              SourceLocation PragmaLoc,
8206                              MSVtorDispAttr::Mode Value);
8207
8208   enum PragmaSectionKind {
8209     PSK_DataSeg,
8210     PSK_BSSSeg,
8211     PSK_ConstSeg,
8212     PSK_CodeSeg,
8213   };
8214
8215   bool UnifySection(StringRef SectionName,
8216                     int SectionFlags,
8217                     DeclaratorDecl *TheDecl);
8218   bool UnifySection(StringRef SectionName,
8219                     int SectionFlags,
8220                     SourceLocation PragmaSectionLocation);
8221
8222   /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
8223   void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
8224                         PragmaMsStackAction Action,
8225                         llvm::StringRef StackSlotLabel,
8226                         StringLiteral *SegmentName,
8227                         llvm::StringRef PragmaName);
8228
8229   /// \brief Called on well formed \#pragma section().
8230   void ActOnPragmaMSSection(SourceLocation PragmaLocation,
8231                             int SectionFlags, StringLiteral *SegmentName);
8232
8233   /// \brief Called on well-formed \#pragma init_seg().
8234   void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
8235                             StringLiteral *SegmentName);
8236
8237   /// \brief Called on #pragma clang __debug dump II
8238   void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
8239
8240   /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
8241   void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
8242                                  StringRef Value);
8243
8244   /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
8245   void ActOnPragmaUnused(const Token &Identifier,
8246                          Scope *curScope,
8247                          SourceLocation PragmaLoc);
8248
8249   /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
8250   void ActOnPragmaVisibility(const IdentifierInfo* VisType,
8251                              SourceLocation PragmaLoc);
8252
8253   NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
8254                                  SourceLocation Loc);
8255   void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
8256
8257   /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
8258   void ActOnPragmaWeakID(IdentifierInfo* WeakName,
8259                          SourceLocation PragmaLoc,
8260                          SourceLocation WeakNameLoc);
8261
8262   /// ActOnPragmaRedefineExtname - Called on well formed
8263   /// \#pragma redefine_extname oldname newname.
8264   void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
8265                                   IdentifierInfo* AliasName,
8266                                   SourceLocation PragmaLoc,
8267                                   SourceLocation WeakNameLoc,
8268                                   SourceLocation AliasNameLoc);
8269
8270   /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
8271   void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
8272                             IdentifierInfo* AliasName,
8273                             SourceLocation PragmaLoc,
8274                             SourceLocation WeakNameLoc,
8275                             SourceLocation AliasNameLoc);
8276
8277   /// ActOnPragmaFPContract - Called on well formed
8278   /// \#pragma {STDC,OPENCL} FP_CONTRACT and
8279   /// \#pragma clang fp contract
8280   void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
8281
8282   /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
8283   /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
8284   void AddAlignmentAttributesForRecord(RecordDecl *RD);
8285
8286   /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
8287   void AddMsStructLayoutForRecord(RecordDecl *RD);
8288
8289   /// FreePackedContext - Deallocate and null out PackContext.
8290   void FreePackedContext();
8291
8292   /// PushNamespaceVisibilityAttr - Note that we've entered a
8293   /// namespace with a visibility attribute.
8294   void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
8295                                    SourceLocation Loc);
8296
8297   /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
8298   /// add an appropriate visibility attribute.
8299   void AddPushedVisibilityAttribute(Decl *RD);
8300
8301   /// PopPragmaVisibility - Pop the top element of the visibility stack; used
8302   /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
8303   void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
8304
8305   /// FreeVisContext - Deallocate and null out VisContext.
8306   void FreeVisContext();
8307
8308   /// AddCFAuditedAttribute - Check whether we're currently within
8309   /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
8310   /// the appropriate attribute.
8311   void AddCFAuditedAttribute(Decl *D);
8312
8313   /// \brief Called on well-formed '\#pragma clang attribute push'.
8314   void ActOnPragmaAttributePush(AttributeList &Attribute,
8315                                 SourceLocation PragmaLoc,
8316                                 attr::ParsedSubjectMatchRuleSet Rules);
8317
8318   /// \brief Called on well-formed '\#pragma clang attribute pop'.
8319   void ActOnPragmaAttributePop(SourceLocation PragmaLoc);
8320
8321   /// \brief Adds the attributes that have been specified using the
8322   /// '\#pragma clang attribute push' directives to the given declaration.
8323   void AddPragmaAttributes(Scope *S, Decl *D);
8324
8325   void DiagnoseUnterminatedPragmaAttribute();
8326
8327   /// \brief Called on well formed \#pragma clang optimize.
8328   void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
8329
8330   /// \brief Get the location for the currently active "\#pragma clang optimize
8331   /// off". If this location is invalid, then the state of the pragma is "on".
8332   SourceLocation getOptimizeOffPragmaLocation() const {
8333     return OptimizeOffPragmaLocation;
8334   }
8335
8336   /// \brief Only called on function definitions; if there is a pragma in scope
8337   /// with the effect of a range-based optnone, consider marking the function
8338   /// with attribute optnone.
8339   void AddRangeBasedOptnone(FunctionDecl *FD);
8340
8341   /// \brief Adds the 'optnone' attribute to the function declaration if there
8342   /// are no conflicts; Loc represents the location causing the 'optnone'
8343   /// attribute to be added (usually because of a pragma).
8344   void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
8345
8346   /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
8347   void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
8348                       unsigned SpellingListIndex, bool IsPackExpansion);
8349   void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
8350                       unsigned SpellingListIndex, bool IsPackExpansion);
8351
8352   /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
8353   /// declaration.
8354   void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
8355                             unsigned SpellingListIndex);
8356
8357   /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
8358   /// declaration.
8359   void AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
8360                          unsigned SpellingListIndex);
8361
8362   /// AddAlignValueAttr - Adds an align_value attribute to a particular
8363   /// declaration.
8364   void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
8365                          unsigned SpellingListIndex);
8366
8367   /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
8368   /// declaration.
8369   void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
8370                            Expr *MinBlocks, unsigned SpellingListIndex);
8371
8372   /// AddModeAttr - Adds a mode attribute to a particular declaration.
8373   void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
8374                    unsigned SpellingListIndex, bool InInstantiation = false);
8375
8376   void AddParameterABIAttr(SourceRange AttrRange, Decl *D,
8377                            ParameterABI ABI, unsigned SpellingListIndex);
8378
8379   void AddNSConsumedAttr(SourceRange AttrRange, Decl *D,
8380                          unsigned SpellingListIndex, bool isNSConsumed,
8381                          bool isTemplateInstantiation);
8382
8383   bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
8384
8385   //===--------------------------------------------------------------------===//
8386   // C++ Coroutines TS
8387   //
8388   bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
8389                                StringRef Keyword);
8390   ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8391   ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
8392   StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
8393
8394   ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8395                                       bool IsImplicit = false);
8396   ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
8397                                         UnresolvedLookupExpr* Lookup);
8398   ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
8399   StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
8400                                bool IsImplicit = false);
8401   StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
8402   VarDecl *buildCoroutinePromise(SourceLocation Loc);
8403   void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
8404
8405   //===--------------------------------------------------------------------===//
8406   // OpenCL extensions.
8407   //
8408 private:
8409   std::string CurrOpenCLExtension;
8410   /// Extensions required by an OpenCL type.
8411   llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
8412   /// Extensions required by an OpenCL declaration.
8413   llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
8414 public:
8415   llvm::StringRef getCurrentOpenCLExtension() const {
8416     return CurrOpenCLExtension;
8417   }
8418   void setCurrentOpenCLExtension(llvm::StringRef Ext) {
8419     CurrOpenCLExtension = Ext;
8420   }
8421
8422   /// \brief Set OpenCL extensions for a type which can only be used when these
8423   /// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
8424   /// \param Exts A space separated list of OpenCL extensions.
8425   void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
8426
8427   /// \brief Set OpenCL extensions for a declaration which can only be
8428   /// used when these OpenCL extensions are enabled. If \p Exts is empty, do
8429   /// nothing.
8430   /// \param Exts A space separated list of OpenCL extensions.
8431   void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
8432
8433   /// \brief Set current OpenCL extensions for a type which can only be used
8434   /// when these OpenCL extensions are enabled. If current OpenCL extension is
8435   /// empty, do nothing.
8436   void setCurrentOpenCLExtensionForType(QualType T);
8437
8438   /// \brief Set current OpenCL extensions for a declaration which
8439   /// can only be used when these OpenCL extensions are enabled. If current
8440   /// OpenCL extension is empty, do nothing.
8441   void setCurrentOpenCLExtensionForDecl(Decl *FD);
8442
8443   bool isOpenCLDisabledDecl(Decl *FD);
8444
8445   /// \brief Check if type \p T corresponding to declaration specifier \p DS
8446   /// is disabled due to required OpenCL extensions being disabled. If so,
8447   /// emit diagnostics.
8448   /// \return true if type is disabled.
8449   bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
8450
8451   /// \brief Check if declaration \p D used by expression \p E
8452   /// is disabled due to required OpenCL extensions being disabled. If so,
8453   /// emit diagnostics.
8454   /// \return true if type is disabled.
8455   bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E);
8456
8457   //===--------------------------------------------------------------------===//
8458   // OpenMP directives and clauses.
8459   //
8460 private:
8461   void *VarDataSharingAttributesStack;
8462   /// Set to true inside '#pragma omp declare target' region.
8463   bool IsInOpenMPDeclareTargetContext = false;
8464   /// \brief Initialization of data-sharing attributes stack.
8465   void InitDataSharingAttributesStack();
8466   void DestroyDataSharingAttributesStack();
8467   ExprResult
8468   VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
8469                                         bool StrictlyPositive = true);
8470   /// Returns OpenMP nesting level for current directive.
8471   unsigned getOpenMPNestingLevel() const;
8472
8473   /// Push new OpenMP function region for non-capturing function.
8474   void pushOpenMPFunctionRegion();
8475
8476   /// Pop OpenMP function region for non-capturing function.
8477   void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
8478
8479   /// Checks if a type or a declaration is disabled due to the owning extension
8480   /// being disabled, and emits diagnostic messages if it is disabled.
8481   /// \param D type or declaration to be checked.
8482   /// \param DiagLoc source location for the diagnostic message.
8483   /// \param DiagInfo information to be emitted for the diagnostic message.
8484   /// \param SrcRange source range of the declaration.
8485   /// \param Map maps type or declaration to the extensions.
8486   /// \param Selector selects diagnostic message: 0 for type and 1 for
8487   ///        declaration.
8488   /// \return true if the type or declaration is disabled.
8489   template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
8490   bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
8491                                      MapT &Map, unsigned Selector = 0,
8492                                      SourceRange SrcRange = SourceRange());
8493
8494 public:
8495   /// \brief Return true if the provided declaration \a VD should be captured by
8496   /// reference.
8497   /// \param Level Relative level of nested OpenMP construct for that the check
8498   /// is performed.
8499   bool IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level);
8500
8501   /// \brief Check if the specified variable is used in one of the private
8502   /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
8503   /// constructs.
8504   VarDecl *IsOpenMPCapturedDecl(ValueDecl *D);
8505   ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
8506                                    ExprObjectKind OK, SourceLocation Loc);
8507
8508   /// \brief Check if the specified variable is used in 'private' clause.
8509   /// \param Level Relative level of nested OpenMP construct for that the check
8510   /// is performed.
8511   bool isOpenMPPrivateDecl(ValueDecl *D, unsigned Level);
8512
8513   /// \brief Check if the specified variable is captured  by 'target' directive.
8514   /// \param Level Relative level of nested OpenMP construct for that the check
8515   /// is performed.
8516   bool isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level);
8517
8518   ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
8519                                                     Expr *Op);
8520   /// \brief Called on start of new data sharing attribute block.
8521   void StartOpenMPDSABlock(OpenMPDirectiveKind K,
8522                            const DeclarationNameInfo &DirName, Scope *CurScope,
8523                            SourceLocation Loc);
8524   /// \brief Start analysis of clauses.
8525   void StartOpenMPClause(OpenMPClauseKind K);
8526   /// \brief End analysis of clauses.
8527   void EndOpenMPClause();
8528   /// \brief Called on end of data sharing attribute block.
8529   void EndOpenMPDSABlock(Stmt *CurDirective);
8530
8531   /// \brief Check if the current region is an OpenMP loop region and if it is,
8532   /// mark loop control variable, used in \p Init for loop initialization, as
8533   /// private by default.
8534   /// \param Init First part of the for loop.
8535   void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
8536
8537   // OpenMP directives and clauses.
8538   /// \brief Called on correct id-expression from the '#pragma omp
8539   /// threadprivate'.
8540   ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
8541                                      CXXScopeSpec &ScopeSpec,
8542                                      const DeclarationNameInfo &Id);
8543   /// \brief Called on well-formed '#pragma omp threadprivate'.
8544   DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
8545                                      SourceLocation Loc,
8546                                      ArrayRef<Expr *> VarList);
8547   /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
8548   OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
8549                                      SourceLocation Loc,
8550                                      ArrayRef<Expr *> VarList);
8551   /// \brief Check if the specified type is allowed to be used in 'omp declare
8552   /// reduction' construct.
8553   QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
8554                                            TypeResult ParsedType);
8555   /// \brief Called on start of '#pragma omp declare reduction'.
8556   DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
8557       Scope *S, DeclContext *DC, DeclarationName Name,
8558       ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
8559       AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
8560   /// \brief Initialize declare reduction construct initializer.
8561   void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
8562   /// \brief Finish current declare reduction construct initializer.
8563   void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
8564   /// \brief Initialize declare reduction construct initializer.
8565   void ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
8566   /// \brief Finish current declare reduction construct initializer.
8567   void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer);
8568   /// \brief Called at the end of '#pragma omp declare reduction'.
8569   DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
8570       Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
8571
8572   /// Called on the start of target region i.e. '#pragma omp declare target'.
8573   bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
8574   /// Called at the end of target region i.e. '#pragme omp end declare target'.
8575   void ActOnFinishOpenMPDeclareTargetDirective();
8576   /// Called on correct id-expression from the '#pragma omp declare target'.
8577   void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
8578                                     const DeclarationNameInfo &Id,
8579                                     OMPDeclareTargetDeclAttr::MapTypeTy MT,
8580                                     NamedDeclSetType &SameDirectiveDecls);
8581   /// Check declaration inside target region.
8582   void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D);
8583   /// Return true inside OpenMP target region.
8584   bool isInOpenMPDeclareTargetContext() const {
8585     return IsInOpenMPDeclareTargetContext;
8586   }
8587
8588   /// Return the number of captured regions created for an OpenMP directive.
8589   static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
8590
8591   /// \brief Initialization of captured region for OpenMP region.
8592   void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
8593   /// \brief End of OpenMP region.
8594   ///
8595   /// \param S Statement associated with the current OpenMP region.
8596   /// \param Clauses List of clauses for the current OpenMP region.
8597   ///
8598   /// \returns Statement for finished OpenMP region.
8599   StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
8600   StmtResult ActOnOpenMPExecutableDirective(
8601       OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
8602       OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
8603       Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
8604   /// \brief Called on well-formed '\#pragma omp parallel' after parsing
8605   /// of the  associated statement.
8606   StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
8607                                           Stmt *AStmt,
8608                                           SourceLocation StartLoc,
8609                                           SourceLocation EndLoc);
8610   /// \brief Called on well-formed '\#pragma omp simd' after parsing
8611   /// of the associated statement.
8612   StmtResult ActOnOpenMPSimdDirective(
8613       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8614       SourceLocation EndLoc,
8615       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8616   /// \brief Called on well-formed '\#pragma omp for' after parsing
8617   /// of the associated statement.
8618   StmtResult ActOnOpenMPForDirective(
8619       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8620       SourceLocation EndLoc,
8621       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8622   /// \brief Called on well-formed '\#pragma omp for simd' after parsing
8623   /// of the associated statement.
8624   StmtResult ActOnOpenMPForSimdDirective(
8625       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8626       SourceLocation EndLoc,
8627       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8628   /// \brief Called on well-formed '\#pragma omp sections' after parsing
8629   /// of the associated statement.
8630   StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8631                                           Stmt *AStmt, SourceLocation StartLoc,
8632                                           SourceLocation EndLoc);
8633   /// \brief Called on well-formed '\#pragma omp section' after parsing of the
8634   /// associated statement.
8635   StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
8636                                          SourceLocation EndLoc);
8637   /// \brief Called on well-formed '\#pragma omp single' after parsing of the
8638   /// associated statement.
8639   StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8640                                         Stmt *AStmt, SourceLocation StartLoc,
8641                                         SourceLocation EndLoc);
8642   /// \brief Called on well-formed '\#pragma omp master' after parsing of the
8643   /// associated statement.
8644   StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
8645                                         SourceLocation EndLoc);
8646   /// \brief Called on well-formed '\#pragma omp critical' after parsing of the
8647   /// associated statement.
8648   StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
8649                                           ArrayRef<OMPClause *> Clauses,
8650                                           Stmt *AStmt, SourceLocation StartLoc,
8651                                           SourceLocation EndLoc);
8652   /// \brief Called on well-formed '\#pragma omp parallel for' after parsing
8653   /// of the  associated statement.
8654   StmtResult ActOnOpenMPParallelForDirective(
8655       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8656       SourceLocation EndLoc,
8657       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8658   /// \brief Called on well-formed '\#pragma omp parallel for simd' after
8659   /// parsing of the  associated statement.
8660   StmtResult ActOnOpenMPParallelForSimdDirective(
8661       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8662       SourceLocation EndLoc,
8663       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8664   /// \brief Called on well-formed '\#pragma omp parallel sections' after
8665   /// parsing of the  associated statement.
8666   StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8667                                                   Stmt *AStmt,
8668                                                   SourceLocation StartLoc,
8669                                                   SourceLocation EndLoc);
8670   /// \brief Called on well-formed '\#pragma omp task' after parsing of the
8671   /// associated statement.
8672   StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8673                                       Stmt *AStmt, SourceLocation StartLoc,
8674                                       SourceLocation EndLoc);
8675   /// \brief Called on well-formed '\#pragma omp taskyield'.
8676   StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8677                                            SourceLocation EndLoc);
8678   /// \brief Called on well-formed '\#pragma omp barrier'.
8679   StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8680                                          SourceLocation EndLoc);
8681   /// \brief Called on well-formed '\#pragma omp taskwait'.
8682   StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8683                                           SourceLocation EndLoc);
8684   /// \brief Called on well-formed '\#pragma omp taskgroup'.
8685   StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
8686                                            Stmt *AStmt, SourceLocation StartLoc,
8687                                            SourceLocation EndLoc);
8688   /// \brief Called on well-formed '\#pragma omp flush'.
8689   StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8690                                        SourceLocation StartLoc,
8691                                        SourceLocation EndLoc);
8692   /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
8693   /// associated statement.
8694   StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8695                                          Stmt *AStmt, SourceLocation StartLoc,
8696                                          SourceLocation EndLoc);
8697   /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
8698   /// associated statement.
8699   StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8700                                         Stmt *AStmt, SourceLocation StartLoc,
8701                                         SourceLocation EndLoc);
8702   /// \brief Called on well-formed '\#pragma omp target' after parsing of the
8703   /// associated statement.
8704   StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8705                                         Stmt *AStmt, SourceLocation StartLoc,
8706                                         SourceLocation EndLoc);
8707   /// \brief Called on well-formed '\#pragma omp target data' after parsing of
8708   /// the associated statement.
8709   StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
8710                                             Stmt *AStmt, SourceLocation StartLoc,
8711                                             SourceLocation EndLoc);
8712   /// \brief Called on well-formed '\#pragma omp target enter data' after
8713   /// parsing of the associated statement.
8714   StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
8715                                                  SourceLocation StartLoc,
8716                                                  SourceLocation EndLoc);
8717   /// \brief Called on well-formed '\#pragma omp target exit data' after
8718   /// parsing of the associated statement.
8719   StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8720                                                 SourceLocation StartLoc,
8721                                                 SourceLocation EndLoc);
8722   /// \brief Called on well-formed '\#pragma omp target parallel' after
8723   /// parsing of the associated statement.
8724   StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8725                                                 Stmt *AStmt,
8726                                                 SourceLocation StartLoc,
8727                                                 SourceLocation EndLoc);
8728   /// \brief Called on well-formed '\#pragma omp target parallel for' after
8729   /// parsing of the  associated statement.
8730   StmtResult ActOnOpenMPTargetParallelForDirective(
8731       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8732       SourceLocation EndLoc,
8733       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8734   /// \brief Called on well-formed '\#pragma omp teams' after parsing of the
8735   /// associated statement.
8736   StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
8737                                        Stmt *AStmt, SourceLocation StartLoc,
8738                                        SourceLocation EndLoc);
8739   /// \brief Called on well-formed '\#pragma omp cancellation point'.
8740   StmtResult
8741   ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
8742                                         SourceLocation EndLoc,
8743                                         OpenMPDirectiveKind CancelRegion);
8744   /// \brief Called on well-formed '\#pragma omp cancel'.
8745   StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
8746                                         SourceLocation StartLoc,
8747                                         SourceLocation EndLoc,
8748                                         OpenMPDirectiveKind CancelRegion);
8749   /// \brief Called on well-formed '\#pragma omp taskloop' after parsing of the
8750   /// associated statement.
8751   StmtResult ActOnOpenMPTaskLoopDirective(
8752       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8753       SourceLocation EndLoc,
8754       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8755   /// \brief Called on well-formed '\#pragma omp taskloop simd' after parsing of
8756   /// the associated statement.
8757   StmtResult ActOnOpenMPTaskLoopSimdDirective(
8758       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8759       SourceLocation EndLoc,
8760       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8761   /// \brief Called on well-formed '\#pragma omp distribute' after parsing
8762   /// of the associated statement.
8763   StmtResult ActOnOpenMPDistributeDirective(
8764       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8765       SourceLocation EndLoc,
8766       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8767   /// \brief Called on well-formed '\#pragma omp target update'.
8768   StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
8769                                               SourceLocation StartLoc,
8770                                               SourceLocation EndLoc);
8771   /// \brief Called on well-formed '\#pragma omp distribute parallel for' after
8772   /// parsing of the associated statement.
8773   StmtResult ActOnOpenMPDistributeParallelForDirective(
8774       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8775       SourceLocation EndLoc,
8776       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8777   /// \brief Called on well-formed '\#pragma omp distribute parallel for simd'
8778   /// after parsing of the associated statement.
8779   StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
8780       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8781       SourceLocation EndLoc,
8782       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8783   /// \brief Called on well-formed '\#pragma omp distribute simd' after
8784   /// parsing of the associated statement.
8785   StmtResult ActOnOpenMPDistributeSimdDirective(
8786       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8787       SourceLocation EndLoc,
8788       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8789   /// \brief Called on well-formed '\#pragma omp target parallel for simd' after
8790   /// parsing of the associated statement.
8791   StmtResult ActOnOpenMPTargetParallelForSimdDirective(
8792       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8793       SourceLocation EndLoc,
8794       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8795   /// \brief Called on well-formed '\#pragma omp target simd' after parsing of
8796   /// the associated statement.
8797   StmtResult ActOnOpenMPTargetSimdDirective(
8798       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8799       SourceLocation EndLoc,
8800       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8801   /// Called on well-formed '\#pragma omp teams distribute' after parsing of
8802   /// the associated statement.
8803   StmtResult ActOnOpenMPTeamsDistributeDirective(
8804       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8805       SourceLocation EndLoc,
8806       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8807   /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
8808   /// of the associated statement.
8809   StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
8810       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8811       SourceLocation EndLoc,
8812       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8813   /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
8814   /// after parsing of the associated statement.
8815   StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8816       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8817       SourceLocation EndLoc,
8818       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8819   /// Called on well-formed '\#pragma omp teams distribute parallel for'
8820   /// after parsing of the associated statement.
8821   StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
8822       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8823       SourceLocation EndLoc,
8824       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8825   /// Called on well-formed '\#pragma omp target teams' after parsing of the
8826   /// associated statement.
8827   StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8828                                              Stmt *AStmt,
8829                                              SourceLocation StartLoc,
8830                                              SourceLocation EndLoc);
8831   /// Called on well-formed '\#pragma omp target teams distribute' after parsing
8832   /// of the associated statement.
8833   StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
8834       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8835       SourceLocation EndLoc,
8836       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8837   /// Called on well-formed '\#pragma omp target teams distribute parallel for'
8838   /// after parsing of the associated statement.
8839   StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8840       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8841       SourceLocation EndLoc,
8842       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8843   /// Called on well-formed '\#pragma omp target teams distribute parallel for
8844   /// simd' after parsing of the associated statement.
8845   StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8846       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8847       SourceLocation EndLoc,
8848       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8849   /// Called on well-formed '\#pragma omp target teams distribute simd' after
8850   /// parsing of the associated statement.
8851   StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
8852       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
8853       SourceLocation EndLoc,
8854       llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA);
8855
8856   /// Checks correctness of linear modifiers.
8857   bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
8858                                  SourceLocation LinLoc);
8859   /// Checks that the specified declaration matches requirements for the linear
8860   /// decls.
8861   bool CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
8862                              OpenMPLinearClauseKind LinKind, QualType Type);
8863
8864   /// \brief Called on well-formed '\#pragma omp declare simd' after parsing of
8865   /// the associated method/function.
8866   DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
8867       DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
8868       Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
8869       ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
8870       ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
8871
8872   OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
8873                                          Expr *Expr,
8874                                          SourceLocation StartLoc,
8875                                          SourceLocation LParenLoc,
8876                                          SourceLocation EndLoc);
8877   /// \brief Called on well-formed 'if' clause.
8878   OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8879                                  Expr *Condition, SourceLocation StartLoc,
8880                                  SourceLocation LParenLoc,
8881                                  SourceLocation NameModifierLoc,
8882                                  SourceLocation ColonLoc,
8883                                  SourceLocation EndLoc);
8884   /// \brief Called on well-formed 'final' clause.
8885   OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
8886                                     SourceLocation LParenLoc,
8887                                     SourceLocation EndLoc);
8888   /// \brief Called on well-formed 'num_threads' clause.
8889   OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8890                                          SourceLocation StartLoc,
8891                                          SourceLocation LParenLoc,
8892                                          SourceLocation EndLoc);
8893   /// \brief Called on well-formed 'safelen' clause.
8894   OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
8895                                       SourceLocation StartLoc,
8896                                       SourceLocation LParenLoc,
8897                                       SourceLocation EndLoc);
8898   /// \brief Called on well-formed 'simdlen' clause.
8899   OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
8900                                       SourceLocation LParenLoc,
8901                                       SourceLocation EndLoc);
8902   /// \brief Called on well-formed 'collapse' clause.
8903   OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
8904                                        SourceLocation StartLoc,
8905                                        SourceLocation LParenLoc,
8906                                        SourceLocation EndLoc);
8907   /// \brief Called on well-formed 'ordered' clause.
8908   OMPClause *
8909   ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
8910                            SourceLocation LParenLoc = SourceLocation(),
8911                            Expr *NumForLoops = nullptr);
8912   /// \brief Called on well-formed 'grainsize' clause.
8913   OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
8914                                         SourceLocation LParenLoc,
8915                                         SourceLocation EndLoc);
8916   /// \brief Called on well-formed 'num_tasks' clause.
8917   OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
8918                                        SourceLocation LParenLoc,
8919                                        SourceLocation EndLoc);
8920   /// \brief Called on well-formed 'hint' clause.
8921   OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
8922                                    SourceLocation LParenLoc,
8923                                    SourceLocation EndLoc);
8924
8925   OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
8926                                      unsigned Argument,
8927                                      SourceLocation ArgumentLoc,
8928                                      SourceLocation StartLoc,
8929                                      SourceLocation LParenLoc,
8930                                      SourceLocation EndLoc);
8931   /// \brief Called on well-formed 'default' clause.
8932   OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8933                                       SourceLocation KindLoc,
8934                                       SourceLocation StartLoc,
8935                                       SourceLocation LParenLoc,
8936                                       SourceLocation EndLoc);
8937   /// \brief Called on well-formed 'proc_bind' clause.
8938   OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8939                                        SourceLocation KindLoc,
8940                                        SourceLocation StartLoc,
8941                                        SourceLocation LParenLoc,
8942                                        SourceLocation EndLoc);
8943
8944   OMPClause *ActOnOpenMPSingleExprWithArgClause(
8945       OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
8946       SourceLocation StartLoc, SourceLocation LParenLoc,
8947       ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
8948       SourceLocation EndLoc);
8949   /// \brief Called on well-formed 'schedule' clause.
8950   OMPClause *ActOnOpenMPScheduleClause(
8951       OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
8952       OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
8953       SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8954       SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
8955
8956   OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
8957                                SourceLocation EndLoc);
8958   /// \brief Called on well-formed 'nowait' clause.
8959   OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8960                                      SourceLocation EndLoc);
8961   /// \brief Called on well-formed 'untied' clause.
8962   OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8963                                      SourceLocation EndLoc);
8964   /// \brief Called on well-formed 'mergeable' clause.
8965   OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8966                                         SourceLocation EndLoc);
8967   /// \brief Called on well-formed 'read' clause.
8968   OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
8969                                    SourceLocation EndLoc);
8970   /// \brief Called on well-formed 'write' clause.
8971   OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
8972                                     SourceLocation EndLoc);
8973   /// \brief Called on well-formed 'update' clause.
8974   OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8975                                      SourceLocation EndLoc);
8976   /// \brief Called on well-formed 'capture' clause.
8977   OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8978                                       SourceLocation EndLoc);
8979   /// \brief Called on well-formed 'seq_cst' clause.
8980   OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8981                                      SourceLocation EndLoc);
8982   /// \brief Called on well-formed 'threads' clause.
8983   OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8984                                       SourceLocation EndLoc);
8985   /// \brief Called on well-formed 'simd' clause.
8986   OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8987                                    SourceLocation EndLoc);
8988   /// \brief Called on well-formed 'nogroup' clause.
8989   OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8990                                       SourceLocation EndLoc);
8991
8992   OMPClause *ActOnOpenMPVarListClause(
8993       OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
8994       SourceLocation StartLoc, SourceLocation LParenLoc,
8995       SourceLocation ColonLoc, SourceLocation EndLoc,
8996       CXXScopeSpec &ReductionIdScopeSpec,
8997       const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
8998       OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8999       OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9000       SourceLocation DepLinMapLoc);
9001   /// \brief Called on well-formed 'private' clause.
9002   OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9003                                       SourceLocation StartLoc,
9004                                       SourceLocation LParenLoc,
9005                                       SourceLocation EndLoc);
9006   /// \brief Called on well-formed 'firstprivate' clause.
9007   OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9008                                            SourceLocation StartLoc,
9009                                            SourceLocation LParenLoc,
9010                                            SourceLocation EndLoc);
9011   /// \brief Called on well-formed 'lastprivate' clause.
9012   OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9013                                           SourceLocation StartLoc,
9014                                           SourceLocation LParenLoc,
9015                                           SourceLocation EndLoc);
9016   /// \brief Called on well-formed 'shared' clause.
9017   OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9018                                      SourceLocation StartLoc,
9019                                      SourceLocation LParenLoc,
9020                                      SourceLocation EndLoc);
9021   /// \brief Called on well-formed 'reduction' clause.
9022   OMPClause *ActOnOpenMPReductionClause(
9023       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9024       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9025       CXXScopeSpec &ReductionIdScopeSpec,
9026       const DeclarationNameInfo &ReductionId,
9027       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9028   /// Called on well-formed 'task_reduction' clause.
9029   OMPClause *ActOnOpenMPTaskReductionClause(
9030       ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9031       SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
9032       CXXScopeSpec &ReductionIdScopeSpec,
9033       const DeclarationNameInfo &ReductionId,
9034       ArrayRef<Expr *> UnresolvedReductions = llvm::None);
9035   /// \brief Called on well-formed 'linear' clause.
9036   OMPClause *
9037   ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
9038                           SourceLocation StartLoc, SourceLocation LParenLoc,
9039                           OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
9040                           SourceLocation ColonLoc, SourceLocation EndLoc);
9041   /// \brief Called on well-formed 'aligned' clause.
9042   OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
9043                                       Expr *Alignment,
9044                                       SourceLocation StartLoc,
9045                                       SourceLocation LParenLoc,
9046                                       SourceLocation ColonLoc,
9047                                       SourceLocation EndLoc);
9048   /// \brief Called on well-formed 'copyin' clause.
9049   OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
9050                                      SourceLocation StartLoc,
9051                                      SourceLocation LParenLoc,
9052                                      SourceLocation EndLoc);
9053   /// \brief Called on well-formed 'copyprivate' clause.
9054   OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
9055                                           SourceLocation StartLoc,
9056                                           SourceLocation LParenLoc,
9057                                           SourceLocation EndLoc);
9058   /// \brief Called on well-formed 'flush' pseudo clause.
9059   OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
9060                                     SourceLocation StartLoc,
9061                                     SourceLocation LParenLoc,
9062                                     SourceLocation EndLoc);
9063   /// \brief Called on well-formed 'depend' clause.
9064   OMPClause *
9065   ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
9066                           SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
9067                           SourceLocation StartLoc, SourceLocation LParenLoc,
9068                           SourceLocation EndLoc);
9069   /// \brief Called on well-formed 'device' clause.
9070   OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
9071                                      SourceLocation LParenLoc,
9072                                      SourceLocation EndLoc);
9073   /// \brief Called on well-formed 'map' clause.
9074   OMPClause *
9075   ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
9076                        OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9077                        SourceLocation MapLoc, SourceLocation ColonLoc,
9078                        ArrayRef<Expr *> VarList, SourceLocation StartLoc,
9079                        SourceLocation LParenLoc, SourceLocation EndLoc);
9080   /// \brief Called on well-formed 'num_teams' clause.
9081   OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
9082                                        SourceLocation LParenLoc,
9083                                        SourceLocation EndLoc);
9084   /// \brief Called on well-formed 'thread_limit' clause.
9085   OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
9086                                           SourceLocation StartLoc,
9087                                           SourceLocation LParenLoc,
9088                                           SourceLocation EndLoc);
9089   /// \brief Called on well-formed 'priority' clause.
9090   OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
9091                                        SourceLocation LParenLoc,
9092                                        SourceLocation EndLoc);
9093   /// \brief Called on well-formed 'dist_schedule' clause.
9094   OMPClause *ActOnOpenMPDistScheduleClause(
9095       OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
9096       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
9097       SourceLocation CommaLoc, SourceLocation EndLoc);
9098   /// \brief Called on well-formed 'defaultmap' clause.
9099   OMPClause *ActOnOpenMPDefaultmapClause(
9100       OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
9101       SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
9102       SourceLocation KindLoc, SourceLocation EndLoc);
9103   /// \brief Called on well-formed 'to' clause.
9104   OMPClause *ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
9105                                  SourceLocation StartLoc,
9106                                  SourceLocation LParenLoc,
9107                                  SourceLocation EndLoc);
9108   /// \brief Called on well-formed 'from' clause.
9109   OMPClause *ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
9110                                    SourceLocation StartLoc,
9111                                    SourceLocation LParenLoc,
9112                                    SourceLocation EndLoc);
9113   /// Called on well-formed 'use_device_ptr' clause.
9114   OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
9115                                            SourceLocation StartLoc,
9116                                            SourceLocation LParenLoc,
9117                                            SourceLocation EndLoc);
9118   /// Called on well-formed 'is_device_ptr' clause.
9119   OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
9120                                           SourceLocation StartLoc,
9121                                           SourceLocation LParenLoc,
9122                                           SourceLocation EndLoc);
9123
9124   /// \brief The kind of conversion being performed.
9125   enum CheckedConversionKind {
9126     /// \brief An implicit conversion.
9127     CCK_ImplicitConversion,
9128     /// \brief A C-style cast.
9129     CCK_CStyleCast,
9130     /// \brief A functional-style cast.
9131     CCK_FunctionalCast,
9132     /// \brief A cast other than a C-style cast.
9133     CCK_OtherCast
9134   };
9135
9136   /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
9137   /// cast.  If there is already an implicit cast, merge into the existing one.
9138   /// If isLvalue, the result of the cast is an lvalue.
9139   ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
9140                                ExprValueKind VK = VK_RValue,
9141                                const CXXCastPath *BasePath = nullptr,
9142                                CheckedConversionKind CCK
9143                                   = CCK_ImplicitConversion);
9144
9145   /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
9146   /// to the conversion from scalar type ScalarTy to the Boolean type.
9147   static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
9148
9149   /// IgnoredValueConversions - Given that an expression's result is
9150   /// syntactically ignored, perform any conversions that are
9151   /// required.
9152   ExprResult IgnoredValueConversions(Expr *E);
9153
9154   // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
9155   // functions and arrays to their respective pointers (C99 6.3.2.1).
9156   ExprResult UsualUnaryConversions(Expr *E);
9157
9158   /// CallExprUnaryConversions - a special case of an unary conversion
9159   /// performed on a function designator of a call expression.
9160   ExprResult CallExprUnaryConversions(Expr *E);
9161
9162   // DefaultFunctionArrayConversion - converts functions and arrays
9163   // to their respective pointers (C99 6.3.2.1).
9164   ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
9165
9166   // DefaultFunctionArrayLvalueConversion - converts functions and
9167   // arrays to their respective pointers and performs the
9168   // lvalue-to-rvalue conversion.
9169   ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
9170                                                   bool Diagnose = true);
9171
9172   // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
9173   // the operand.  This is DefaultFunctionArrayLvalueConversion,
9174   // except that it assumes the operand isn't of function or array
9175   // type.
9176   ExprResult DefaultLvalueConversion(Expr *E);
9177
9178   // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
9179   // do not have a prototype. Integer promotions are performed on each
9180   // argument, and arguments that have type float are promoted to double.
9181   ExprResult DefaultArgumentPromotion(Expr *E);
9182
9183   /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
9184   /// it as an xvalue. In C++98, the result will still be a prvalue, because
9185   /// we don't have xvalues there.
9186   ExprResult TemporaryMaterializationConversion(Expr *E);
9187
9188   // Used for emitting the right warning by DefaultVariadicArgumentPromotion
9189   enum VariadicCallType {
9190     VariadicFunction,
9191     VariadicBlock,
9192     VariadicMethod,
9193     VariadicConstructor,
9194     VariadicDoesNotApply
9195   };
9196
9197   VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
9198                                        const FunctionProtoType *Proto,
9199                                        Expr *Fn);
9200
9201   // Used for determining in which context a type is allowed to be passed to a
9202   // vararg function.
9203   enum VarArgKind {
9204     VAK_Valid,
9205     VAK_ValidInCXX11,
9206     VAK_Undefined,
9207     VAK_MSVCUndefined,
9208     VAK_Invalid
9209   };
9210
9211   // Determines which VarArgKind fits an expression.
9212   VarArgKind isValidVarArgType(const QualType &Ty);
9213
9214   /// Check to see if the given expression is a valid argument to a variadic
9215   /// function, issuing a diagnostic if not.
9216   void checkVariadicArgument(const Expr *E, VariadicCallType CT);
9217
9218   /// Check to see if a given expression could have '.c_str()' called on it.
9219   bool hasCStrMethod(const Expr *E);
9220
9221   /// GatherArgumentsForCall - Collector argument expressions for various
9222   /// form of call prototypes.
9223   bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
9224                               const FunctionProtoType *Proto,
9225                               unsigned FirstParam, ArrayRef<Expr *> Args,
9226                               SmallVectorImpl<Expr *> &AllArgs,
9227                               VariadicCallType CallType = VariadicDoesNotApply,
9228                               bool AllowExplicit = false,
9229                               bool IsListInitialization = false);
9230
9231   // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
9232   // will create a runtime trap if the resulting type is not a POD type.
9233   ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
9234                                               FunctionDecl *FDecl);
9235
9236   // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
9237   // operands and then handles various conversions that are common to binary
9238   // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
9239   // routine returns the first non-arithmetic type found. The client is
9240   // responsible for emitting appropriate error diagnostics.
9241   QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
9242                                       bool IsCompAssign = false);
9243
9244   /// AssignConvertType - All of the 'assignment' semantic checks return this
9245   /// enum to indicate whether the assignment was allowed.  These checks are
9246   /// done for simple assignments, as well as initialization, return from
9247   /// function, argument passing, etc.  The query is phrased in terms of a
9248   /// source and destination type.
9249   enum AssignConvertType {
9250     /// Compatible - the types are compatible according to the standard.
9251     Compatible,
9252
9253     /// PointerToInt - The assignment converts a pointer to an int, which we
9254     /// accept as an extension.
9255     PointerToInt,
9256
9257     /// IntToPointer - The assignment converts an int to a pointer, which we
9258     /// accept as an extension.
9259     IntToPointer,
9260
9261     /// FunctionVoidPointer - The assignment is between a function pointer and
9262     /// void*, which the standard doesn't allow, but we accept as an extension.
9263     FunctionVoidPointer,
9264
9265     /// IncompatiblePointer - The assignment is between two pointers types that
9266     /// are not compatible, but we accept them as an extension.
9267     IncompatiblePointer,
9268
9269     /// IncompatiblePointerSign - The assignment is between two pointers types
9270     /// which point to integers which have a different sign, but are otherwise
9271     /// identical. This is a subset of the above, but broken out because it's by
9272     /// far the most common case of incompatible pointers.
9273     IncompatiblePointerSign,
9274
9275     /// CompatiblePointerDiscardsQualifiers - The assignment discards
9276     /// c/v/r qualifiers, which we accept as an extension.
9277     CompatiblePointerDiscardsQualifiers,
9278
9279     /// IncompatiblePointerDiscardsQualifiers - The assignment
9280     /// discards qualifiers that we don't permit to be discarded,
9281     /// like address spaces.
9282     IncompatiblePointerDiscardsQualifiers,
9283
9284     /// IncompatibleNestedPointerQualifiers - The assignment is between two
9285     /// nested pointer types, and the qualifiers other than the first two
9286     /// levels differ e.g. char ** -> const char **, but we accept them as an
9287     /// extension.
9288     IncompatibleNestedPointerQualifiers,
9289
9290     /// IncompatibleVectors - The assignment is between two vector types that
9291     /// have the same size, which we accept as an extension.
9292     IncompatibleVectors,
9293
9294     /// IntToBlockPointer - The assignment converts an int to a block
9295     /// pointer. We disallow this.
9296     IntToBlockPointer,
9297
9298     /// IncompatibleBlockPointer - The assignment is between two block
9299     /// pointers types that are not compatible.
9300     IncompatibleBlockPointer,
9301
9302     /// IncompatibleObjCQualifiedId - The assignment is between a qualified
9303     /// id type and something else (that is incompatible with it). For example,
9304     /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
9305     IncompatibleObjCQualifiedId,
9306
9307     /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
9308     /// object with __weak qualifier.
9309     IncompatibleObjCWeakRef,
9310
9311     /// Incompatible - We reject this conversion outright, it is invalid to
9312     /// represent it in the AST.
9313     Incompatible
9314   };
9315
9316   /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
9317   /// assignment conversion type specified by ConvTy.  This returns true if the
9318   /// conversion was invalid or false if the conversion was accepted.
9319   bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
9320                                 SourceLocation Loc,
9321                                 QualType DstType, QualType SrcType,
9322                                 Expr *SrcExpr, AssignmentAction Action,
9323                                 bool *Complained = nullptr);
9324
9325   /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
9326   /// enum. If AllowMask is true, then we also allow the complement of a valid
9327   /// value, to be used as a mask.
9328   bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
9329                          bool AllowMask) const;
9330
9331   /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
9332   /// integer not in the range of enum values.
9333   void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
9334                               Expr *SrcExpr);
9335
9336   /// CheckAssignmentConstraints - Perform type checking for assignment,
9337   /// argument passing, variable initialization, and function return values.
9338   /// C99 6.5.16.
9339   AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
9340                                                QualType LHSType,
9341                                                QualType RHSType);
9342
9343   /// Check assignment constraints and optionally prepare for a conversion of
9344   /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
9345   /// is true.
9346   AssignConvertType CheckAssignmentConstraints(QualType LHSType,
9347                                                ExprResult &RHS,
9348                                                CastKind &Kind,
9349                                                bool ConvertRHS = true);
9350
9351   /// Check assignment constraints for an assignment of RHS to LHSType.
9352   ///
9353   /// \param LHSType The destination type for the assignment.
9354   /// \param RHS The source expression for the assignment.
9355   /// \param Diagnose If \c true, diagnostics may be produced when checking
9356   ///        for assignability. If a diagnostic is produced, \p RHS will be
9357   ///        set to ExprError(). Note that this function may still return
9358   ///        without producing a diagnostic, even for an invalid assignment.
9359   /// \param DiagnoseCFAudited If \c true, the target is a function parameter
9360   ///        in an audited Core Foundation API and does not need to be checked
9361   ///        for ARC retain issues.
9362   /// \param ConvertRHS If \c true, \p RHS will be updated to model the
9363   ///        conversions necessary to perform the assignment. If \c false,
9364   ///        \p Diagnose must also be \c false.
9365   AssignConvertType CheckSingleAssignmentConstraints(
9366       QualType LHSType, ExprResult &RHS, bool Diagnose = true,
9367       bool DiagnoseCFAudited = false, bool ConvertRHS = true);
9368
9369   // \brief If the lhs type is a transparent union, check whether we
9370   // can initialize the transparent union with the given expression.
9371   AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
9372                                                              ExprResult &RHS);
9373
9374   bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
9375
9376   bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
9377
9378   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9379                                        AssignmentAction Action,
9380                                        bool AllowExplicit = false);
9381   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9382                                        AssignmentAction Action,
9383                                        bool AllowExplicit,
9384                                        ImplicitConversionSequence& ICS);
9385   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9386                                        const ImplicitConversionSequence& ICS,
9387                                        AssignmentAction Action,
9388                                        CheckedConversionKind CCK
9389                                           = CCK_ImplicitConversion);
9390   ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
9391                                        const StandardConversionSequence& SCS,
9392                                        AssignmentAction Action,
9393                                        CheckedConversionKind CCK);
9394
9395   /// the following "Check" methods will return a valid/converted QualType
9396   /// or a null QualType (indicating an error diagnostic was issued).
9397
9398   /// type checking binary operators (subroutines of CreateBuiltinBinOp).
9399   QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9400                            ExprResult &RHS);
9401   QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9402                                  ExprResult &RHS);
9403   QualType CheckPointerToMemberOperands( // C++ 5.5
9404     ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
9405     SourceLocation OpLoc, bool isIndirect);
9406   QualType CheckMultiplyDivideOperands( // C99 6.5.5
9407     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
9408     bool IsDivide);
9409   QualType CheckRemainderOperands( // C99 6.5.5
9410     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9411     bool IsCompAssign = false);
9412   QualType CheckAdditionOperands( // C99 6.5.6
9413     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9414     BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
9415   QualType CheckSubtractionOperands( // C99 6.5.6
9416     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9417     QualType* CompLHSTy = nullptr);
9418   QualType CheckShiftOperands( // C99 6.5.7
9419     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9420     BinaryOperatorKind Opc, bool IsCompAssign = false);
9421   QualType CheckCompareOperands( // C99 6.5.8/9
9422     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9423     BinaryOperatorKind Opc, bool isRelational);
9424   QualType CheckBitwiseOperands( // C99 6.5.[10...12]
9425       ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9426       BinaryOperatorKind Opc);
9427   QualType CheckLogicalOperands( // C99 6.5.[13,14]
9428     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
9429     BinaryOperatorKind Opc);
9430   // CheckAssignmentOperands is used for both simple and compound assignment.
9431   // For simple assignment, pass both expressions and a null converted type.
9432   // For compound assignment, pass both expressions and the converted type.
9433   QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
9434     Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
9435
9436   ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
9437                                      UnaryOperatorKind Opcode, Expr *Op);
9438   ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
9439                                          BinaryOperatorKind Opcode,
9440                                          Expr *LHS, Expr *RHS);
9441   ExprResult checkPseudoObjectRValue(Expr *E);
9442   Expr *recreateSyntacticForm(PseudoObjectExpr *E);
9443
9444   QualType CheckConditionalOperands( // C99 6.5.15
9445     ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
9446     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
9447   QualType CXXCheckConditionalOperands( // C++ 5.16
9448     ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
9449     ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
9450   QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
9451                                     bool ConvertArgs = true);
9452   QualType FindCompositePointerType(SourceLocation Loc,
9453                                     ExprResult &E1, ExprResult &E2,
9454                                     bool ConvertArgs = true) {
9455     Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
9456     QualType Composite =
9457         FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
9458     E1 = E1Tmp;
9459     E2 = E2Tmp;
9460     return Composite;
9461   }
9462
9463   QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
9464                                         SourceLocation QuestionLoc);
9465
9466   bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
9467                                   SourceLocation QuestionLoc);
9468
9469   void DiagnoseAlwaysNonNullPointer(Expr *E,
9470                                     Expr::NullPointerConstantKind NullType,
9471                                     bool IsEqual, SourceRange Range);
9472
9473   /// type checking for vector binary operators.
9474   QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9475                                SourceLocation Loc, bool IsCompAssign,
9476                                bool AllowBothBool, bool AllowBoolConversion);
9477   QualType GetSignedVectorType(QualType V);
9478   QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9479                                       SourceLocation Loc, bool isRelational);
9480   QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9481                                       SourceLocation Loc);
9482
9483   bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
9484   bool isLaxVectorConversion(QualType srcType, QualType destType);
9485
9486   /// type checking declaration initializers (C99 6.7.8)
9487   bool CheckForConstantInitializer(Expr *e, QualType t);
9488
9489   // type checking C++ declaration initializers (C++ [dcl.init]).
9490
9491   /// ReferenceCompareResult - Expresses the result of comparing two
9492   /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
9493   /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
9494   enum ReferenceCompareResult {
9495     /// Ref_Incompatible - The two types are incompatible, so direct
9496     /// reference binding is not possible.
9497     Ref_Incompatible = 0,
9498     /// Ref_Related - The two types are reference-related, which means
9499     /// that their unqualified forms (T1 and T2) are either the same
9500     /// or T1 is a base class of T2.
9501     Ref_Related,
9502     /// Ref_Compatible - The two types are reference-compatible.
9503     Ref_Compatible
9504   };
9505
9506   ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
9507                                                       QualType T1, QualType T2,
9508                                                       bool &DerivedToBase,
9509                                                       bool &ObjCConversion,
9510                                                 bool &ObjCLifetimeConversion);
9511
9512   ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
9513                                  Expr *CastExpr, CastKind &CastKind,
9514                                  ExprValueKind &VK, CXXCastPath &Path);
9515
9516   /// \brief Force an expression with unknown-type to an expression of the
9517   /// given type.
9518   ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
9519
9520   /// \brief Type-check an expression that's being passed to an
9521   /// __unknown_anytype parameter.
9522   ExprResult checkUnknownAnyArg(SourceLocation callLoc,
9523                                 Expr *result, QualType &paramType);
9524
9525   // CheckVectorCast - check type constraints for vectors.
9526   // Since vectors are an extension, there are no C standard reference for this.
9527   // We allow casting between vectors and integer datatypes of the same size.
9528   // returns true if the cast is invalid
9529   bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
9530                        CastKind &Kind);
9531
9532   /// \brief Prepare `SplattedExpr` for a vector splat operation, adding
9533   /// implicit casts if necessary.
9534   ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
9535
9536   // CheckExtVectorCast - check type constraints for extended vectors.
9537   // Since vectors are an extension, there are no C standard reference for this.
9538   // We allow casting between vectors and integer datatypes of the same size,
9539   // or vectors and the element type of that vector.
9540   // returns the cast expr
9541   ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
9542                                 CastKind &Kind);
9543
9544   ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
9545                                         SourceLocation LParenLoc,
9546                                         Expr *CastExpr,
9547                                         SourceLocation RParenLoc);
9548
9549   enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
9550
9551   /// \brief Checks for invalid conversions and casts between
9552   /// retainable pointers and other pointer kinds for ARC and Weak.
9553   ARCConversionResult CheckObjCConversion(SourceRange castRange,
9554                                           QualType castType, Expr *&op,
9555                                           CheckedConversionKind CCK,
9556                                           bool Diagnose = true,
9557                                           bool DiagnoseCFAudited = false,
9558                                           BinaryOperatorKind Opc = BO_PtrMemD
9559                                           );
9560
9561   Expr *stripARCUnbridgedCast(Expr *e);
9562   void diagnoseARCUnbridgedCast(Expr *e);
9563
9564   bool CheckObjCARCUnavailableWeakConversion(QualType castType,
9565                                              QualType ExprType);
9566
9567   /// checkRetainCycles - Check whether an Objective-C message send
9568   /// might create an obvious retain cycle.
9569   void checkRetainCycles(ObjCMessageExpr *msg);
9570   void checkRetainCycles(Expr *receiver, Expr *argument);
9571   void checkRetainCycles(VarDecl *Var, Expr *Init);
9572
9573   /// checkUnsafeAssigns - Check whether +1 expr is being assigned
9574   /// to weak/__unsafe_unretained type.
9575   bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
9576
9577   /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
9578   /// to weak/__unsafe_unretained expression.
9579   void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
9580
9581   /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
9582   /// \param Method - May be null.
9583   /// \param [out] ReturnType - The return type of the send.
9584   /// \return true iff there were any incompatible types.
9585   bool CheckMessageArgumentTypes(QualType ReceiverType,
9586                                  MultiExprArg Args, Selector Sel,
9587                                  ArrayRef<SourceLocation> SelectorLocs,
9588                                  ObjCMethodDecl *Method, bool isClassMessage,
9589                                  bool isSuperMessage,
9590                                  SourceLocation lbrac, SourceLocation rbrac,
9591                                  SourceRange RecRange,
9592                                  QualType &ReturnType, ExprValueKind &VK);
9593
9594   /// \brief Determine the result of a message send expression based on
9595   /// the type of the receiver, the method expected to receive the message,
9596   /// and the form of the message send.
9597   QualType getMessageSendResultType(QualType ReceiverType,
9598                                     ObjCMethodDecl *Method,
9599                                     bool isClassMessage, bool isSuperMessage);
9600
9601   /// \brief If the given expression involves a message send to a method
9602   /// with a related result type, emit a note describing what happened.
9603   void EmitRelatedResultTypeNote(const Expr *E);
9604
9605   /// \brief Given that we had incompatible pointer types in a return
9606   /// statement, check whether we're in a method with a related result
9607   /// type, and if so, emit a note describing what happened.
9608   void EmitRelatedResultTypeNoteForReturn(QualType destType);
9609
9610   class ConditionResult {
9611     Decl *ConditionVar;
9612     FullExprArg Condition;
9613     bool Invalid;
9614     bool HasKnownValue;
9615     bool KnownValue;
9616
9617     friend class Sema;
9618     ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
9619                     bool IsConstexpr)
9620         : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
9621           HasKnownValue(IsConstexpr && Condition.get() &&
9622                         !Condition.get()->isValueDependent()),
9623           KnownValue(HasKnownValue &&
9624                      !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
9625     explicit ConditionResult(bool Invalid)
9626         : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
9627           HasKnownValue(false), KnownValue(false) {}
9628
9629   public:
9630     ConditionResult() : ConditionResult(false) {}
9631     bool isInvalid() const { return Invalid; }
9632     std::pair<VarDecl *, Expr *> get() const {
9633       return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
9634                             Condition.get());
9635     }
9636     llvm::Optional<bool> getKnownValue() const {
9637       if (!HasKnownValue)
9638         return None;
9639       return KnownValue;
9640     }
9641   };
9642   static ConditionResult ConditionError() { return ConditionResult(true); }
9643
9644   enum class ConditionKind {
9645     Boolean,     ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
9646     ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
9647     Switch       ///< An integral condition for a 'switch' statement.
9648   };
9649
9650   ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
9651                                  Expr *SubExpr, ConditionKind CK);
9652
9653   ConditionResult ActOnConditionVariable(Decl *ConditionVar,
9654                                          SourceLocation StmtLoc,
9655                                          ConditionKind CK);
9656
9657   DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
9658
9659   ExprResult CheckConditionVariable(VarDecl *ConditionVar,
9660                                     SourceLocation StmtLoc,
9661                                     ConditionKind CK);
9662   ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
9663
9664   /// CheckBooleanCondition - Diagnose problems involving the use of
9665   /// the given expression as a boolean condition (e.g. in an if
9666   /// statement).  Also performs the standard function and array
9667   /// decays, possibly changing the input variable.
9668   ///
9669   /// \param Loc - A location associated with the condition, e.g. the
9670   /// 'if' keyword.
9671   /// \return true iff there were any errors
9672   ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
9673                                    bool IsConstexpr = false);
9674
9675   /// DiagnoseAssignmentAsCondition - Given that an expression is
9676   /// being used as a boolean condition, warn if it's an assignment.
9677   void DiagnoseAssignmentAsCondition(Expr *E);
9678
9679   /// \brief Redundant parentheses over an equality comparison can indicate
9680   /// that the user intended an assignment used as condition.
9681   void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
9682
9683   /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
9684   ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
9685
9686   /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
9687   /// the specified width and sign.  If an overflow occurs, detect it and emit
9688   /// the specified diagnostic.
9689   void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
9690                                           unsigned NewWidth, bool NewSign,
9691                                           SourceLocation Loc, unsigned DiagID);
9692
9693   /// Checks that the Objective-C declaration is declared in the global scope.
9694   /// Emits an error and marks the declaration as invalid if it's not declared
9695   /// in the global scope.
9696   bool CheckObjCDeclScope(Decl *D);
9697
9698   /// \brief Abstract base class used for diagnosing integer constant
9699   /// expression violations.
9700   class VerifyICEDiagnoser {
9701   public:
9702     bool Suppress;
9703
9704     VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
9705
9706     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
9707     virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
9708     virtual ~VerifyICEDiagnoser() { }
9709   };
9710
9711   /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
9712   /// and reports the appropriate diagnostics. Returns false on success.
9713   /// Can optionally return the value of the expression.
9714   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9715                                              VerifyICEDiagnoser &Diagnoser,
9716                                              bool AllowFold = true);
9717   ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9718                                              unsigned DiagID,
9719                                              bool AllowFold = true);
9720   ExprResult VerifyIntegerConstantExpression(Expr *E,
9721                                              llvm::APSInt *Result = nullptr);
9722
9723   /// VerifyBitField - verifies that a bit field expression is an ICE and has
9724   /// the correct width, and that the field type is valid.
9725   /// Returns false on success.
9726   /// Can optionally return whether the bit-field is of width 0
9727   ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
9728                             QualType FieldTy, bool IsMsStruct,
9729                             Expr *BitWidth, bool *ZeroWidth = nullptr);
9730
9731 private:
9732   unsigned ForceCUDAHostDeviceDepth = 0;
9733
9734 public:
9735   /// Increments our count of the number of times we've seen a pragma forcing
9736   /// functions to be __host__ __device__.  So long as this count is greater
9737   /// than zero, all functions encountered will be __host__ __device__.
9738   void PushForceCUDAHostDevice();
9739
9740   /// Decrements our count of the number of times we've seen a pragma forcing
9741   /// functions to be __host__ __device__.  Returns false if the count is 0
9742   /// before incrementing, so you can emit an error.
9743   bool PopForceCUDAHostDevice();
9744
9745   /// Diagnostics that are emitted only if we discover that the given function
9746   /// must be codegen'ed.  Because handling these correctly adds overhead to
9747   /// compilation, this is currently only enabled for CUDA compilations.
9748   llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
9749                  std::vector<PartialDiagnosticAt>>
9750       CUDADeferredDiags;
9751
9752   /// A pair of a canonical FunctionDecl and a SourceLocation.  When used as the
9753   /// key in a hashtable, both the FD and location are hashed.
9754   struct FunctionDeclAndLoc {
9755     CanonicalDeclPtr<FunctionDecl> FD;
9756     SourceLocation Loc;
9757   };
9758
9759   /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
9760   /// (maybe deferred) "bad call" diagnostic.  We use this to avoid emitting the
9761   /// same deferred diag twice.
9762   llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
9763
9764   /// An inverse call graph, mapping known-emitted functions to one of their
9765   /// known-emitted callers (plus the location of the call).
9766   ///
9767   /// Functions that we can tell a priori must be emitted aren't added to this
9768   /// map.
9769   llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
9770                  /* Caller = */ FunctionDeclAndLoc>
9771       CUDAKnownEmittedFns;
9772
9773   /// A partial call graph maintained during CUDA compilation to support
9774   /// deferred diagnostics.
9775   ///
9776   /// Functions are only added here if, at the time they're considered, they are
9777   /// not known-emitted.  As soon as we discover that a function is
9778   /// known-emitted, we remove it and everything it transitively calls from this
9779   /// set and add those functions to CUDAKnownEmittedFns.
9780   llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
9781                  /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
9782                                                  SourceLocation>>
9783       CUDACallGraph;
9784
9785   /// Diagnostic builder for CUDA errors which may or may not be deferred.
9786   ///
9787   /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
9788   /// which are not allowed to appear inside __device__ functions and are
9789   /// allowed to appear in __host__ __device__ functions only if the host+device
9790   /// function is never codegen'ed.
9791   ///
9792   /// To handle this, we use the notion of "deferred diagnostics", where we
9793   /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
9794   ///
9795   /// This class lets you emit either a regular diagnostic, a deferred
9796   /// diagnostic, or no diagnostic at all, according to an argument you pass to
9797   /// its constructor, thus simplifying the process of creating these "maybe
9798   /// deferred" diagnostics.
9799   class CUDADiagBuilder {
9800   public:
9801     enum Kind {
9802       /// Emit no diagnostics.
9803       K_Nop,
9804       /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
9805       K_Immediate,
9806       /// Emit the diagnostic immediately, and, if it's a warning or error, also
9807       /// emit a call stack showing how this function can be reached by an a
9808       /// priori known-emitted function.
9809       K_ImmediateWithCallStack,
9810       /// Create a deferred diagnostic, which is emitted only if the function
9811       /// it's attached to is codegen'ed.  Also emit a call stack as with
9812       /// K_ImmediateWithCallStack.
9813       K_Deferred
9814     };
9815
9816     CUDADiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
9817                     FunctionDecl *Fn, Sema &S);
9818     ~CUDADiagBuilder();
9819
9820     /// Convertible to bool: True if we immediately emitted an error, false if
9821     /// we didn't emit an error or we created a deferred error.
9822     ///
9823     /// Example usage:
9824     ///
9825     ///   if (CUDADiagBuilder(...) << foo << bar)
9826     ///     return ExprError();
9827     ///
9828     /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
9829     /// want to use these instead of creating a CUDADiagBuilder yourself.
9830     operator bool() const { return ImmediateDiag.hasValue(); }
9831
9832     template <typename T>
9833     friend const CUDADiagBuilder &operator<<(const CUDADiagBuilder &Diag,
9834                                              const T &Value) {
9835       if (Diag.ImmediateDiag.hasValue())
9836         *Diag.ImmediateDiag << Value;
9837       else if (Diag.PartialDiag.hasValue())
9838         *Diag.PartialDiag << Value;
9839       return Diag;
9840     }
9841
9842   private:
9843     Sema &S;
9844     SourceLocation Loc;
9845     unsigned DiagID;
9846     FunctionDecl *Fn;
9847     bool ShowCallStack;
9848
9849     // Invariant: At most one of these Optionals has a value.
9850     // FIXME: Switch these to a Variant once that exists.
9851     llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
9852     llvm::Optional<PartialDiagnostic> PartialDiag;
9853   };
9854
9855   /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9856   /// is "used as device code".
9857   ///
9858   /// - If CurContext is a __host__ function, does not emit any diagnostics.
9859   /// - If CurContext is a __device__ or __global__ function, emits the
9860   ///   diagnostics immediately.
9861   /// - If CurContext is a __host__ __device__ function and we are compiling for
9862   ///   the device, creates a diagnostic which is emitted if and when we realize
9863   ///   that the function will be codegen'ed.
9864   ///
9865   /// Example usage:
9866   ///
9867   ///  // Variable-length arrays are not allowed in CUDA device code.
9868   ///  if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
9869   ///    return ExprError();
9870   ///  // Otherwise, continue parsing as normal.
9871   CUDADiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
9872
9873   /// Creates a CUDADiagBuilder that emits the diagnostic if the current context
9874   /// is "used as host code".
9875   ///
9876   /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
9877   CUDADiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
9878
9879   enum CUDAFunctionTarget {
9880     CFT_Device,
9881     CFT_Global,
9882     CFT_Host,
9883     CFT_HostDevice,
9884     CFT_InvalidTarget
9885   };
9886
9887   /// Determines whether the given function is a CUDA device/host/kernel/etc.
9888   /// function.
9889   ///
9890   /// Use this rather than examining the function's attributes yourself -- you
9891   /// will get it wrong.  Returns CFT_Host if D is null.
9892   CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
9893                                         bool IgnoreImplicitHDAttr = false);
9894   CUDAFunctionTarget IdentifyCUDATarget(const AttributeList *Attr);
9895
9896   /// Gets the CUDA target for the current context.
9897   CUDAFunctionTarget CurrentCUDATarget() {
9898     return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
9899   }
9900
9901   // CUDA function call preference. Must be ordered numerically from
9902   // worst to best.
9903   enum CUDAFunctionPreference {
9904     CFP_Never,      // Invalid caller/callee combination.
9905     CFP_WrongSide,  // Calls from host-device to host or device
9906                     // function that do not match current compilation
9907                     // mode.
9908     CFP_HostDevice, // Any calls to host/device functions.
9909     CFP_SameSide,   // Calls from host-device to host or device
9910                     // function matching current compilation mode.
9911     CFP_Native,     // host-to-host or device-to-device calls.
9912   };
9913
9914   /// Identifies relative preference of a given Caller/Callee
9915   /// combination, based on their host/device attributes.
9916   /// \param Caller function which needs address of \p Callee.
9917   ///               nullptr in case of global context.
9918   /// \param Callee target function
9919   ///
9920   /// \returns preference value for particular Caller/Callee combination.
9921   CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
9922                                                 const FunctionDecl *Callee);
9923
9924   /// Determines whether Caller may invoke Callee, based on their CUDA
9925   /// host/device attributes.  Returns false if the call is not allowed.
9926   ///
9927   /// Note: Will return true for CFP_WrongSide calls.  These may appear in
9928   /// semantically correct CUDA programs, but only if they're never codegen'ed.
9929   bool IsAllowedCUDACall(const FunctionDecl *Caller,
9930                          const FunctionDecl *Callee) {
9931     return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
9932   }
9933
9934   /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
9935   /// depending on FD and the current compilation settings.
9936   void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
9937                                    const LookupResult &Previous);
9938
9939 public:
9940   /// Check whether we're allowed to call Callee from the current context.
9941   ///
9942   /// - If the call is never allowed in a semantically-correct program
9943   ///   (CFP_Never), emits an error and returns false.
9944   ///
9945   /// - If the call is allowed in semantically-correct programs, but only if
9946   ///   it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
9947   ///   be emitted if and when the caller is codegen'ed, and returns true.
9948   ///
9949   ///   Will only create deferred diagnostics for a given SourceLocation once,
9950   ///   so you can safely call this multiple times without generating duplicate
9951   ///   deferred errors.
9952   ///
9953   /// - Otherwise, returns true without emitting any diagnostics.
9954   bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
9955
9956   /// Set __device__ or __host__ __device__ attributes on the given lambda
9957   /// operator() method.
9958   ///
9959   /// CUDA lambdas declared inside __device__ or __global__ functions inherit
9960   /// the __device__ attribute.  Similarly, lambdas inside __host__ __device__
9961   /// functions become __host__ __device__ themselves.
9962   void CUDASetLambdaAttrs(CXXMethodDecl *Method);
9963
9964   /// Finds a function in \p Matches with highest calling priority
9965   /// from \p Caller context and erases all functions with lower
9966   /// calling priority.
9967   void EraseUnwantedCUDAMatches(
9968       const FunctionDecl *Caller,
9969       SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
9970
9971   /// Given a implicit special member, infer its CUDA target from the
9972   /// calls it needs to make to underlying base/field special members.
9973   /// \param ClassDecl the class for which the member is being created.
9974   /// \param CSM the kind of special member.
9975   /// \param MemberDecl the special member itself.
9976   /// \param ConstRHS true if this is a copy operation with a const object on
9977   ///        its RHS.
9978   /// \param Diagnose true if this call should emit diagnostics.
9979   /// \return true if there was an error inferring.
9980   /// The result of this call is implicit CUDA target attribute(s) attached to
9981   /// the member declaration.
9982   bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
9983                                                CXXSpecialMember CSM,
9984                                                CXXMethodDecl *MemberDecl,
9985                                                bool ConstRHS,
9986                                                bool Diagnose);
9987
9988   /// \return true if \p CD can be considered empty according to CUDA
9989   /// (E.2.3.1 in CUDA 7.5 Programming guide).
9990   bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
9991   bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
9992
9993   /// Check whether NewFD is a valid overload for CUDA. Emits
9994   /// diagnostics and invalidates NewFD if not.
9995   void checkCUDATargetOverload(FunctionDecl *NewFD,
9996                                const LookupResult &Previous);
9997   /// Copies target attributes from the template TD to the function FD.
9998   void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
9999
10000   /// \name Code completion
10001   //@{
10002   /// \brief Describes the context in which code completion occurs.
10003   enum ParserCompletionContext {
10004     /// \brief Code completion occurs at top-level or namespace context.
10005     PCC_Namespace,
10006     /// \brief Code completion occurs within a class, struct, or union.
10007     PCC_Class,
10008     /// \brief Code completion occurs within an Objective-C interface, protocol,
10009     /// or category.
10010     PCC_ObjCInterface,
10011     /// \brief Code completion occurs within an Objective-C implementation or
10012     /// category implementation
10013     PCC_ObjCImplementation,
10014     /// \brief Code completion occurs within the list of instance variables
10015     /// in an Objective-C interface, protocol, category, or implementation.
10016     PCC_ObjCInstanceVariableList,
10017     /// \brief Code completion occurs following one or more template
10018     /// headers.
10019     PCC_Template,
10020     /// \brief Code completion occurs following one or more template
10021     /// headers within a class.
10022     PCC_MemberTemplate,
10023     /// \brief Code completion occurs within an expression.
10024     PCC_Expression,
10025     /// \brief Code completion occurs within a statement, which may
10026     /// also be an expression or a declaration.
10027     PCC_Statement,
10028     /// \brief Code completion occurs at the beginning of the
10029     /// initialization statement (or expression) in a for loop.
10030     PCC_ForInit,
10031     /// \brief Code completion occurs within the condition of an if,
10032     /// while, switch, or for statement.
10033     PCC_Condition,
10034     /// \brief Code completion occurs within the body of a function on a
10035     /// recovery path, where we do not have a specific handle on our position
10036     /// in the grammar.
10037     PCC_RecoveryInFunction,
10038     /// \brief Code completion occurs where only a type is permitted.
10039     PCC_Type,
10040     /// \brief Code completion occurs in a parenthesized expression, which
10041     /// might also be a type cast.
10042     PCC_ParenthesizedExpression,
10043     /// \brief Code completion occurs within a sequence of declaration
10044     /// specifiers within a function, method, or block.
10045     PCC_LocalDeclarationSpecifiers
10046   };
10047
10048   void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
10049   void CodeCompleteOrdinaryName(Scope *S,
10050                                 ParserCompletionContext CompletionContext);
10051   void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
10052                             bool AllowNonIdentifiers,
10053                             bool AllowNestedNameSpecifiers);
10054
10055   struct CodeCompleteExpressionData;
10056   void CodeCompleteExpression(Scope *S,
10057                               const CodeCompleteExpressionData &Data);
10058   void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
10059                                        SourceLocation OpLoc, bool IsArrow,
10060                                        bool IsBaseExprStatement);
10061   void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
10062   void CodeCompleteTag(Scope *S, unsigned TagSpec);
10063   void CodeCompleteTypeQualifiers(DeclSpec &DS);
10064   void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
10065                                       const VirtSpecifiers *VS = nullptr);
10066   void CodeCompleteBracketDeclarator(Scope *S);
10067   void CodeCompleteCase(Scope *S);
10068   void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
10069   void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
10070                                ArrayRef<Expr *> Args);
10071   void CodeCompleteInitializer(Scope *S, Decl *D);
10072   void CodeCompleteReturn(Scope *S);
10073   void CodeCompleteAfterIf(Scope *S);
10074   void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
10075
10076   void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
10077                                bool EnteringContext);
10078   void CodeCompleteUsing(Scope *S);
10079   void CodeCompleteUsingDirective(Scope *S);
10080   void CodeCompleteNamespaceDecl(Scope *S);
10081   void CodeCompleteNamespaceAliasDecl(Scope *S);
10082   void CodeCompleteOperatorName(Scope *S);
10083   void CodeCompleteConstructorInitializer(
10084                                 Decl *Constructor,
10085                                 ArrayRef<CXXCtorInitializer *> Initializers);
10086
10087   void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
10088                                     bool AfterAmpersand);
10089
10090   void CodeCompleteObjCAtDirective(Scope *S);
10091   void CodeCompleteObjCAtVisibility(Scope *S);
10092   void CodeCompleteObjCAtStatement(Scope *S);
10093   void CodeCompleteObjCAtExpression(Scope *S);
10094   void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
10095   void CodeCompleteObjCPropertyGetter(Scope *S);
10096   void CodeCompleteObjCPropertySetter(Scope *S);
10097   void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
10098                                    bool IsParameter);
10099   void CodeCompleteObjCMessageReceiver(Scope *S);
10100   void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
10101                                     ArrayRef<IdentifierInfo *> SelIdents,
10102                                     bool AtArgumentExpression);
10103   void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
10104                                     ArrayRef<IdentifierInfo *> SelIdents,
10105                                     bool AtArgumentExpression,
10106                                     bool IsSuper = false);
10107   void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
10108                                        ArrayRef<IdentifierInfo *> SelIdents,
10109                                        bool AtArgumentExpression,
10110                                        ObjCInterfaceDecl *Super = nullptr);
10111   void CodeCompleteObjCForCollection(Scope *S,
10112                                      DeclGroupPtrTy IterationVar);
10113   void CodeCompleteObjCSelector(Scope *S,
10114                                 ArrayRef<IdentifierInfo *> SelIdents);
10115   void CodeCompleteObjCProtocolReferences(
10116                                          ArrayRef<IdentifierLocPair> Protocols);
10117   void CodeCompleteObjCProtocolDecl(Scope *S);
10118   void CodeCompleteObjCInterfaceDecl(Scope *S);
10119   void CodeCompleteObjCSuperclass(Scope *S,
10120                                   IdentifierInfo *ClassName,
10121                                   SourceLocation ClassNameLoc);
10122   void CodeCompleteObjCImplementationDecl(Scope *S);
10123   void CodeCompleteObjCInterfaceCategory(Scope *S,
10124                                          IdentifierInfo *ClassName,
10125                                          SourceLocation ClassNameLoc);
10126   void CodeCompleteObjCImplementationCategory(Scope *S,
10127                                               IdentifierInfo *ClassName,
10128                                               SourceLocation ClassNameLoc);
10129   void CodeCompleteObjCPropertyDefinition(Scope *S);
10130   void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
10131                                               IdentifierInfo *PropertyName);
10132   void CodeCompleteObjCMethodDecl(Scope *S,
10133                                   bool IsInstanceMethod,
10134                                   ParsedType ReturnType);
10135   void CodeCompleteObjCMethodDeclSelector(Scope *S,
10136                                           bool IsInstanceMethod,
10137                                           bool AtParameterName,
10138                                           ParsedType ReturnType,
10139                                           ArrayRef<IdentifierInfo *> SelIdents);
10140   void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
10141                                             SourceLocation ClassNameLoc,
10142                                             bool IsBaseExprStatement);
10143   void CodeCompletePreprocessorDirective(bool InConditional);
10144   void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
10145   void CodeCompletePreprocessorMacroName(bool IsDefinition);
10146   void CodeCompletePreprocessorExpression();
10147   void CodeCompletePreprocessorMacroArgument(Scope *S,
10148                                              IdentifierInfo *Macro,
10149                                              MacroInfo *MacroInfo,
10150                                              unsigned Argument);
10151   void CodeCompleteNaturalLanguage();
10152   void CodeCompleteAvailabilityPlatformName();
10153   void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
10154                                    CodeCompletionTUInfo &CCTUInfo,
10155                   SmallVectorImpl<CodeCompletionResult> &Results);
10156   //@}
10157
10158   //===--------------------------------------------------------------------===//
10159   // Extra semantic analysis beyond the C type system
10160
10161 public:
10162   SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
10163                                                 unsigned ByteNo) const;
10164
10165 private:
10166   void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10167                         const ArraySubscriptExpr *ASE=nullptr,
10168                         bool AllowOnePastEnd=true, bool IndexNegated=false);
10169   void CheckArrayAccess(const Expr *E);
10170   // Used to grab the relevant information from a FormatAttr and a
10171   // FunctionDeclaration.
10172   struct FormatStringInfo {
10173     unsigned FormatIdx;
10174     unsigned FirstDataArg;
10175     bool HasVAListArg;
10176   };
10177
10178   static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
10179                                   FormatStringInfo *FSI);
10180   bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
10181                          const FunctionProtoType *Proto);
10182   bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
10183                            ArrayRef<const Expr *> Args);
10184   bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
10185                         const FunctionProtoType *Proto);
10186   bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
10187   void CheckConstructorCall(FunctionDecl *FDecl,
10188                             ArrayRef<const Expr *> Args,
10189                             const FunctionProtoType *Proto,
10190                             SourceLocation Loc);
10191
10192   void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
10193                  const Expr *ThisArg, ArrayRef<const Expr *> Args,
10194                  bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
10195                  VariadicCallType CallType);
10196
10197   bool CheckObjCString(Expr *Arg);
10198   ExprResult CheckOSLogFormatStringArg(Expr *Arg);
10199
10200   ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
10201                                       unsigned BuiltinID, CallExpr *TheCall);
10202
10203   bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
10204                                     unsigned MaxWidth);
10205   bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10206   bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10207
10208   bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10209   bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10210   bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10211   bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
10212   bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
10213   bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10214   bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
10215
10216   bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
10217   bool SemaBuiltinVAStartARM(CallExpr *Call);
10218   bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
10219   bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
10220   bool SemaBuiltinVSX(CallExpr *TheCall);
10221   bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
10222
10223 public:
10224   // Used by C++ template instantiation.
10225   ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
10226   ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
10227                                    SourceLocation BuiltinLoc,
10228                                    SourceLocation RParenLoc);
10229
10230 private:
10231   bool SemaBuiltinPrefetch(CallExpr *TheCall);
10232   bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
10233   bool SemaBuiltinAssume(CallExpr *TheCall);
10234   bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
10235   bool SemaBuiltinLongjmp(CallExpr *TheCall);
10236   bool SemaBuiltinSetjmp(CallExpr *TheCall);
10237   ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
10238   ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
10239   ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
10240                                      AtomicExpr::AtomicOp Op);
10241   bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
10242                               llvm::APSInt &Result);
10243   bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
10244                                    int Low, int High);
10245   bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
10246                                       unsigned Multiple);
10247   bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
10248                                 int ArgNum, unsigned ExpectedFieldNum,
10249                                 bool AllowName);
10250 public:
10251   enum FormatStringType {
10252     FST_Scanf,
10253     FST_Printf,
10254     FST_NSString,
10255     FST_Strftime,
10256     FST_Strfmon,
10257     FST_Kprintf,
10258     FST_FreeBSDKPrintf,
10259     FST_OSTrace,
10260     FST_OSLog,
10261     FST_Unknown
10262   };
10263   static FormatStringType GetFormatStringType(const FormatAttr *Format);
10264
10265   bool FormatStringHasSArg(const StringLiteral *FExpr);
10266
10267   static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
10268
10269 private:
10270   bool CheckFormatArguments(const FormatAttr *Format,
10271                             ArrayRef<const Expr *> Args,
10272                             bool IsCXXMember,
10273                             VariadicCallType CallType,
10274                             SourceLocation Loc, SourceRange Range,
10275                             llvm::SmallBitVector &CheckedVarArgs);
10276   bool CheckFormatArguments(ArrayRef<const Expr *> Args,
10277                             bool HasVAListArg, unsigned format_idx,
10278                             unsigned firstDataArg, FormatStringType Type,
10279                             VariadicCallType CallType,
10280                             SourceLocation Loc, SourceRange range,
10281                             llvm::SmallBitVector &CheckedVarArgs);
10282
10283   void CheckAbsoluteValueFunction(const CallExpr *Call,
10284                                   const FunctionDecl *FDecl);
10285
10286   void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
10287
10288   void CheckMemaccessArguments(const CallExpr *Call,
10289                                unsigned BId,
10290                                IdentifierInfo *FnName);
10291
10292   void CheckStrlcpycatArguments(const CallExpr *Call,
10293                                 IdentifierInfo *FnName);
10294
10295   void CheckStrncatArguments(const CallExpr *Call,
10296                              IdentifierInfo *FnName);
10297
10298   void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10299                           SourceLocation ReturnLoc,
10300                           bool isObjCMethod = false,
10301                           const AttrVec *Attrs = nullptr,
10302                           const FunctionDecl *FD = nullptr);
10303
10304   void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
10305   void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
10306   void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
10307   void CheckForIntOverflow(Expr *E);
10308   void CheckUnsequencedOperations(Expr *E);
10309
10310   /// \brief Perform semantic checks on a completed expression. This will either
10311   /// be a full-expression or a default argument expression.
10312   void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
10313                           bool IsConstexpr = false);
10314
10315   void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
10316                                    Expr *Init);
10317
10318   /// Check if there is a field shadowing.
10319   void CheckShadowInheritedFields(const SourceLocation &Loc,
10320                                   DeclarationName FieldName,
10321                                   const CXXRecordDecl *RD);
10322
10323   /// \brief Check if the given expression contains 'break' or 'continue'
10324   /// statement that produces control flow different from GCC.
10325   void CheckBreakContinueBinding(Expr *E);
10326
10327   /// \brief Check whether receiver is mutable ObjC container which
10328   /// attempts to add itself into the container
10329   void CheckObjCCircularContainer(ObjCMessageExpr *Message);
10330
10331   void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
10332   void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
10333                                  bool DeleteWasArrayForm);
10334 public:
10335   /// \brief Register a magic integral constant to be used as a type tag.
10336   void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10337                                   uint64_t MagicValue, QualType Type,
10338                                   bool LayoutCompatible, bool MustBeNull);
10339
10340   struct TypeTagData {
10341     TypeTagData() {}
10342
10343     TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
10344         Type(Type), LayoutCompatible(LayoutCompatible),
10345         MustBeNull(MustBeNull)
10346     {}
10347
10348     QualType Type;
10349
10350     /// If true, \c Type should be compared with other expression's types for
10351     /// layout-compatibility.
10352     unsigned LayoutCompatible : 1;
10353     unsigned MustBeNull : 1;
10354   };
10355
10356   /// A pair of ArgumentKind identifier and magic value.  This uniquely
10357   /// identifies the magic value.
10358   typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
10359
10360 private:
10361   /// \brief A map from magic value to type information.
10362   std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
10363       TypeTagForDatatypeMagicValues;
10364
10365   /// \brief Peform checks on a call of a function with argument_with_type_tag
10366   /// or pointer_with_type_tag attributes.
10367   void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10368                                 const Expr * const *ExprArgs);
10369
10370   /// \brief Check if we are taking the address of a packed field
10371   /// as this may be a problem if the pointer value is dereferenced.
10372   void CheckAddressOfPackedMember(Expr *rhs);
10373
10374   /// \brief The parser's current scope.
10375   ///
10376   /// The parser maintains this state here.
10377   Scope *CurScope;
10378
10379   mutable IdentifierInfo *Ident_super;
10380   mutable IdentifierInfo *Ident___float128;
10381
10382   /// Nullability type specifiers.
10383   IdentifierInfo *Ident__Nonnull = nullptr;
10384   IdentifierInfo *Ident__Nullable = nullptr;
10385   IdentifierInfo *Ident__Null_unspecified = nullptr;
10386
10387   IdentifierInfo *Ident_NSError = nullptr;
10388
10389 protected:
10390   friend class Parser;
10391   friend class InitializationSequence;
10392   friend class ASTReader;
10393   friend class ASTDeclReader;
10394   friend class ASTWriter;
10395
10396 public:
10397   /// Retrieve the keyword associated
10398   IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
10399
10400   /// The struct behind the CFErrorRef pointer.
10401   RecordDecl *CFError = nullptr;
10402
10403   /// Retrieve the identifier "NSError".
10404   IdentifierInfo *getNSErrorIdent();
10405
10406   /// \brief Retrieve the parser's current scope.
10407   ///
10408   /// This routine must only be used when it is certain that semantic analysis
10409   /// and the parser are in precisely the same context, which is not the case
10410   /// when, e.g., we are performing any kind of template instantiation.
10411   /// Therefore, the only safe places to use this scope are in the parser
10412   /// itself and in routines directly invoked from the parser and *never* from
10413   /// template substitution or instantiation.
10414   Scope *getCurScope() const { return CurScope; }
10415
10416   void incrementMSManglingNumber() const {
10417     return CurScope->incrementMSManglingNumber();
10418   }
10419
10420   IdentifierInfo *getSuperIdentifier() const;
10421   IdentifierInfo *getFloat128Identifier() const;
10422
10423   Decl *getObjCDeclContext() const;
10424
10425   DeclContext *getCurLexicalContext() const {
10426     return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
10427   }
10428
10429   /// The diagnostic we should emit for \c D, and the declaration that
10430   /// originated it, or \c AR_Available.
10431   ///
10432   /// \param D The declaration to check.
10433   /// \param Message If non-null, this will be populated with the message from
10434   /// the availability attribute that is selected.
10435   std::pair<AvailabilityResult, const NamedDecl *>
10436   ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message);
10437
10438   const DeclContext *getCurObjCLexicalContext() const {
10439     const DeclContext *DC = getCurLexicalContext();
10440     // A category implicitly has the attribute of the interface.
10441     if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
10442       DC = CatD->getClassInterface();
10443     return DC;
10444   }
10445
10446   /// \brief To be used for checking whether the arguments being passed to
10447   /// function exceeds the number of parameters expected for it.
10448   static bool TooManyArguments(size_t NumParams, size_t NumArgs,
10449                                bool PartialOverloading = false) {
10450     // We check whether we're just after a comma in code-completion.
10451     if (NumArgs > 0 && PartialOverloading)
10452       return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
10453     return NumArgs > NumParams;
10454   }
10455
10456   // Emitting members of dllexported classes is delayed until the class
10457   // (including field initializers) is fully parsed.
10458   SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
10459
10460 private:
10461   /// \brief Helper class that collects misaligned member designations and
10462   /// their location info for delayed diagnostics.
10463   struct MisalignedMember {
10464     Expr *E;
10465     RecordDecl *RD;
10466     ValueDecl *MD;
10467     CharUnits Alignment;
10468
10469     MisalignedMember() : E(), RD(), MD(), Alignment() {}
10470     MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
10471                      CharUnits Alignment)
10472         : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
10473     explicit MisalignedMember(Expr *E)
10474         : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
10475
10476     bool operator==(const MisalignedMember &m) { return this->E == m.E; }
10477   };
10478   /// \brief Small set of gathered accesses to potentially misaligned members
10479   /// due to the packed attribute.
10480   SmallVector<MisalignedMember, 4> MisalignedMembers;
10481
10482   /// \brief Adds an expression to the set of gathered misaligned members.
10483   void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
10484                                      CharUnits Alignment);
10485
10486 public:
10487   /// \brief Diagnoses the current set of gathered accesses. This typically
10488   /// happens at full expression level. The set is cleared after emitting the
10489   /// diagnostics.
10490   void DiagnoseMisalignedMembers();
10491
10492   /// \brief This function checks if the expression is in the sef of potentially
10493   /// misaligned members and it is converted to some pointer type T with lower
10494   /// or equal alignment requirements. If so it removes it. This is used when
10495   /// we do not want to diagnose such misaligned access (e.g. in conversions to
10496   /// void*).
10497   void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
10498
10499   /// \brief This function calls Action when it determines that E designates a
10500   /// misaligned member due to the packed attribute. This is used to emit
10501   /// local diagnostics like in reference binding.
10502   void RefersToMemberWithReducedAlignment(
10503       Expr *E,
10504       llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
10505           Action);
10506 };
10507
10508 /// \brief RAII object that enters a new expression evaluation context.
10509 class EnterExpressionEvaluationContext {
10510   Sema &Actions;
10511   bool Entered = true;
10512
10513 public:
10514
10515   EnterExpressionEvaluationContext(Sema &Actions,
10516                                    Sema::ExpressionEvaluationContext NewContext,
10517                                    Decl *LambdaContextDecl = nullptr,
10518                                    bool IsDecltype = false,
10519                                    bool ShouldEnter = true)
10520       : Actions(Actions), Entered(ShouldEnter) {
10521     if (Entered)
10522       Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
10523                                               IsDecltype);
10524   }
10525   EnterExpressionEvaluationContext(Sema &Actions,
10526                                    Sema::ExpressionEvaluationContext NewContext,
10527                                    Sema::ReuseLambdaContextDecl_t,
10528                                    bool IsDecltype = false)
10529     : Actions(Actions) {
10530     Actions.PushExpressionEvaluationContext(NewContext,
10531                                             Sema::ReuseLambdaContextDecl,
10532                                             IsDecltype);
10533   }
10534
10535   enum InitListTag { InitList };
10536   EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
10537                                    bool ShouldEnter = true)
10538       : Actions(Actions), Entered(false) {
10539     // In C++11 onwards, narrowing checks are performed on the contents of
10540     // braced-init-lists, even when they occur within unevaluated operands.
10541     // Therefore we still need to instantiate constexpr functions used in such
10542     // a context.
10543     if (ShouldEnter && Actions.isUnevaluatedContext() &&
10544         Actions.getLangOpts().CPlusPlus11) {
10545       Actions.PushExpressionEvaluationContext(
10546           Sema::ExpressionEvaluationContext::UnevaluatedList, nullptr, false);
10547       Entered = true;
10548     }
10549   }
10550
10551   ~EnterExpressionEvaluationContext() {
10552     if (Entered)
10553       Actions.PopExpressionEvaluationContext();
10554   }
10555 };
10556
10557 DeductionFailureInfo
10558 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
10559                          sema::TemplateDeductionInfo &Info);
10560
10561 /// \brief Contains a late templated function.
10562 /// Will be parsed at the end of the translation unit, used by Sema & Parser.
10563 struct LateParsedTemplate {
10564   CachedTokens Toks;
10565   /// \brief The template function declaration to be late parsed.
10566   Decl *D;
10567 };
10568
10569 } // end namespace clang
10570
10571 namespace llvm {
10572 // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
10573 // SourceLocation.
10574 template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
10575   using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
10576   using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
10577
10578   static FunctionDeclAndLoc getEmptyKey() {
10579     return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
10580   }
10581
10582   static FunctionDeclAndLoc getTombstoneKey() {
10583     return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
10584   }
10585
10586   static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
10587     return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
10588                         FDL.Loc.getRawEncoding());
10589   }
10590
10591   static bool isEqual(const FunctionDeclAndLoc &LHS,
10592                       const FunctionDeclAndLoc &RHS) {
10593     return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
10594   }
10595 };
10596 } // namespace llvm
10597
10598 #endif