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