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