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