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