]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/AST/Decl.h
Merge llvm, clang, lld and lldb trunk r300890, and update build glue.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / include / clang / AST / Decl.h
1 //===--- Decl.h - Classes for representing declarations ---------*- 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 Decl subclasses.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_CLANG_AST_DECL_H
15 #define LLVM_CLANG_AST_DECL_H
16
17 #include "clang/AST/APValue.h"
18 #include "clang/AST/DeclBase.h"
19 #include "clang/AST/DeclarationName.h"
20 #include "clang/AST/ExternalASTSource.h"
21 #include "clang/AST/Redeclarable.h"
22 #include "clang/AST/Type.h"
23 #include "clang/Basic/Linkage.h"
24 #include "clang/Basic/Module.h"
25 #include "clang/Basic/OperatorKinds.h"
26 #include "clang/Basic/PragmaKinds.h"
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/ADT/Optional.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/TrailingObjects.h"
32
33 namespace clang {
34 struct ASTTemplateArgumentListInfo;
35 class CXXTemporary;
36 class CompoundStmt;
37 class DependentFunctionTemplateSpecializationInfo;
38 class Expr;
39 class FunctionTemplateDecl;
40 class FunctionTemplateSpecializationInfo;
41 class LabelStmt;
42 class MemberSpecializationInfo;
43 class NestedNameSpecifier;
44 class ParmVarDecl;
45 class Stmt;
46 class StringLiteral;
47 class TemplateArgumentList;
48 class TemplateParameterList;
49 class TypeAliasTemplateDecl;
50 class TypeLoc;
51 class UnresolvedSetImpl;
52 class VarTemplateDecl;
53
54 /// \brief A container of type source information.
55 ///
56 /// A client can read the relevant info using TypeLoc wrappers, e.g:
57 /// @code
58 /// TypeLoc TL = TypeSourceInfo->getTypeLoc();
59 /// TL.getStartLoc().print(OS, SrcMgr);
60 /// @endcode
61 ///
62 class TypeSourceInfo {
63   QualType Ty;
64   // Contains a memory block after the class, used for type source information,
65   // allocated by ASTContext.
66   friend class ASTContext;
67   TypeSourceInfo(QualType ty) : Ty(ty) { }
68 public:
69   /// \brief Return the type wrapped by this type source info.
70   QualType getType() const { return Ty; }
71
72   /// \brief Return the TypeLoc wrapper for the type source info.
73   TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
74   
75   /// \brief Override the type stored in this TypeSourceInfo. Use with caution!
76   void overrideType(QualType T) { Ty = T; }
77 };
78
79 /// TranslationUnitDecl - The top declaration context.
80 class TranslationUnitDecl : public Decl, public DeclContext {
81   virtual void anchor();
82   ASTContext &Ctx;
83
84   /// The (most recently entered) anonymous namespace for this
85   /// translation unit, if one has been created.
86   NamespaceDecl *AnonymousNamespace;
87
88   explicit TranslationUnitDecl(ASTContext &ctx);
89 public:
90   ASTContext &getASTContext() const { return Ctx; }
91
92   NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
93   void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
94
95   static TranslationUnitDecl *Create(ASTContext &C);
96   // Implement isa/cast/dyncast/etc.
97   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
98   static bool classofKind(Kind K) { return K == TranslationUnit; }
99   static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
100     return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
101   }
102   static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
103     return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
104   }
105 };
106
107 /// \brief Represents a `#pragma comment` line. Always a child of
108 /// TranslationUnitDecl.
109 class PragmaCommentDecl final
110     : public Decl,
111       private llvm::TrailingObjects<PragmaCommentDecl, char> {
112   virtual void anchor();
113
114   PragmaMSCommentKind CommentKind;
115
116   friend TrailingObjects;
117   friend class ASTDeclReader;
118   friend class ASTDeclWriter;
119
120   PragmaCommentDecl(TranslationUnitDecl *TU, SourceLocation CommentLoc,
121                     PragmaMSCommentKind CommentKind)
122       : Decl(PragmaComment, TU, CommentLoc), CommentKind(CommentKind) {}
123
124 public:
125   static PragmaCommentDecl *Create(const ASTContext &C, TranslationUnitDecl *DC,
126                                    SourceLocation CommentLoc,
127                                    PragmaMSCommentKind CommentKind,
128                                    StringRef Arg);
129   static PragmaCommentDecl *CreateDeserialized(ASTContext &C, unsigned ID,
130                                                unsigned ArgSize);
131
132   PragmaMSCommentKind getCommentKind() const { return CommentKind; }
133
134   StringRef getArg() const { return getTrailingObjects<char>(); }
135
136   // Implement isa/cast/dyncast/etc.
137   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
138   static bool classofKind(Kind K) { return K == PragmaComment; }
139 };
140
141 /// \brief Represents a `#pragma detect_mismatch` line. Always a child of
142 /// TranslationUnitDecl.
143 class PragmaDetectMismatchDecl final
144     : public Decl,
145       private llvm::TrailingObjects<PragmaDetectMismatchDecl, char> {
146   virtual void anchor();
147
148   size_t ValueStart;
149
150   friend TrailingObjects;
151   friend class ASTDeclReader;
152   friend class ASTDeclWriter;
153
154   PragmaDetectMismatchDecl(TranslationUnitDecl *TU, SourceLocation Loc,
155                            size_t ValueStart)
156       : Decl(PragmaDetectMismatch, TU, Loc), ValueStart(ValueStart) {}
157
158 public:
159   static PragmaDetectMismatchDecl *Create(const ASTContext &C,
160                                           TranslationUnitDecl *DC,
161                                           SourceLocation Loc, StringRef Name,
162                                           StringRef Value);
163   static PragmaDetectMismatchDecl *
164   CreateDeserialized(ASTContext &C, unsigned ID, unsigned NameValueSize);
165
166   StringRef getName() const { return getTrailingObjects<char>(); }
167   StringRef getValue() const { return getTrailingObjects<char>() + ValueStart; }
168
169   // Implement isa/cast/dyncast/etc.
170   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
171   static bool classofKind(Kind K) { return K == PragmaDetectMismatch; }
172 };
173
174 /// \brief Declaration context for names declared as extern "C" in C++. This
175 /// is neither the semantic nor lexical context for such declarations, but is
176 /// used to check for conflicts with other extern "C" declarations. Example:
177 ///
178 /// \code
179 ///   namespace N { extern "C" void f(); } // #1
180 ///   void N::f() {}                       // #2
181 ///   namespace M { extern "C" void f(); } // #3
182 /// \endcode
183 ///
184 /// The semantic context of #1 is namespace N and its lexical context is the
185 /// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical
186 /// context is the TU. However, both declarations are also visible in the
187 /// extern "C" context.
188 ///
189 /// The declaration at #3 finds it is a redeclaration of \c N::f through
190 /// lookup in the extern "C" context.
191 class ExternCContextDecl : public Decl, public DeclContext {
192   virtual void anchor();
193
194   explicit ExternCContextDecl(TranslationUnitDecl *TU)
195     : Decl(ExternCContext, TU, SourceLocation()),
196       DeclContext(ExternCContext) {}
197 public:
198   static ExternCContextDecl *Create(const ASTContext &C,
199                                     TranslationUnitDecl *TU);
200   // Implement isa/cast/dyncast/etc.
201   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
202   static bool classofKind(Kind K) { return K == ExternCContext; }
203   static DeclContext *castToDeclContext(const ExternCContextDecl *D) {
204     return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D));
205   }
206   static ExternCContextDecl *castFromDeclContext(const DeclContext *DC) {
207     return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC));
208   }
209 };
210
211 /// NamedDecl - This represents a decl with a name.  Many decls have names such
212 /// as ObjCMethodDecl, but not \@class, etc.
213 class NamedDecl : public Decl {
214   virtual void anchor();
215   /// Name - The name of this declaration, which is typically a normal
216   /// identifier but may also be a special kind of name (C++
217   /// constructor, Objective-C selector, etc.)
218   DeclarationName Name;
219
220 private:
221   NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY;
222
223 protected:
224   NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
225     : Decl(DK, DC, L), Name(N) { }
226
227 public:
228   /// getIdentifier - Get the identifier that names this declaration,
229   /// if there is one. This will return NULL if this declaration has
230   /// no name (e.g., for an unnamed class) or if the name is a special
231   /// name (C++ constructor, Objective-C selector, etc.).
232   IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
233
234   /// getName - Get the name of identifier for this declaration as a StringRef.
235   /// This requires that the declaration have a name and that it be a simple
236   /// identifier.
237   StringRef getName() const {
238     assert(Name.isIdentifier() && "Name is not a simple identifier");
239     return getIdentifier() ? getIdentifier()->getName() : "";
240   }
241
242   /// getNameAsString - Get a human-readable name for the declaration, even if
243   /// it is one of the special kinds of names (C++ constructor, Objective-C
244   /// selector, etc).  Creating this name requires expensive string
245   /// manipulation, so it should be called only when performance doesn't matter.
246   /// For simple declarations, getNameAsCString() should suffice.
247   //
248   // FIXME: This function should be renamed to indicate that it is not just an
249   // alternate form of getName(), and clients should move as appropriate.
250   //
251   // FIXME: Deprecated, move clients to getName().
252   std::string getNameAsString() const { return Name.getAsString(); }
253
254   virtual void printName(raw_ostream &os) const;
255
256   /// getDeclName - Get the actual, stored name of the declaration,
257   /// which may be a special name.
258   DeclarationName getDeclName() const { return Name; }
259
260   /// \brief Set the name of this declaration.
261   void setDeclName(DeclarationName N) { Name = N; }
262
263   /// printQualifiedName - Returns human-readable qualified name for
264   /// declaration, like A::B::i, for i being member of namespace A::B.
265   /// If declaration is not member of context which can be named (record,
266   /// namespace), it will return same result as printName().
267   /// Creating this name is expensive, so it should be called only when
268   /// performance doesn't matter.
269   void printQualifiedName(raw_ostream &OS) const;
270   void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
271
272   // FIXME: Remove string version.
273   std::string getQualifiedNameAsString() const;
274
275   /// getNameForDiagnostic - Appends a human-readable name for this
276   /// declaration into the given stream.
277   ///
278   /// This is the method invoked by Sema when displaying a NamedDecl
279   /// in a diagnostic.  It does not necessarily produce the same
280   /// result as printName(); for example, class template
281   /// specializations are printed with their template arguments.
282   virtual void getNameForDiagnostic(raw_ostream &OS,
283                                     const PrintingPolicy &Policy,
284                                     bool Qualified) const;
285
286   /// \brief Determine whether this declaration, if
287   /// known to be well-formed within its context, will replace the
288   /// declaration OldD if introduced into scope. A declaration will
289   /// replace another declaration if, for example, it is a
290   /// redeclaration of the same variable or function, but not if it is
291   /// a declaration of a different kind (function vs. class) or an
292   /// overloaded function.
293   ///
294   /// \param IsKnownNewer \c true if this declaration is known to be newer
295   /// than \p OldD (for instance, if this declaration is newly-created).
296   bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const;
297
298   /// \brief Determine whether this declaration has linkage.
299   bool hasLinkage() const;
300
301   using Decl::isModulePrivate;
302   using Decl::setModulePrivate;
303
304   /// \brief Determine whether this declaration is hidden from name lookup.
305   bool isHidden() const { return Hidden; }
306
307   /// \brief Set whether this declaration is hidden from name lookup.
308   void setHidden(bool Hide) {
309     assert((!Hide || isFromASTFile() || hasLocalOwningModuleStorage()) &&
310            "declaration with no owning module can't be hidden");
311     Hidden = Hide;
312   }
313
314   /// \brief Determine whether this declaration is a C++ class member.
315   bool isCXXClassMember() const {
316     const DeclContext *DC = getDeclContext();
317
318     // C++0x [class.mem]p1:
319     //   The enumerators of an unscoped enumeration defined in
320     //   the class are members of the class.
321     if (isa<EnumDecl>(DC))
322       DC = DC->getRedeclContext();
323
324     return DC->isRecord();
325   }
326
327   /// \brief Determine whether the given declaration is an instance member of
328   /// a C++ class.
329   bool isCXXInstanceMember() const;
330
331   /// \brief Determine what kind of linkage this entity has.
332   /// This is not the linkage as defined by the standard or the codegen notion
333   /// of linkage. It is just an implementation detail that is used to compute
334   /// those.
335   Linkage getLinkageInternal() const;
336
337   /// \brief Get the linkage from a semantic point of view. Entities in
338   /// anonymous namespaces are external (in c++98).
339   Linkage getFormalLinkage() const {
340     return clang::getFormalLinkage(getLinkageInternal());
341   }
342
343   /// \brief True if this decl has external linkage.
344   bool hasExternalFormalLinkage() const {
345     return isExternalFormalLinkage(getLinkageInternal());
346   }
347
348   bool isExternallyVisible() const {
349     return clang::isExternallyVisible(getLinkageInternal());
350   }
351
352   /// \brief Determines the visibility of this entity.
353   Visibility getVisibility() const {
354     return getLinkageAndVisibility().getVisibility();
355   }
356
357   /// \brief Determines the linkage and visibility of this entity.
358   LinkageInfo getLinkageAndVisibility() const;
359
360   /// Kinds of explicit visibility.
361   enum ExplicitVisibilityKind {
362     VisibilityForType,
363     VisibilityForValue
364   };
365
366   /// \brief If visibility was explicitly specified for this
367   /// declaration, return that visibility.
368   Optional<Visibility>
369   getExplicitVisibility(ExplicitVisibilityKind kind) const;
370
371   /// \brief True if the computed linkage is valid. Used for consistency
372   /// checking. Should always return true.
373   bool isLinkageValid() const;
374
375   /// \brief True if something has required us to compute the linkage
376   /// of this declaration.
377   ///
378   /// Language features which can retroactively change linkage (like a
379   /// typedef name for linkage purposes) may need to consider this,
380   /// but hopefully only in transitory ways during parsing.
381   bool hasLinkageBeenComputed() const {
382     return hasCachedLinkage();
383   }
384
385   /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for
386   /// the underlying named decl.
387   NamedDecl *getUnderlyingDecl() {
388     // Fast-path the common case.
389     if (this->getKind() != UsingShadow &&
390         this->getKind() != ConstructorUsingShadow &&
391         this->getKind() != ObjCCompatibleAlias &&
392         this->getKind() != NamespaceAlias)
393       return this;
394
395     return getUnderlyingDeclImpl();
396   }
397   const NamedDecl *getUnderlyingDecl() const {
398     return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
399   }
400
401   NamedDecl *getMostRecentDecl() {
402     return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl());
403   }
404   const NamedDecl *getMostRecentDecl() const {
405     return const_cast<NamedDecl*>(this)->getMostRecentDecl();
406   }
407
408   ObjCStringFormatFamily getObjCFStringFormattingFamily() const;
409
410   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
411   static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
412 };
413
414 inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
415   ND.printName(OS);
416   return OS;
417 }
418
419 /// LabelDecl - Represents the declaration of a label.  Labels also have a
420 /// corresponding LabelStmt, which indicates the position that the label was
421 /// defined at.  For normal labels, the location of the decl is the same as the
422 /// location of the statement.  For GNU local labels (__label__), the decl
423 /// location is where the __label__ is.
424 class LabelDecl : public NamedDecl {
425   void anchor() override;
426   LabelStmt *TheStmt;
427   StringRef MSAsmName;
428   bool MSAsmNameResolved;
429   /// LocStart - For normal labels, this is the same as the main declaration
430   /// label, i.e., the location of the identifier; for GNU local labels,
431   /// this is the location of the __label__ keyword.
432   SourceLocation LocStart;
433
434   LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
435             LabelStmt *S, SourceLocation StartL)
436     : NamedDecl(Label, DC, IdentL, II),
437       TheStmt(S),
438       MSAsmNameResolved(false),
439       LocStart(StartL) {}
440
441 public:
442   static LabelDecl *Create(ASTContext &C, DeclContext *DC,
443                            SourceLocation IdentL, IdentifierInfo *II);
444   static LabelDecl *Create(ASTContext &C, DeclContext *DC,
445                            SourceLocation IdentL, IdentifierInfo *II,
446                            SourceLocation GnuLabelL);
447   static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
448   
449   LabelStmt *getStmt() const { return TheStmt; }
450   void setStmt(LabelStmt *T) { TheStmt = T; }
451
452   bool isGnuLocal() const { return LocStart != getLocation(); }
453   void setLocStart(SourceLocation L) { LocStart = L; }
454
455   SourceRange getSourceRange() const override LLVM_READONLY {
456     return SourceRange(LocStart, getLocation());
457   }
458
459   bool isMSAsmLabel() const { return MSAsmName.size() != 0; }
460   bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; }
461   void setMSAsmLabel(StringRef Name);
462   StringRef getMSAsmLabel() const { return MSAsmName; }
463   void setMSAsmLabelResolved() { MSAsmNameResolved = true; }
464
465   // Implement isa/cast/dyncast/etc.
466   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
467   static bool classofKind(Kind K) { return K == Label; }
468 };
469
470 /// NamespaceDecl - Represent a C++ namespace.
471 class NamespaceDecl : public NamedDecl, public DeclContext, 
472                       public Redeclarable<NamespaceDecl> 
473 {
474   /// LocStart - The starting location of the source range, pointing
475   /// to either the namespace or the inline keyword.
476   SourceLocation LocStart;
477   /// RBraceLoc - The ending location of the source range.
478   SourceLocation RBraceLoc;
479
480   /// \brief A pointer to either the anonymous namespace that lives just inside
481   /// this namespace or to the first namespace in the chain (the latter case
482   /// only when this is not the first in the chain), along with a 
483   /// boolean value indicating whether this is an inline namespace.
484   llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
485
486   NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
487                 SourceLocation StartLoc, SourceLocation IdLoc,
488                 IdentifierInfo *Id, NamespaceDecl *PrevDecl);
489
490   typedef Redeclarable<NamespaceDecl> redeclarable_base;
491   NamespaceDecl *getNextRedeclarationImpl() override;
492   NamespaceDecl *getPreviousDeclImpl() override;
493   NamespaceDecl *getMostRecentDeclImpl() override;
494
495 public:
496   static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
497                                bool Inline, SourceLocation StartLoc,
498                                SourceLocation IdLoc, IdentifierInfo *Id,
499                                NamespaceDecl *PrevDecl);
500
501   static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
502
503   typedef redeclarable_base::redecl_range redecl_range;
504   typedef redeclarable_base::redecl_iterator redecl_iterator;
505   using redeclarable_base::redecls_begin;
506   using redeclarable_base::redecls_end;
507   using redeclarable_base::redecls;
508   using redeclarable_base::getPreviousDecl;
509   using redeclarable_base::getMostRecentDecl;
510   using redeclarable_base::isFirstDecl;
511
512   /// \brief Returns true if this is an anonymous namespace declaration.
513   ///
514   /// For example:
515   /// \code
516   ///   namespace {
517   ///     ...
518   ///   };
519   /// \endcode
520   /// q.v. C++ [namespace.unnamed]
521   bool isAnonymousNamespace() const {
522     return !getIdentifier();
523   }
524
525   /// \brief Returns true if this is an inline namespace declaration.
526   bool isInline() const {
527     return AnonOrFirstNamespaceAndInline.getInt();
528   }
529
530   /// \brief Set whether this is an inline namespace declaration.
531   void setInline(bool Inline) {
532     AnonOrFirstNamespaceAndInline.setInt(Inline);
533   }
534
535   /// \brief Get the original (first) namespace declaration.
536   NamespaceDecl *getOriginalNamespace();
537
538   /// \brief Get the original (first) namespace declaration.
539   const NamespaceDecl *getOriginalNamespace() const;
540
541   /// \brief Return true if this declaration is an original (first) declaration
542   /// of the namespace. This is false for non-original (subsequent) namespace
543   /// declarations and anonymous namespaces.
544   bool isOriginalNamespace() const;
545
546   /// \brief Retrieve the anonymous namespace nested inside this namespace,
547   /// if any.
548   NamespaceDecl *getAnonymousNamespace() const {
549     return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
550   }
551
552   void setAnonymousNamespace(NamespaceDecl *D) {
553     getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
554   }
555
556   /// Retrieves the canonical declaration of this namespace.
557   NamespaceDecl *getCanonicalDecl() override {
558     return getOriginalNamespace();
559   }
560   const NamespaceDecl *getCanonicalDecl() const {
561     return getOriginalNamespace();
562   }
563
564   SourceRange getSourceRange() const override LLVM_READONLY {
565     return SourceRange(LocStart, RBraceLoc);
566   }
567
568   SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
569   SourceLocation getRBraceLoc() const { return RBraceLoc; }
570   void setLocStart(SourceLocation L) { LocStart = L; }
571   void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
572
573   // Implement isa/cast/dyncast/etc.
574   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
575   static bool classofKind(Kind K) { return K == Namespace; }
576   static DeclContext *castToDeclContext(const NamespaceDecl *D) {
577     return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
578   }
579   static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
580     return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
581   }
582
583   friend class ASTDeclReader;
584   friend class ASTDeclWriter;
585 };
586
587 /// ValueDecl - Represent the declaration of a variable (in which case it is
588 /// an lvalue) a function (in which case it is a function designator) or
589 /// an enum constant.
590 class ValueDecl : public NamedDecl {
591   void anchor() override;
592   QualType DeclType;
593
594 protected:
595   ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
596             DeclarationName N, QualType T)
597     : NamedDecl(DK, DC, L, N), DeclType(T) {}
598 public:
599   QualType getType() const { return DeclType; }
600   void setType(QualType newType) { DeclType = newType; }
601
602   /// \brief Determine whether this symbol is weakly-imported,
603   ///        or declared with the weak or weak-ref attr.
604   bool isWeak() const;
605
606   // Implement isa/cast/dyncast/etc.
607   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
608   static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
609 };
610
611 /// QualifierInfo - A struct with extended info about a syntactic
612 /// name qualifier, to be used for the case of out-of-line declarations.
613 struct QualifierInfo {
614   NestedNameSpecifierLoc QualifierLoc;
615
616   /// NumTemplParamLists - The number of "outer" template parameter lists.
617   /// The count includes all of the template parameter lists that were matched
618   /// against the template-ids occurring into the NNS and possibly (in the
619   /// case of an explicit specialization) a final "template <>".
620   unsigned NumTemplParamLists;
621
622   /// TemplParamLists - A new-allocated array of size NumTemplParamLists,
623   /// containing pointers to the "outer" template parameter lists.
624   /// It includes all of the template parameter lists that were matched
625   /// against the template-ids occurring into the NNS and possibly (in the
626   /// case of an explicit specialization) a final "template <>".
627   TemplateParameterList** TemplParamLists;
628
629   /// Default constructor.
630   QualifierInfo()
631     : QualifierLoc(), NumTemplParamLists(0), TemplParamLists(nullptr) {}
632
633   /// setTemplateParameterListsInfo - Sets info about "outer" template
634   /// parameter lists.
635   void setTemplateParameterListsInfo(ASTContext &Context,
636                                      ArrayRef<TemplateParameterList *> TPLists);
637
638 private:
639   // Copy constructor and copy assignment are disabled.
640   QualifierInfo(const QualifierInfo&) = delete;
641   QualifierInfo& operator=(const QualifierInfo&) = delete;
642 };
643
644 /// \brief Represents a ValueDecl that came out of a declarator.
645 /// Contains type source information through TypeSourceInfo.
646 class DeclaratorDecl : public ValueDecl {
647   // A struct representing both a TInfo and a syntactic qualifier,
648   // to be used for the (uncommon) case of out-of-line declarations.
649   struct ExtInfo : public QualifierInfo {
650     TypeSourceInfo *TInfo;
651   };
652
653   llvm::PointerUnion<TypeSourceInfo*, ExtInfo*> DeclInfo;
654
655   /// InnerLocStart - The start of the source range for this declaration,
656   /// ignoring outer template declarations.
657   SourceLocation InnerLocStart;
658
659   bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
660   ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
661   const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
662
663 protected:
664   DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
665                  DeclarationName N, QualType T, TypeSourceInfo *TInfo,
666                  SourceLocation StartL)
667     : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {
668   }
669
670 public:
671   TypeSourceInfo *getTypeSourceInfo() const {
672     return hasExtInfo()
673       ? getExtInfo()->TInfo
674       : DeclInfo.get<TypeSourceInfo*>();
675   }
676   void setTypeSourceInfo(TypeSourceInfo *TI) {
677     if (hasExtInfo())
678       getExtInfo()->TInfo = TI;
679     else
680       DeclInfo = TI;
681   }
682
683   /// getInnerLocStart - Return SourceLocation representing start of source
684   /// range ignoring outer template declarations.
685   SourceLocation getInnerLocStart() const { return InnerLocStart; }
686   void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
687
688   /// getOuterLocStart - Return SourceLocation representing start of source
689   /// range taking into account any outer template declarations.
690   SourceLocation getOuterLocStart() const;
691
692   SourceRange getSourceRange() const override LLVM_READONLY;
693   SourceLocation getLocStart() const LLVM_READONLY {
694     return getOuterLocStart();
695   }
696
697   /// \brief Retrieve the nested-name-specifier that qualifies the name of this
698   /// declaration, if it was present in the source.
699   NestedNameSpecifier *getQualifier() const {
700     return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
701                         : nullptr;
702   }
703
704   /// \brief Retrieve the nested-name-specifier (with source-location
705   /// information) that qualifies the name of this declaration, if it was
706   /// present in the source.
707   NestedNameSpecifierLoc getQualifierLoc() const {
708     return hasExtInfo() ? getExtInfo()->QualifierLoc
709                         : NestedNameSpecifierLoc();
710   }
711
712   void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
713
714   unsigned getNumTemplateParameterLists() const {
715     return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
716   }
717   TemplateParameterList *getTemplateParameterList(unsigned index) const {
718     assert(index < getNumTemplateParameterLists());
719     return getExtInfo()->TemplParamLists[index];
720   }
721   void setTemplateParameterListsInfo(ASTContext &Context,
722                                      ArrayRef<TemplateParameterList *> TPLists);
723
724   SourceLocation getTypeSpecStartLoc() const;
725
726   // Implement isa/cast/dyncast/etc.
727   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
728   static bool classofKind(Kind K) {
729     return K >= firstDeclarator && K <= lastDeclarator;
730   }
731
732   friend class ASTDeclReader;
733   friend class ASTDeclWriter;
734 };
735
736 /// \brief Structure used to store a statement, the constant value to
737 /// which it was evaluated (if any), and whether or not the statement
738 /// is an integral constant expression (if known).
739 struct EvaluatedStmt {
740   EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
741                     CheckingICE(false), IsICE(false) { }
742
743   /// \brief Whether this statement was already evaluated.
744   bool WasEvaluated : 1;
745
746   /// \brief Whether this statement is being evaluated.
747   bool IsEvaluating : 1;
748
749   /// \brief Whether we already checked whether this statement was an
750   /// integral constant expression.
751   bool CheckedICE : 1;
752
753   /// \brief Whether we are checking whether this statement is an
754   /// integral constant expression.
755   bool CheckingICE : 1;
756
757   /// \brief Whether this statement is an integral constant expression,
758   /// or in C++11, whether the statement is a constant expression. Only
759   /// valid if CheckedICE is true.
760   bool IsICE : 1;
761
762   Stmt *Value;
763   APValue Evaluated;
764 };
765
766 /// VarDecl - An instance of this class is created to represent a variable
767 /// declaration or definition.
768 class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
769 public:
770   /// getStorageClassSpecifierString - Return the string used to
771   /// specify the storage class \p SC.
772   ///
773   /// It is illegal to call this function with SC == None.
774   static const char *getStorageClassSpecifierString(StorageClass SC);
775
776   /// \brief Initialization styles.
777   enum InitializationStyle {
778     CInit,    ///< C-style initialization with assignment
779     CallInit, ///< Call-style initialization (C++98)
780     ListInit  ///< Direct list-initialization (C++11)
781   };
782
783   /// \brief Kinds of thread-local storage.
784   enum TLSKind {
785     TLS_None,   ///< Not a TLS variable.
786     TLS_Static, ///< TLS with a known-constant initializer.
787     TLS_Dynamic ///< TLS with a dynamic initializer.
788   };
789
790 protected:
791   // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we
792   // have allocated the auxiliary struct of information there.
793   //
794   // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for
795   // this as *many* VarDecls are ParmVarDecls that don't have default
796   // arguments. We could save some space by moving this pointer union to be
797   // allocated in trailing space when necessary.
798   typedef llvm::PointerUnion<Stmt *, EvaluatedStmt *> InitType;
799
800   /// \brief The initializer for this variable or, for a ParmVarDecl, the
801   /// C++ default argument.
802   mutable InitType Init;
803
804 private:
805   class VarDeclBitfields {
806     friend class VarDecl;
807     friend class ASTDeclReader;
808
809     unsigned SClass : 3;
810     unsigned TSCSpec : 2;
811     unsigned InitStyle : 2;
812   };
813   enum { NumVarDeclBits = 7 };
814
815   friend class ASTDeclReader;
816   friend class StmtIteratorBase;
817   friend class ASTNodeImporter;
818
819 protected:
820   enum { NumParameterIndexBits = 8 };
821
822   enum DefaultArgKind {
823     DAK_None,
824     DAK_Unparsed,
825     DAK_Uninstantiated,
826     DAK_Normal
827   };
828
829   class ParmVarDeclBitfields {
830     friend class ParmVarDecl;
831     friend class ASTDeclReader;
832
833     unsigned : NumVarDeclBits;
834
835     /// Whether this parameter inherits a default argument from a
836     /// prior declaration.
837     unsigned HasInheritedDefaultArg : 1;
838
839     /// Describes the kind of default argument for this parameter. By default
840     /// this is none. If this is normal, then the default argument is stored in
841     /// the \c VarDecl initializer expression unless we were unable to parse
842     /// (even an invalid) expression for the default argument.
843     unsigned DefaultArgKind : 2;
844
845     /// Whether this parameter undergoes K&R argument promotion.
846     unsigned IsKNRPromoted : 1;
847
848     /// Whether this parameter is an ObjC method parameter or not.
849     unsigned IsObjCMethodParam : 1;
850
851     /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
852     /// Otherwise, the number of function parameter scopes enclosing
853     /// the function parameter scope in which this parameter was
854     /// declared.
855     unsigned ScopeDepthOrObjCQuals : 7;
856
857     /// The number of parameters preceding this parameter in the
858     /// function parameter scope in which it was declared.
859     unsigned ParameterIndex : NumParameterIndexBits;
860   };
861
862   class NonParmVarDeclBitfields {
863     friend class VarDecl;
864     friend class ASTDeclReader;
865
866     unsigned : NumVarDeclBits;
867
868     // FIXME: We need something similar to CXXRecordDecl::DefinitionData.
869     /// \brief Whether this variable is a definition which was demoted due to
870     /// module merge.
871     unsigned IsThisDeclarationADemotedDefinition : 1;
872
873     /// \brief Whether this variable is the exception variable in a C++ catch
874     /// or an Objective-C @catch statement.
875     unsigned ExceptionVar : 1;
876
877     /// \brief Whether this local variable could be allocated in the return
878     /// slot of its function, enabling the named return value optimization
879     /// (NRVO).
880     unsigned NRVOVariable : 1;
881
882     /// \brief Whether this variable is the for-range-declaration in a C++0x
883     /// for-range statement.
884     unsigned CXXForRangeDecl : 1;
885
886     /// \brief Whether this variable is an ARC pseudo-__strong
887     /// variable;  see isARCPseudoStrong() for details.
888     unsigned ARCPseudoStrong : 1;
889
890     /// \brief Whether this variable is (C++1z) inline.
891     unsigned IsInline : 1;
892
893     /// \brief Whether this variable has (C++1z) inline explicitly specified.
894     unsigned IsInlineSpecified : 1;
895
896     /// \brief Whether this variable is (C++0x) constexpr.
897     unsigned IsConstexpr : 1;
898
899     /// \brief Whether this variable is the implicit variable for a lambda
900     /// init-capture.
901     unsigned IsInitCapture : 1;
902
903     /// \brief Whether this local extern variable's previous declaration was
904     /// declared in the same block scope. This controls whether we should merge
905     /// the type of this declaration with its previous declaration.
906     unsigned PreviousDeclInSameBlockScope : 1;
907   };
908
909   union {
910     unsigned AllBits;
911     VarDeclBitfields VarDeclBits;
912     ParmVarDeclBitfields ParmVarDeclBits;
913     NonParmVarDeclBitfields NonParmVarDeclBits;
914   };
915
916   VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
917           SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
918           TypeSourceInfo *TInfo, StorageClass SC);
919
920   typedef Redeclarable<VarDecl> redeclarable_base;
921   VarDecl *getNextRedeclarationImpl() override {
922     return getNextRedeclaration();
923   }
924   VarDecl *getPreviousDeclImpl() override {
925     return getPreviousDecl();
926   }
927   VarDecl *getMostRecentDeclImpl() override {
928     return getMostRecentDecl();
929   }
930
931 public:
932   typedef redeclarable_base::redecl_range redecl_range;
933   typedef redeclarable_base::redecl_iterator redecl_iterator;
934   using redeclarable_base::redecls_begin;
935   using redeclarable_base::redecls_end;
936   using redeclarable_base::redecls;
937   using redeclarable_base::getPreviousDecl;
938   using redeclarable_base::getMostRecentDecl;
939   using redeclarable_base::isFirstDecl;
940
941   static VarDecl *Create(ASTContext &C, DeclContext *DC,
942                          SourceLocation StartLoc, SourceLocation IdLoc,
943                          IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
944                          StorageClass S);
945
946   static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
947
948   SourceRange getSourceRange() const override LLVM_READONLY;
949
950   /// \brief Returns the storage class as written in the source. For the
951   /// computed linkage of symbol, see getLinkage.
952   StorageClass getStorageClass() const {
953     return (StorageClass) VarDeclBits.SClass;
954   }
955   void setStorageClass(StorageClass SC);
956
957   void setTSCSpec(ThreadStorageClassSpecifier TSC) {
958     VarDeclBits.TSCSpec = TSC;
959     assert(VarDeclBits.TSCSpec == TSC && "truncation");
960   }
961   ThreadStorageClassSpecifier getTSCSpec() const {
962     return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
963   }
964   TLSKind getTLSKind() const;
965
966   /// hasLocalStorage - Returns true if a variable with function scope
967   ///  is a non-static local variable.
968   bool hasLocalStorage() const {
969     if (getStorageClass() == SC_None)
970       // Second check is for C++11 [dcl.stc]p4.
971       return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
972
973     // Global Named Register (GNU extension)
974     if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
975       return false;
976
977     // Return true for:  Auto, Register.
978     // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
979
980     return getStorageClass() >= SC_Auto;
981   }
982
983   /// isStaticLocal - Returns true if a variable with function scope is a
984   /// static local variable.
985   bool isStaticLocal() const {
986     return (getStorageClass() == SC_Static ||
987             // C++11 [dcl.stc]p4
988             (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
989       && !isFileVarDecl();
990   }
991
992   /// \brief Returns true if a variable has extern or __private_extern__
993   /// storage.
994   bool hasExternalStorage() const {
995     return getStorageClass() == SC_Extern ||
996            getStorageClass() == SC_PrivateExtern;
997   }
998
999   /// \brief Returns true for all variables that do not have local storage.
1000   ///
1001   /// This includes all global variables as well as static variables declared
1002   /// within a function.
1003   bool hasGlobalStorage() const { return !hasLocalStorage(); }
1004
1005   /// \brief Get the storage duration of this variable, per C++ [basic.stc].
1006   StorageDuration getStorageDuration() const {
1007     return hasLocalStorage() ? SD_Automatic :
1008            getTSCSpec() ? SD_Thread : SD_Static;
1009   }
1010
1011   /// \brief Compute the language linkage.
1012   LanguageLinkage getLanguageLinkage() const;
1013
1014   /// \brief Determines whether this variable is a variable with
1015   /// external, C linkage.
1016   bool isExternC() const;
1017
1018   /// \brief Determines whether this variable's context is, or is nested within,
1019   /// a C++ extern "C" linkage spec.
1020   bool isInExternCContext() const;
1021
1022   /// \brief Determines whether this variable's context is, or is nested within,
1023   /// a C++ extern "C++" linkage spec.
1024   bool isInExternCXXContext() const;
1025
1026   /// isLocalVarDecl - Returns true for local variable declarations
1027   /// other than parameters.  Note that this includes static variables
1028   /// inside of functions. It also includes variables inside blocks.
1029   ///
1030   ///   void foo() { int x; static int y; extern int z; }
1031   ///
1032   bool isLocalVarDecl() const {
1033     if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1034       return false;
1035     if (const DeclContext *DC = getLexicalDeclContext())
1036       return DC->getRedeclContext()->isFunctionOrMethod();
1037     return false;
1038   }
1039
1040   /// \brief Similar to isLocalVarDecl but also includes parameters.
1041   bool isLocalVarDeclOrParm() const {
1042     return isLocalVarDecl() || getKind() == Decl::ParmVar;
1043   }
1044
1045   /// isFunctionOrMethodVarDecl - Similar to isLocalVarDecl, but
1046   /// excludes variables declared in blocks.
1047   bool isFunctionOrMethodVarDecl() const {
1048     if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1049       return false;
1050     const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
1051     return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
1052   }
1053
1054   /// \brief Determines whether this is a static data member.
1055   ///
1056   /// This will only be true in C++, and applies to, e.g., the
1057   /// variable 'x' in:
1058   /// \code
1059   /// struct S {
1060   ///   static int x;
1061   /// };
1062   /// \endcode
1063   bool isStaticDataMember() const {
1064     // If it wasn't static, it would be a FieldDecl.
1065     return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
1066   }
1067
1068   VarDecl *getCanonicalDecl() override;
1069   const VarDecl *getCanonicalDecl() const {
1070     return const_cast<VarDecl*>(this)->getCanonicalDecl();
1071   }
1072
1073   enum DefinitionKind {
1074     DeclarationOnly,      ///< This declaration is only a declaration.
1075     TentativeDefinition,  ///< This declaration is a tentative definition.
1076     Definition            ///< This declaration is definitely a definition.
1077   };
1078
1079   /// \brief Check whether this declaration is a definition. If this could be
1080   /// a tentative definition (in C), don't check whether there's an overriding
1081   /// definition.
1082   DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
1083   DefinitionKind isThisDeclarationADefinition() const {
1084     return isThisDeclarationADefinition(getASTContext());
1085   }
1086
1087   /// \brief Check whether this variable is defined in this
1088   /// translation unit.
1089   DefinitionKind hasDefinition(ASTContext &) const;
1090   DefinitionKind hasDefinition() const {
1091     return hasDefinition(getASTContext());
1092   }
1093
1094   /// \brief Get the tentative definition that acts as the real definition in
1095   /// a TU. Returns null if there is a proper definition available.
1096   VarDecl *getActingDefinition();
1097   const VarDecl *getActingDefinition() const {
1098     return const_cast<VarDecl*>(this)->getActingDefinition();
1099   }
1100
1101   /// \brief Get the real (not just tentative) definition for this declaration.
1102   VarDecl *getDefinition(ASTContext &);
1103   const VarDecl *getDefinition(ASTContext &C) const {
1104     return const_cast<VarDecl*>(this)->getDefinition(C);
1105   }
1106   VarDecl *getDefinition() {
1107     return getDefinition(getASTContext());
1108   }
1109   const VarDecl *getDefinition() const {
1110     return const_cast<VarDecl*>(this)->getDefinition();
1111   }
1112
1113   /// \brief Determine whether this is or was instantiated from an out-of-line
1114   /// definition of a static data member.
1115   bool isOutOfLine() const override;
1116
1117   /// isFileVarDecl - Returns true for file scoped variable declaration.
1118   bool isFileVarDecl() const {
1119     Kind K = getKind();
1120     if (K == ParmVar || K == ImplicitParam)
1121       return false;
1122
1123     if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
1124       return true;
1125
1126     if (isStaticDataMember())
1127       return true;
1128
1129     return false;
1130   }
1131
1132   /// getAnyInitializer - Get the initializer for this variable, no matter which
1133   /// declaration it is attached to.
1134   const Expr *getAnyInitializer() const {
1135     const VarDecl *D;
1136     return getAnyInitializer(D);
1137   }
1138
1139   /// getAnyInitializer - Get the initializer for this variable, no matter which
1140   /// declaration it is attached to. Also get that declaration.
1141   const Expr *getAnyInitializer(const VarDecl *&D) const;
1142
1143   bool hasInit() const;
1144   const Expr *getInit() const {
1145     return const_cast<VarDecl *>(this)->getInit();
1146   }
1147   Expr *getInit();
1148
1149   /// \brief Retrieve the address of the initializer expression.
1150   Stmt **getInitAddress();
1151
1152   void setInit(Expr *I);
1153
1154   /// \brief Determine whether this variable's value can be used in a
1155   /// constant expression, according to the relevant language standard.
1156   /// This only checks properties of the declaration, and does not check
1157   /// whether the initializer is in fact a constant expression.
1158   bool isUsableInConstantExpressions(ASTContext &C) const;
1159
1160   EvaluatedStmt *ensureEvaluatedStmt() const;
1161
1162   /// \brief Attempt to evaluate the value of the initializer attached to this
1163   /// declaration, and produce notes explaining why it cannot be evaluated or is
1164   /// not a constant expression. Returns a pointer to the value if evaluation
1165   /// succeeded, 0 otherwise.
1166   APValue *evaluateValue() const;
1167   APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1168
1169   /// \brief Return the already-evaluated value of this variable's
1170   /// initializer, or NULL if the value is not yet known. Returns pointer
1171   /// to untyped APValue if the value could not be evaluated.
1172   APValue *getEvaluatedValue() const;
1173
1174   /// \brief Determines whether it is already known whether the
1175   /// initializer is an integral constant expression or not.
1176   bool isInitKnownICE() const;
1177
1178   /// \brief Determines whether the initializer is an integral constant
1179   /// expression, or in C++11, whether the initializer is a constant
1180   /// expression.
1181   ///
1182   /// \pre isInitKnownICE()
1183   bool isInitICE() const;
1184
1185   /// \brief Determine whether the value of the initializer attached to this
1186   /// declaration is an integral constant expression.
1187   bool checkInitIsICE() const;
1188
1189   void setInitStyle(InitializationStyle Style) {
1190     VarDeclBits.InitStyle = Style;
1191   }
1192
1193   /// \brief The style of initialization for this declaration.
1194   ///
1195   /// C-style initialization is "int x = 1;". Call-style initialization is
1196   /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1197   /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1198   /// expression for class types. List-style initialization is C++11 syntax,
1199   /// e.g. "int x{1};". Clients can distinguish between different forms of
1200   /// initialization by checking this value. In particular, "int x = {1};" is
1201   /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1202   /// Init expression in all three cases is an InitListExpr.
1203   InitializationStyle getInitStyle() const {
1204     return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1205   }
1206   /// \brief Whether the initializer is a direct-initializer (list or call).
1207   bool isDirectInit() const {
1208     return getInitStyle() != CInit;
1209   }
1210
1211   /// \brief If this definition should pretend to be a declaration.
1212   bool isThisDeclarationADemotedDefinition() const {
1213     return isa<ParmVarDecl>(this) ? false :
1214       NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
1215   }
1216
1217   /// \brief This is a definition which should be demoted to a declaration.
1218   ///
1219   /// In some cases (mostly module merging) we can end up with two visible
1220   /// definitions one of which needs to be demoted to a declaration to keep
1221   /// the AST invariants.
1222   void demoteThisDefinitionToDeclaration() {
1223     assert (isThisDeclarationADefinition() && "Not a definition!");
1224     assert (!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!");
1225     NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
1226   }
1227
1228   /// \brief Determine whether this variable is the exception variable in a
1229   /// C++ catch statememt or an Objective-C \@catch statement.
1230   bool isExceptionVariable() const {
1231     return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
1232   }
1233   void setExceptionVariable(bool EV) {
1234     assert(!isa<ParmVarDecl>(this));
1235     NonParmVarDeclBits.ExceptionVar = EV;
1236   }
1237
1238   /// \brief Determine whether this local variable can be used with the named
1239   /// return value optimization (NRVO).
1240   ///
1241   /// The named return value optimization (NRVO) works by marking certain
1242   /// non-volatile local variables of class type as NRVO objects. These
1243   /// locals can be allocated within the return slot of their containing
1244   /// function, in which case there is no need to copy the object to the
1245   /// return slot when returning from the function. Within the function body,
1246   /// each return that returns the NRVO object will have this variable as its
1247   /// NRVO candidate.
1248   bool isNRVOVariable() const {
1249     return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable;
1250   }
1251   void setNRVOVariable(bool NRVO) {
1252     assert(!isa<ParmVarDecl>(this));
1253     NonParmVarDeclBits.NRVOVariable = NRVO;
1254   }
1255
1256   /// \brief Determine whether this variable is the for-range-declaration in
1257   /// a C++0x for-range statement.
1258   bool isCXXForRangeDecl() const {
1259     return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
1260   }
1261   void setCXXForRangeDecl(bool FRD) {
1262     assert(!isa<ParmVarDecl>(this));
1263     NonParmVarDeclBits.CXXForRangeDecl = FRD;
1264   }
1265
1266   /// \brief Determine whether this variable is an ARC pseudo-__strong
1267   /// variable.  A pseudo-__strong variable has a __strong-qualified
1268   /// type but does not actually retain the object written into it.
1269   /// Generally such variables are also 'const' for safety.
1270   bool isARCPseudoStrong() const {
1271     return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ARCPseudoStrong;
1272   }
1273   void setARCPseudoStrong(bool ps) {
1274     assert(!isa<ParmVarDecl>(this));
1275     NonParmVarDeclBits.ARCPseudoStrong = ps;
1276   }
1277
1278   /// Whether this variable is (C++1z) inline.
1279   bool isInline() const {
1280     return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline;
1281   }
1282   bool isInlineSpecified() const {
1283     return isa<ParmVarDecl>(this) ? false
1284                                   : NonParmVarDeclBits.IsInlineSpecified;
1285   }
1286   void setInlineSpecified() {
1287     assert(!isa<ParmVarDecl>(this));
1288     NonParmVarDeclBits.IsInline = true;
1289     NonParmVarDeclBits.IsInlineSpecified = true;
1290   }
1291   void setImplicitlyInline() {
1292     assert(!isa<ParmVarDecl>(this));
1293     NonParmVarDeclBits.IsInline = true;
1294   }
1295
1296   /// Whether this variable is (C++11) constexpr.
1297   bool isConstexpr() const {
1298     return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr;
1299   }
1300   void setConstexpr(bool IC) {
1301     assert(!isa<ParmVarDecl>(this));
1302     NonParmVarDeclBits.IsConstexpr = IC;
1303   }
1304
1305   /// Whether this variable is the implicit variable for a lambda init-capture.
1306   bool isInitCapture() const {
1307     return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture;
1308   }
1309   void setInitCapture(bool IC) {
1310     assert(!isa<ParmVarDecl>(this));
1311     NonParmVarDeclBits.IsInitCapture = IC;
1312   }
1313
1314   /// Whether this local extern variable declaration's previous declaration
1315   /// was declared in the same block scope. Only correct in C++.
1316   bool isPreviousDeclInSameBlockScope() const {
1317     return isa<ParmVarDecl>(this)
1318                ? false
1319                : NonParmVarDeclBits.PreviousDeclInSameBlockScope;
1320   }
1321   void setPreviousDeclInSameBlockScope(bool Same) {
1322     assert(!isa<ParmVarDecl>(this));
1323     NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same;
1324   }
1325
1326   /// \brief Retrieve the variable declaration from which this variable could
1327   /// be instantiated, if it is an instantiation (rather than a non-template).
1328   VarDecl *getTemplateInstantiationPattern() const;
1329
1330   /// \brief If this variable is an instantiated static data member of a
1331   /// class template specialization, returns the templated static data member
1332   /// from which it was instantiated.
1333   VarDecl *getInstantiatedFromStaticDataMember() const;
1334
1335   /// \brief If this variable is an instantiation of a variable template or a
1336   /// static data member of a class template, determine what kind of
1337   /// template specialization or instantiation this is.
1338   TemplateSpecializationKind getTemplateSpecializationKind() const;
1339
1340   /// \brief If this variable is an instantiation of a variable template or a
1341   /// static data member of a class template, determine its point of
1342   /// instantiation.
1343   SourceLocation getPointOfInstantiation() const;
1344
1345   /// \brief If this variable is an instantiation of a static data member of a
1346   /// class template specialization, retrieves the member specialization
1347   /// information.
1348   MemberSpecializationInfo *getMemberSpecializationInfo() const;
1349
1350   /// \brief For a static data member that was instantiated from a static
1351   /// data member of a class template, set the template specialiation kind.
1352   void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1353                         SourceLocation PointOfInstantiation = SourceLocation());
1354
1355   /// \brief Specify that this variable is an instantiation of the
1356   /// static data member VD.
1357   void setInstantiationOfStaticDataMember(VarDecl *VD,
1358                                           TemplateSpecializationKind TSK);
1359
1360   /// \brief Retrieves the variable template that is described by this
1361   /// variable declaration.
1362   ///
1363   /// Every variable template is represented as a VarTemplateDecl and a
1364   /// VarDecl. The former contains template properties (such as
1365   /// the template parameter lists) while the latter contains the
1366   /// actual description of the template's
1367   /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
1368   /// VarDecl that from a VarTemplateDecl, while
1369   /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
1370   /// a VarDecl.
1371   VarTemplateDecl *getDescribedVarTemplate() const;
1372
1373   void setDescribedVarTemplate(VarTemplateDecl *Template);
1374
1375   // Implement isa/cast/dyncast/etc.
1376   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1377   static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1378 };
1379
1380 class ImplicitParamDecl : public VarDecl {
1381   void anchor() override;
1382 public:
1383   static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1384                                    SourceLocation IdLoc, IdentifierInfo *Id,
1385                                    QualType T);
1386
1387   static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1388
1389   ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc,
1390                     IdentifierInfo *Id, QualType Type)
1391     : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type,
1392               /*tinfo*/ nullptr, SC_None) {
1393     setImplicit();
1394   }
1395
1396   // Implement isa/cast/dyncast/etc.
1397   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1398   static bool classofKind(Kind K) { return K == ImplicitParam; }
1399 };
1400
1401 /// ParmVarDecl - Represents a parameter to a function.
1402 class ParmVarDecl : public VarDecl {
1403 public:
1404   enum { MaxFunctionScopeDepth = 255 };
1405   enum { MaxFunctionScopeIndex = 255 };
1406
1407 protected:
1408   ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1409               SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1410               TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
1411       : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
1412     assert(ParmVarDeclBits.HasInheritedDefaultArg == false);
1413     assert(ParmVarDeclBits.DefaultArgKind == DAK_None);
1414     assert(ParmVarDeclBits.IsKNRPromoted == false);
1415     assert(ParmVarDeclBits.IsObjCMethodParam == false);
1416     setDefaultArg(DefArg);
1417   }
1418
1419 public:
1420   static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1421                              SourceLocation StartLoc,
1422                              SourceLocation IdLoc, IdentifierInfo *Id,
1423                              QualType T, TypeSourceInfo *TInfo,
1424                              StorageClass S, Expr *DefArg);
1425
1426   static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1427
1428   SourceRange getSourceRange() const override LLVM_READONLY;
1429
1430   void setObjCMethodScopeInfo(unsigned parameterIndex) {
1431     ParmVarDeclBits.IsObjCMethodParam = true;
1432     setParameterIndex(parameterIndex);
1433   }
1434
1435   void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1436     assert(!ParmVarDeclBits.IsObjCMethodParam);
1437
1438     ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1439     assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth
1440            && "truncation!");
1441
1442     setParameterIndex(parameterIndex);
1443   }
1444
1445   bool isObjCMethodParameter() const {
1446     return ParmVarDeclBits.IsObjCMethodParam;
1447   }
1448
1449   unsigned getFunctionScopeDepth() const {
1450     if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1451     return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1452   }
1453
1454   /// Returns the index of this parameter in its prototype or method scope.
1455   unsigned getFunctionScopeIndex() const {
1456     return getParameterIndex();
1457   }
1458
1459   ObjCDeclQualifier getObjCDeclQualifier() const {
1460     if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1461     return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1462   }
1463   void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1464     assert(ParmVarDeclBits.IsObjCMethodParam);
1465     ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1466   }
1467
1468   /// True if the value passed to this parameter must undergo
1469   /// K&R-style default argument promotion:
1470   ///
1471   /// C99 6.5.2.2.
1472   ///   If the expression that denotes the called function has a type
1473   ///   that does not include a prototype, the integer promotions are
1474   ///   performed on each argument, and arguments that have type float
1475   ///   are promoted to double.
1476   bool isKNRPromoted() const {
1477     return ParmVarDeclBits.IsKNRPromoted;
1478   }
1479   void setKNRPromoted(bool promoted) {
1480     ParmVarDeclBits.IsKNRPromoted = promoted;
1481   }
1482
1483   Expr *getDefaultArg();
1484   const Expr *getDefaultArg() const {
1485     return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1486   }
1487
1488   void setDefaultArg(Expr *defarg);
1489
1490   /// \brief Retrieve the source range that covers the entire default
1491   /// argument.
1492   SourceRange getDefaultArgRange() const;
1493   void setUninstantiatedDefaultArg(Expr *arg);
1494   Expr *getUninstantiatedDefaultArg();
1495   const Expr *getUninstantiatedDefaultArg() const {
1496     return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg();
1497   }
1498
1499   /// hasDefaultArg - Determines whether this parameter has a default argument,
1500   /// either parsed or not.
1501   bool hasDefaultArg() const;
1502
1503   /// hasUnparsedDefaultArg - Determines whether this parameter has a
1504   /// default argument that has not yet been parsed. This will occur
1505   /// during the processing of a C++ class whose member functions have
1506   /// default arguments, e.g.,
1507   /// @code
1508   ///   class X {
1509   ///   public:
1510   ///     void f(int x = 17); // x has an unparsed default argument now
1511   ///   }; // x has a regular default argument now
1512   /// @endcode
1513   bool hasUnparsedDefaultArg() const {
1514     return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed;
1515   }
1516
1517   bool hasUninstantiatedDefaultArg() const {
1518     return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated;
1519   }
1520
1521   /// setUnparsedDefaultArg - Specify that this parameter has an
1522   /// unparsed default argument. The argument will be replaced with a
1523   /// real default argument via setDefaultArg when the class
1524   /// definition enclosing the function declaration that owns this
1525   /// default argument is completed.
1526   void setUnparsedDefaultArg() {
1527     ParmVarDeclBits.DefaultArgKind = DAK_Unparsed;
1528   }
1529
1530   bool hasInheritedDefaultArg() const {
1531     return ParmVarDeclBits.HasInheritedDefaultArg;
1532   }
1533
1534   void setHasInheritedDefaultArg(bool I = true) {
1535     ParmVarDeclBits.HasInheritedDefaultArg = I;
1536   }
1537
1538   QualType getOriginalType() const;
1539
1540   /// \brief Determine whether this parameter is actually a function
1541   /// parameter pack.
1542   bool isParameterPack() const;
1543
1544   /// setOwningFunction - Sets the function declaration that owns this
1545   /// ParmVarDecl. Since ParmVarDecls are often created before the
1546   /// FunctionDecls that own them, this routine is required to update
1547   /// the DeclContext appropriately.
1548   void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1549
1550   // Implement isa/cast/dyncast/etc.
1551   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1552   static bool classofKind(Kind K) { return K == ParmVar; }
1553
1554 private:
1555   enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1556
1557   void setParameterIndex(unsigned parameterIndex) {
1558     if (parameterIndex >= ParameterIndexSentinel) {
1559       setParameterIndexLarge(parameterIndex);
1560       return;
1561     }
1562
1563     ParmVarDeclBits.ParameterIndex = parameterIndex;
1564     assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!");
1565   }
1566   unsigned getParameterIndex() const {
1567     unsigned d = ParmVarDeclBits.ParameterIndex;
1568     return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1569   }
1570
1571   void setParameterIndexLarge(unsigned parameterIndex);
1572   unsigned getParameterIndexLarge() const;
1573 };
1574
1575 /// FunctionDecl - An instance of this class is created to represent a
1576 /// function declaration or definition.
1577 ///
1578 /// Since a given function can be declared several times in a program,
1579 /// there may be several FunctionDecls that correspond to that
1580 /// function. Only one of those FunctionDecls will be found when
1581 /// traversing the list of declarations in the context of the
1582 /// FunctionDecl (e.g., the translation unit); this FunctionDecl
1583 /// contains all of the information known about the function. Other,
1584 /// previous declarations of the function are available via the
1585 /// getPreviousDecl() chain.
1586 class FunctionDecl : public DeclaratorDecl, public DeclContext,
1587                      public Redeclarable<FunctionDecl> {
1588 public:
1589   /// \brief The kind of templated function a FunctionDecl can be.
1590   enum TemplatedKind {
1591     TK_NonTemplate,
1592     TK_FunctionTemplate,
1593     TK_MemberSpecialization,
1594     TK_FunctionTemplateSpecialization,
1595     TK_DependentFunctionTemplateSpecialization
1596   };
1597
1598 private:
1599   /// ParamInfo - new[]'d array of pointers to VarDecls for the formal
1600   /// parameters of this function.  This is null if a prototype or if there are
1601   /// no formals.
1602   ParmVarDecl **ParamInfo;
1603
1604   LazyDeclStmtPtr Body;
1605
1606   // FIXME: This can be packed into the bitfields in DeclContext.
1607   // NOTE: VC++ packs bitfields poorly if the types differ.
1608   unsigned SClass : 3;
1609   unsigned IsInline : 1;
1610   unsigned IsInlineSpecified : 1;
1611 protected:
1612   // This is shared by CXXConstructorDecl, CXXConversionDecl, and
1613   // CXXDeductionGuideDecl.
1614   unsigned IsExplicitSpecified : 1;
1615 private:
1616   unsigned IsVirtualAsWritten : 1;
1617   unsigned IsPure : 1;
1618   unsigned HasInheritedPrototype : 1;
1619   unsigned HasWrittenPrototype : 1;
1620   unsigned IsDeleted : 1;
1621   unsigned IsTrivial : 1; // sunk from CXXMethodDecl
1622   unsigned IsDefaulted : 1; // sunk from CXXMethoDecl
1623   unsigned IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl
1624   unsigned HasImplicitReturnZero : 1;
1625   unsigned IsLateTemplateParsed : 1;
1626   unsigned IsConstexpr : 1;
1627
1628   /// \brief Indicates if the function uses __try.
1629   unsigned UsesSEHTry : 1;
1630
1631   /// \brief Indicates if the function was a definition but its body was
1632   /// skipped.
1633   unsigned HasSkippedBody : 1;
1634
1635   /// Indicates if the function declaration will have a body, once we're done
1636   /// parsing it.  (We don't set it to false when we're done parsing, in the
1637   /// hopes this is simpler.)
1638   unsigned WillHaveBody : 1;
1639
1640   /// \brief End part of this FunctionDecl's source range.
1641   ///
1642   /// We could compute the full range in getSourceRange(). However, when we're
1643   /// dealing with a function definition deserialized from a PCH/AST file,
1644   /// we can only compute the full range once the function body has been
1645   /// de-serialized, so it's far better to have the (sometimes-redundant)
1646   /// EndRangeLoc.
1647   SourceLocation EndRangeLoc;
1648
1649   /// \brief The template or declaration that this declaration
1650   /// describes or was instantiated from, respectively.
1651   ///
1652   /// For non-templates, this value will be NULL. For function
1653   /// declarations that describe a function template, this will be a
1654   /// pointer to a FunctionTemplateDecl. For member functions
1655   /// of class template specializations, this will be a MemberSpecializationInfo
1656   /// pointer containing information about the specialization.
1657   /// For function template specializations, this will be a
1658   /// FunctionTemplateSpecializationInfo, which contains information about
1659   /// the template being specialized and the template arguments involved in
1660   /// that specialization.
1661   llvm::PointerUnion4<FunctionTemplateDecl *,
1662                       MemberSpecializationInfo *,
1663                       FunctionTemplateSpecializationInfo *,
1664                       DependentFunctionTemplateSpecializationInfo *>
1665     TemplateOrSpecialization;
1666
1667   /// DNLoc - Provides source/type location info for the
1668   /// declaration name embedded in the DeclaratorDecl base class.
1669   DeclarationNameLoc DNLoc;
1670
1671   /// \brief Specify that this function declaration is actually a function
1672   /// template specialization.
1673   ///
1674   /// \param C the ASTContext.
1675   ///
1676   /// \param Template the function template that this function template
1677   /// specialization specializes.
1678   ///
1679   /// \param TemplateArgs the template arguments that produced this
1680   /// function template specialization from the template.
1681   ///
1682   /// \param InsertPos If non-NULL, the position in the function template
1683   /// specialization set where the function template specialization data will
1684   /// be inserted.
1685   ///
1686   /// \param TSK the kind of template specialization this is.
1687   ///
1688   /// \param TemplateArgsAsWritten location info of template arguments.
1689   ///
1690   /// \param PointOfInstantiation point at which the function template
1691   /// specialization was first instantiated.
1692   void setFunctionTemplateSpecialization(ASTContext &C,
1693                                          FunctionTemplateDecl *Template,
1694                                        const TemplateArgumentList *TemplateArgs,
1695                                          void *InsertPos,
1696                                          TemplateSpecializationKind TSK,
1697                           const TemplateArgumentListInfo *TemplateArgsAsWritten,
1698                                          SourceLocation PointOfInstantiation);
1699
1700   /// \brief Specify that this record is an instantiation of the
1701   /// member function FD.
1702   void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1703                                         TemplateSpecializationKind TSK);
1704
1705   void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
1706
1707 protected:
1708   FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1709                const DeclarationNameInfo &NameInfo, QualType T,
1710                TypeSourceInfo *TInfo, StorageClass S, bool isInlineSpecified,
1711                bool isConstexprSpecified)
1712       : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
1713                        StartLoc),
1714         DeclContext(DK), redeclarable_base(C), ParamInfo(nullptr), Body(),
1715         SClass(S), IsInline(isInlineSpecified),
1716         IsInlineSpecified(isInlineSpecified), IsExplicitSpecified(false),
1717         IsVirtualAsWritten(false), IsPure(false),
1718         HasInheritedPrototype(false), HasWrittenPrototype(true),
1719         IsDeleted(false), IsTrivial(false), IsDefaulted(false),
1720         IsExplicitlyDefaulted(false), HasImplicitReturnZero(false),
1721         IsLateTemplateParsed(false), IsConstexpr(isConstexprSpecified),
1722         UsesSEHTry(false), HasSkippedBody(false), WillHaveBody(false),
1723         EndRangeLoc(NameInfo.getEndLoc()), TemplateOrSpecialization(),
1724         DNLoc(NameInfo.getInfo()) {}
1725
1726   typedef Redeclarable<FunctionDecl> redeclarable_base;
1727   FunctionDecl *getNextRedeclarationImpl() override {
1728     return getNextRedeclaration();
1729   }
1730   FunctionDecl *getPreviousDeclImpl() override {
1731     return getPreviousDecl();
1732   }
1733   FunctionDecl *getMostRecentDeclImpl() override {
1734     return getMostRecentDecl();
1735   }
1736
1737 public:
1738   typedef redeclarable_base::redecl_range redecl_range;
1739   typedef redeclarable_base::redecl_iterator redecl_iterator;
1740   using redeclarable_base::redecls_begin;
1741   using redeclarable_base::redecls_end;
1742   using redeclarable_base::redecls;
1743   using redeclarable_base::getPreviousDecl;
1744   using redeclarable_base::getMostRecentDecl;
1745   using redeclarable_base::isFirstDecl;
1746
1747   static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1748                               SourceLocation StartLoc, SourceLocation NLoc,
1749                               DeclarationName N, QualType T,
1750                               TypeSourceInfo *TInfo,
1751                               StorageClass SC,
1752                               bool isInlineSpecified = false,
1753                               bool hasWrittenPrototype = true,
1754                               bool isConstexprSpecified = false) {
1755     DeclarationNameInfo NameInfo(N, NLoc);
1756     return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo,
1757                                 SC,
1758                                 isInlineSpecified, hasWrittenPrototype,
1759                                 isConstexprSpecified);
1760   }
1761
1762   static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1763                               SourceLocation StartLoc,
1764                               const DeclarationNameInfo &NameInfo,
1765                               QualType T, TypeSourceInfo *TInfo,
1766                               StorageClass SC,
1767                               bool isInlineSpecified,
1768                               bool hasWrittenPrototype,
1769                               bool isConstexprSpecified = false);
1770
1771   static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1772                        
1773   DeclarationNameInfo getNameInfo() const {
1774     return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1775   }
1776
1777   void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1778                             bool Qualified) const override;
1779
1780   void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1781
1782   SourceRange getSourceRange() const override LLVM_READONLY;
1783
1784   /// \brief Returns true if the function has a body (definition). The
1785   /// function body might be in any of the (re-)declarations of this
1786   /// function. The variant that accepts a FunctionDecl pointer will
1787   /// set that function declaration to the actual declaration
1788   /// containing the body (if there is one).
1789   bool hasBody(const FunctionDecl *&Definition) const;
1790
1791   bool hasBody() const override {
1792     const FunctionDecl* Definition;
1793     return hasBody(Definition);
1794   }
1795
1796   /// hasTrivialBody - Returns whether the function has a trivial body that does
1797   /// not require any specific codegen.
1798   bool hasTrivialBody() const;
1799
1800   /// isDefined - Returns true if the function is defined at all, including
1801   /// a deleted definition. Except for the behavior when the function is
1802   /// deleted, behaves like hasBody.
1803   bool isDefined(const FunctionDecl *&Definition) const;
1804
1805   virtual bool isDefined() const {
1806     const FunctionDecl* Definition;
1807     return isDefined(Definition);
1808   }
1809
1810   /// \brief Get the definition for this declaration.
1811   FunctionDecl *getDefinition() {
1812     const FunctionDecl *Definition;
1813     if (isDefined(Definition))
1814       return const_cast<FunctionDecl *>(Definition);
1815     return nullptr;
1816   }
1817   const FunctionDecl *getDefinition() const {
1818     return const_cast<FunctionDecl *>(this)->getDefinition();
1819   }
1820
1821   /// getBody - Retrieve the body (definition) of the function. The
1822   /// function body might be in any of the (re-)declarations of this
1823   /// function. The variant that accepts a FunctionDecl pointer will
1824   /// set that function declaration to the actual declaration
1825   /// containing the body (if there is one).
1826   /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
1827   /// unnecessary AST de-serialization of the body.
1828   Stmt *getBody(const FunctionDecl *&Definition) const;
1829
1830   Stmt *getBody() const override {
1831     const FunctionDecl* Definition;
1832     return getBody(Definition);
1833   }
1834
1835   /// isThisDeclarationADefinition - Returns whether this specific
1836   /// declaration of the function is also a definition. This does not
1837   /// determine whether the function has been defined (e.g., in a
1838   /// previous definition); for that information, use isDefined. Note
1839   /// that this returns false for a defaulted function unless that function
1840   /// has been implicitly defined (possibly as deleted).
1841   bool isThisDeclarationADefinition() const {
1842     return IsDeleted || Body || IsLateTemplateParsed;
1843   }
1844
1845   /// doesThisDeclarationHaveABody - Returns whether this specific
1846   /// declaration of the function has a body - that is, if it is a non-
1847   /// deleted definition.
1848   bool doesThisDeclarationHaveABody() const {
1849     return Body || IsLateTemplateParsed;
1850   }
1851
1852   void setBody(Stmt *B);
1853   void setLazyBody(uint64_t Offset) { Body = Offset; }
1854
1855   /// Whether this function is variadic.
1856   bool isVariadic() const;
1857
1858   /// Whether this function is marked as virtual explicitly.
1859   bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
1860   void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
1861
1862   /// Whether this virtual function is pure, i.e. makes the containing class
1863   /// abstract.
1864   bool isPure() const { return IsPure; }
1865   void setPure(bool P = true);
1866
1867   /// Whether this templated function will be late parsed.
1868   bool isLateTemplateParsed() const { return IsLateTemplateParsed; }
1869   void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; }
1870
1871   /// Whether this function is "trivial" in some specialized C++ senses.
1872   /// Can only be true for default constructors, copy constructors,
1873   /// copy assignment operators, and destructors.  Not meaningful until
1874   /// the class has been fully built by Sema.
1875   bool isTrivial() const { return IsTrivial; }
1876   void setTrivial(bool IT) { IsTrivial = IT; }
1877
1878   /// Whether this function is defaulted per C++0x. Only valid for
1879   /// special member functions.
1880   bool isDefaulted() const { return IsDefaulted; }
1881   void setDefaulted(bool D = true) { IsDefaulted = D; }
1882
1883   /// Whether this function is explicitly defaulted per C++0x. Only valid
1884   /// for special member functions.
1885   bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; }
1886   void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; }
1887
1888   /// Whether falling off this function implicitly returns null/zero.
1889   /// If a more specific implicit return value is required, front-ends
1890   /// should synthesize the appropriate return statements.
1891   bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
1892   void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
1893
1894   /// \brief Whether this function has a prototype, either because one
1895   /// was explicitly written or because it was "inherited" by merging
1896   /// a declaration without a prototype with a declaration that has a
1897   /// prototype.
1898   bool hasPrototype() const {
1899     return HasWrittenPrototype || HasInheritedPrototype;
1900   }
1901
1902   bool hasWrittenPrototype() const { return HasWrittenPrototype; }
1903
1904   /// \brief Whether this function inherited its prototype from a
1905   /// previous declaration.
1906   bool hasInheritedPrototype() const { return HasInheritedPrototype; }
1907   void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
1908
1909   /// Whether this is a (C++11) constexpr function or constexpr constructor.
1910   bool isConstexpr() const { return IsConstexpr; }
1911   void setConstexpr(bool IC) { IsConstexpr = IC; }
1912
1913   /// \brief Indicates the function uses __try.
1914   bool usesSEHTry() const { return UsesSEHTry; }
1915   void setUsesSEHTry(bool UST) { UsesSEHTry = UST; }
1916
1917   /// \brief Whether this function has been deleted.
1918   ///
1919   /// A function that is "deleted" (via the C++0x "= delete" syntax)
1920   /// acts like a normal function, except that it cannot actually be
1921   /// called or have its address taken. Deleted functions are
1922   /// typically used in C++ overload resolution to attract arguments
1923   /// whose type or lvalue/rvalue-ness would permit the use of a
1924   /// different overload that would behave incorrectly. For example,
1925   /// one might use deleted functions to ban implicit conversion from
1926   /// a floating-point number to an Integer type:
1927   ///
1928   /// @code
1929   /// struct Integer {
1930   ///   Integer(long); // construct from a long
1931   ///   Integer(double) = delete; // no construction from float or double
1932   ///   Integer(long double) = delete; // no construction from long double
1933   /// };
1934   /// @endcode
1935   // If a function is deleted, its first declaration must be.
1936   bool isDeleted() const { return getCanonicalDecl()->IsDeleted; }
1937   bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; }
1938   void setDeletedAsWritten(bool D = true) { IsDeleted = D; }
1939
1940   /// \brief Determines whether this function is "main", which is the
1941   /// entry point into an executable program.
1942   bool isMain() const;
1943
1944   /// \brief Determines whether this function is a MSVCRT user defined entry
1945   /// point.
1946   bool isMSVCRTEntryPoint() const;
1947
1948   /// \brief Determines whether this operator new or delete is one
1949   /// of the reserved global placement operators:
1950   ///    void *operator new(size_t, void *);
1951   ///    void *operator new[](size_t, void *);
1952   ///    void operator delete(void *, void *);
1953   ///    void operator delete[](void *, void *);
1954   /// These functions have special behavior under [new.delete.placement]:
1955   ///    These functions are reserved, a C++ program may not define
1956   ///    functions that displace the versions in the Standard C++ library.
1957   ///    The provisions of [basic.stc.dynamic] do not apply to these
1958   ///    reserved placement forms of operator new and operator delete.
1959   ///
1960   /// This function must be an allocation or deallocation function.
1961   bool isReservedGlobalPlacementOperator() const;
1962
1963   /// \brief Determines whether this function is one of the replaceable
1964   /// global allocation functions:
1965   ///    void *operator new(size_t);
1966   ///    void *operator new(size_t, const std::nothrow_t &) noexcept;
1967   ///    void *operator new[](size_t);
1968   ///    void *operator new[](size_t, const std::nothrow_t &) noexcept;
1969   ///    void operator delete(void *) noexcept;
1970   ///    void operator delete(void *, std::size_t) noexcept;      [C++1y]
1971   ///    void operator delete(void *, const std::nothrow_t &) noexcept;
1972   ///    void operator delete[](void *) noexcept;
1973   ///    void operator delete[](void *, std::size_t) noexcept;    [C++1y]
1974   ///    void operator delete[](void *, const std::nothrow_t &) noexcept;
1975   /// These functions have special behavior under C++1y [expr.new]:
1976   ///    An implementation is allowed to omit a call to a replaceable global
1977   ///    allocation function. [...]
1978   bool isReplaceableGlobalAllocationFunction() const;
1979
1980   /// Compute the language linkage.
1981   LanguageLinkage getLanguageLinkage() const;
1982
1983   /// \brief Determines whether this function is a function with
1984   /// external, C linkage.
1985   bool isExternC() const;
1986
1987   /// \brief Determines whether this function's context is, or is nested within,
1988   /// a C++ extern "C" linkage spec.
1989   bool isInExternCContext() const;
1990
1991   /// \brief Determines whether this function's context is, or is nested within,
1992   /// a C++ extern "C++" linkage spec.
1993   bool isInExternCXXContext() const;
1994
1995   /// \brief Determines whether this is a global function.
1996   bool isGlobal() const;
1997
1998   /// \brief Determines whether this function is known to be 'noreturn', through
1999   /// an attribute on its declaration or its type.
2000   bool isNoReturn() const;
2001
2002   /// \brief True if the function was a definition but its body was skipped.
2003   bool hasSkippedBody() const { return HasSkippedBody; }
2004   void setHasSkippedBody(bool Skipped = true) { HasSkippedBody = Skipped; }
2005
2006   /// True if this function will eventually have a body, once it's fully parsed.
2007   bool willHaveBody() const { return WillHaveBody; }
2008   void setWillHaveBody(bool V = true) { WillHaveBody = V; }
2009
2010   void setPreviousDeclaration(FunctionDecl * PrevDecl);
2011
2012   FunctionDecl *getCanonicalDecl() override;
2013   const FunctionDecl *getCanonicalDecl() const {
2014     return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
2015   }
2016
2017   unsigned getBuiltinID() const;
2018
2019   // ArrayRef interface to parameters.
2020   ArrayRef<ParmVarDecl *> parameters() const {
2021     return {ParamInfo, getNumParams()};
2022   }
2023   MutableArrayRef<ParmVarDecl *> parameters() {
2024     return {ParamInfo, getNumParams()};
2025   }
2026
2027   // Iterator access to formal parameters.
2028   typedef MutableArrayRef<ParmVarDecl *>::iterator param_iterator;
2029   typedef ArrayRef<ParmVarDecl *>::const_iterator param_const_iterator;
2030   bool param_empty() const { return parameters().empty(); }
2031   param_iterator param_begin() { return parameters().begin(); }
2032   param_iterator param_end() { return parameters().end(); }
2033   param_const_iterator param_begin() const { return parameters().begin(); }
2034   param_const_iterator param_end() const { return parameters().end(); }
2035   size_t param_size() const { return parameters().size(); }
2036
2037   /// getNumParams - Return the number of parameters this function must have
2038   /// based on its FunctionType.  This is the length of the ParamInfo array
2039   /// after it has been created.
2040   unsigned getNumParams() const;
2041
2042   const ParmVarDecl *getParamDecl(unsigned i) const {
2043     assert(i < getNumParams() && "Illegal param #");
2044     return ParamInfo[i];
2045   }
2046   ParmVarDecl *getParamDecl(unsigned i) {
2047     assert(i < getNumParams() && "Illegal param #");
2048     return ParamInfo[i];
2049   }
2050   void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
2051     setParams(getASTContext(), NewParamInfo);
2052   }
2053
2054   /// getMinRequiredArguments - Returns the minimum number of arguments
2055   /// needed to call this function. This may be fewer than the number of
2056   /// function parameters, if some of the parameters have default
2057   /// arguments (in C++).
2058   unsigned getMinRequiredArguments() const;
2059
2060   QualType getReturnType() const {
2061     assert(getType()->getAs<FunctionType>() && "Expected a FunctionType!");
2062     return getType()->getAs<FunctionType>()->getReturnType();
2063   }
2064
2065   /// \brief Attempt to compute an informative source range covering the
2066   /// function return type. This may omit qualifiers and other information with
2067   /// limited representation in the AST.
2068   SourceRange getReturnTypeSourceRange() const;
2069
2070   /// \brief Attempt to compute an informative source range covering the
2071   /// function exception specification, if any.
2072   SourceRange getExceptionSpecSourceRange() const;
2073
2074   /// \brief Determine the type of an expression that calls this function.
2075   QualType getCallResultType() const {
2076     assert(getType()->getAs<FunctionType>() && "Expected a FunctionType!");
2077     return getType()->getAs<FunctionType>()->getCallResultType(getASTContext());
2078   }
2079
2080   /// \brief Returns the WarnUnusedResultAttr that is either declared on this
2081   /// function, or its return type declaration.
2082   const Attr *getUnusedResultAttr() const;
2083
2084   /// \brief Returns true if this function or its return type has the
2085   /// warn_unused_result attribute.
2086   bool hasUnusedResultAttr() const { return getUnusedResultAttr() != nullptr; }
2087
2088   /// \brief Returns the storage class as written in the source. For the
2089   /// computed linkage of symbol, see getLinkage.
2090   StorageClass getStorageClass() const { return StorageClass(SClass); }
2091
2092   /// \brief Determine whether the "inline" keyword was specified for this
2093   /// function.
2094   bool isInlineSpecified() const { return IsInlineSpecified; }
2095
2096   /// Set whether the "inline" keyword was specified for this function.
2097   void setInlineSpecified(bool I) {
2098     IsInlineSpecified = I;
2099     IsInline = I;
2100   }
2101
2102   /// Flag that this function is implicitly inline.
2103   void setImplicitlyInline() {
2104     IsInline = true;
2105   }
2106
2107   /// \brief Determine whether this function should be inlined, because it is
2108   /// either marked "inline" or "constexpr" or is a member function of a class
2109   /// that was defined in the class body.
2110   bool isInlined() const { return IsInline; }
2111
2112   bool isInlineDefinitionExternallyVisible() const;
2113
2114   bool isMSExternInline() const;
2115
2116   bool doesDeclarationForceExternallyVisibleDefinition() const;
2117
2118   /// isOverloadedOperator - Whether this function declaration
2119   /// represents an C++ overloaded operator, e.g., "operator+".
2120   bool isOverloadedOperator() const {
2121     return getOverloadedOperator() != OO_None;
2122   }
2123
2124   OverloadedOperatorKind getOverloadedOperator() const;
2125
2126   const IdentifierInfo *getLiteralIdentifier() const;
2127
2128   /// \brief If this function is an instantiation of a member function
2129   /// of a class template specialization, retrieves the function from
2130   /// which it was instantiated.
2131   ///
2132   /// This routine will return non-NULL for (non-templated) member
2133   /// functions of class templates and for instantiations of function
2134   /// templates. For example, given:
2135   ///
2136   /// \code
2137   /// template<typename T>
2138   /// struct X {
2139   ///   void f(T);
2140   /// };
2141   /// \endcode
2142   ///
2143   /// The declaration for X<int>::f is a (non-templated) FunctionDecl
2144   /// whose parent is the class template specialization X<int>. For
2145   /// this declaration, getInstantiatedFromFunction() will return
2146   /// the FunctionDecl X<T>::A. When a complete definition of
2147   /// X<int>::A is required, it will be instantiated from the
2148   /// declaration returned by getInstantiatedFromMemberFunction().
2149   FunctionDecl *getInstantiatedFromMemberFunction() const;
2150
2151   /// \brief What kind of templated function this is.
2152   TemplatedKind getTemplatedKind() const;
2153
2154   /// \brief If this function is an instantiation of a member function of a
2155   /// class template specialization, retrieves the member specialization
2156   /// information.
2157   MemberSpecializationInfo *getMemberSpecializationInfo() const;
2158
2159   /// \brief Specify that this record is an instantiation of the
2160   /// member function FD.
2161   void setInstantiationOfMemberFunction(FunctionDecl *FD,
2162                                         TemplateSpecializationKind TSK) {
2163     setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
2164   }
2165
2166   /// \brief Retrieves the function template that is described by this
2167   /// function declaration.
2168   ///
2169   /// Every function template is represented as a FunctionTemplateDecl
2170   /// and a FunctionDecl (or something derived from FunctionDecl). The
2171   /// former contains template properties (such as the template
2172   /// parameter lists) while the latter contains the actual
2173   /// description of the template's
2174   /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
2175   /// FunctionDecl that describes the function template,
2176   /// getDescribedFunctionTemplate() retrieves the
2177   /// FunctionTemplateDecl from a FunctionDecl.
2178   FunctionTemplateDecl *getDescribedFunctionTemplate() const;
2179
2180   void setDescribedFunctionTemplate(FunctionTemplateDecl *Template);
2181
2182   /// \brief Determine whether this function is a function template
2183   /// specialization.
2184   bool isFunctionTemplateSpecialization() const {
2185     return getPrimaryTemplate() != nullptr;
2186   }
2187
2188   /// \brief Retrieve the class scope template pattern that this function
2189   ///  template specialization is instantiated from.
2190   FunctionDecl *getClassScopeSpecializationPattern() const;
2191
2192   /// \brief If this function is actually a function template specialization,
2193   /// retrieve information about this function template specialization.
2194   /// Otherwise, returns NULL.
2195   FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const;
2196
2197   /// \brief Determines whether this function is a function template
2198   /// specialization or a member of a class template specialization that can
2199   /// be implicitly instantiated.
2200   bool isImplicitlyInstantiable() const;
2201
2202   /// \brief Determines if the given function was instantiated from a
2203   /// function template.
2204   bool isTemplateInstantiation() const;
2205
2206   /// \brief Retrieve the function declaration from which this function could
2207   /// be instantiated, if it is an instantiation (rather than a non-template
2208   /// or a specialization, for example).
2209   FunctionDecl *getTemplateInstantiationPattern() const;
2210
2211   /// \brief Retrieve the primary template that this function template
2212   /// specialization either specializes or was instantiated from.
2213   ///
2214   /// If this function declaration is not a function template specialization,
2215   /// returns NULL.
2216   FunctionTemplateDecl *getPrimaryTemplate() const;
2217
2218   /// \brief Retrieve the template arguments used to produce this function
2219   /// template specialization from the primary template.
2220   ///
2221   /// If this function declaration is not a function template specialization,
2222   /// returns NULL.
2223   const TemplateArgumentList *getTemplateSpecializationArgs() const;
2224
2225   /// \brief Retrieve the template argument list as written in the sources,
2226   /// if any.
2227   ///
2228   /// If this function declaration is not a function template specialization
2229   /// or if it had no explicit template argument list, returns NULL.
2230   /// Note that it an explicit template argument list may be written empty,
2231   /// e.g., template<> void foo<>(char* s);
2232   const ASTTemplateArgumentListInfo*
2233   getTemplateSpecializationArgsAsWritten() const;
2234
2235   /// \brief Specify that this function declaration is actually a function
2236   /// template specialization.
2237   ///
2238   /// \param Template the function template that this function template
2239   /// specialization specializes.
2240   ///
2241   /// \param TemplateArgs the template arguments that produced this
2242   /// function template specialization from the template.
2243   ///
2244   /// \param InsertPos If non-NULL, the position in the function template
2245   /// specialization set where the function template specialization data will
2246   /// be inserted.
2247   ///
2248   /// \param TSK the kind of template specialization this is.
2249   ///
2250   /// \param TemplateArgsAsWritten location info of template arguments.
2251   ///
2252   /// \param PointOfInstantiation point at which the function template
2253   /// specialization was first instantiated.
2254   void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2255                 const TemplateArgumentList *TemplateArgs,
2256                 void *InsertPos,
2257                 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2258                 const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
2259                 SourceLocation PointOfInstantiation = SourceLocation()) {
2260     setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2261                                       InsertPos, TSK, TemplateArgsAsWritten,
2262                                       PointOfInstantiation);
2263   }
2264
2265   /// \brief Specifies that this function declaration is actually a
2266   /// dependent function template specialization.
2267   void setDependentTemplateSpecialization(ASTContext &Context,
2268                              const UnresolvedSetImpl &Templates,
2269                       const TemplateArgumentListInfo &TemplateArgs);
2270
2271   DependentFunctionTemplateSpecializationInfo *
2272   getDependentSpecializationInfo() const;
2273
2274   /// \brief Determine what kind of template instantiation this function
2275   /// represents.
2276   TemplateSpecializationKind getTemplateSpecializationKind() const;
2277
2278   /// \brief Determine what kind of template instantiation this function
2279   /// represents.
2280   void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2281                         SourceLocation PointOfInstantiation = SourceLocation());
2282
2283   /// \brief Retrieve the (first) point of instantiation of a function template
2284   /// specialization or a member of a class template specialization.
2285   ///
2286   /// \returns the first point of instantiation, if this function was
2287   /// instantiated from a template; otherwise, returns an invalid source
2288   /// location.
2289   SourceLocation getPointOfInstantiation() const;
2290
2291   /// \brief Determine whether this is or was instantiated from an out-of-line
2292   /// definition of a member function.
2293   bool isOutOfLine() const override;
2294
2295   /// \brief Identify a memory copying or setting function.
2296   /// If the given function is a memory copy or setting function, returns
2297   /// the corresponding Builtin ID. If the function is not a memory function,
2298   /// returns 0.
2299   unsigned getMemoryFunctionKind() const;
2300
2301   // Implement isa/cast/dyncast/etc.
2302   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2303   static bool classofKind(Kind K) {
2304     return K >= firstFunction && K <= lastFunction;
2305   }
2306   static DeclContext *castToDeclContext(const FunctionDecl *D) {
2307     return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2308   }
2309   static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2310     return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2311   }
2312
2313   friend class ASTDeclReader;
2314   friend class ASTDeclWriter;
2315 };
2316
2317
2318 /// FieldDecl - An instance of this class is created by Sema::ActOnField to
2319 /// represent a member of a struct/union/class.
2320 class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
2321   // FIXME: This can be packed into the bitfields in Decl.
2322   unsigned Mutable : 1;
2323   mutable unsigned CachedFieldIndex : 31;
2324
2325   /// The kinds of value we can store in InitializerOrBitWidth.
2326   ///
2327   /// Note that this is compatible with InClassInitStyle except for
2328   /// ISK_CapturedVLAType.
2329   enum InitStorageKind {
2330     /// If the pointer is null, there's nothing special.  Otherwise,
2331     /// this is a bitfield and the pointer is the Expr* storing the
2332     /// bit-width.
2333     ISK_BitWidthOrNothing = (unsigned) ICIS_NoInit,
2334
2335     /// The pointer is an (optional due to delayed parsing) Expr*
2336     /// holding the copy-initializer.
2337     ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
2338
2339     /// The pointer is an (optional due to delayed parsing) Expr*
2340     /// holding the list-initializer.
2341     ISK_InClassListInit = (unsigned) ICIS_ListInit,
2342
2343     /// The pointer is a VariableArrayType* that's been captured;
2344     /// the enclosing context is a lambda or captured statement.
2345     ISK_CapturedVLAType,
2346   };
2347
2348   /// \brief Storage for either the bit-width, the in-class
2349   /// initializer, or the captured variable length array bound.
2350   ///
2351   /// We can safely combine these because in-class initializers are
2352   /// not permitted for bit-fields, and both are exclusive with VLA
2353   /// captures.
2354   ///
2355   /// If the storage kind is ISK_InClassCopyInit or
2356   /// ISK_InClassListInit, but the initializer is null, then this
2357   /// field has an in-class initializer which has not yet been parsed
2358   /// and attached.
2359   llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
2360 protected:
2361   FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2362             SourceLocation IdLoc, IdentifierInfo *Id,
2363             QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2364             InClassInitStyle InitStyle)
2365     : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2366       Mutable(Mutable), CachedFieldIndex(0),
2367       InitStorage(BW, (InitStorageKind) InitStyle) {
2368     assert((!BW || InitStyle == ICIS_NoInit) && "got initializer for bitfield");
2369   }
2370
2371 public:
2372   static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2373                            SourceLocation StartLoc, SourceLocation IdLoc,
2374                            IdentifierInfo *Id, QualType T,
2375                            TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2376                            InClassInitStyle InitStyle);
2377
2378   static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2379   
2380   /// getFieldIndex - Returns the index of this field within its record,
2381   /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2382   unsigned getFieldIndex() const;
2383
2384   /// isMutable - Determines whether this field is mutable (C++ only).
2385   bool isMutable() const { return Mutable; }
2386
2387   /// \brief Determines whether this field is a bitfield.
2388   bool isBitField() const {
2389     return InitStorage.getInt() == ISK_BitWidthOrNothing &&
2390            InitStorage.getPointer() != nullptr;
2391   }
2392
2393   /// @brief Determines whether this is an unnamed bitfield.
2394   bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2395
2396   /// isAnonymousStructOrUnion - Determines whether this field is a
2397   /// representative for an anonymous struct or union. Such fields are
2398   /// unnamed and are implicitly generated by the implementation to
2399   /// store the data for the anonymous union or struct.
2400   bool isAnonymousStructOrUnion() const;
2401
2402   Expr *getBitWidth() const {
2403     return isBitField()
2404                ? static_cast<Expr *>(InitStorage.getPointer())
2405                : nullptr;
2406   }
2407   unsigned getBitWidthValue(const ASTContext &Ctx) const;
2408
2409   /// setBitWidth - Set the bit-field width for this member.
2410   // Note: used by some clients (i.e., do not remove it).
2411   void setBitWidth(Expr *Width) {
2412     assert(InitStorage.getInt() == ISK_BitWidthOrNothing &&
2413            InitStorage.getPointer() == nullptr &&
2414            "bit width, initializer or captured type already set");
2415     InitStorage.setPointerAndInt(Width, ISK_BitWidthOrNothing);
2416   }
2417
2418   /// removeBitWidth - Remove the bit-field width from this member.
2419   // Note: used by some clients (i.e., do not remove it).
2420   void removeBitWidth() {
2421     assert(isBitField() && "no bitfield width to remove");
2422     InitStorage.setPointerAndInt(nullptr, ISK_BitWidthOrNothing);
2423   }
2424
2425   /// getInClassInitStyle - Get the kind of (C++11) in-class initializer which
2426   /// this field has.
2427   InClassInitStyle getInClassInitStyle() const {
2428     InitStorageKind storageKind = InitStorage.getInt();
2429     return (storageKind == ISK_CapturedVLAType
2430               ? ICIS_NoInit : (InClassInitStyle) storageKind);
2431   }
2432
2433   /// hasInClassInitializer - Determine whether this member has a C++11 in-class
2434   /// initializer.
2435   bool hasInClassInitializer() const {
2436     return getInClassInitStyle() != ICIS_NoInit;
2437   }
2438
2439   /// getInClassInitializer - Get the C++11 in-class initializer for this
2440   /// member, or null if one has not been set. If a valid declaration has an
2441   /// in-class initializer, but this returns null, then we have not parsed and
2442   /// attached it yet.
2443   Expr *getInClassInitializer() const {
2444     return hasInClassInitializer()
2445                ? static_cast<Expr *>(InitStorage.getPointer())
2446                : nullptr;
2447   }
2448
2449   /// setInClassInitializer - Set the C++11 in-class initializer for this
2450   /// member.
2451   void setInClassInitializer(Expr *Init) {
2452     assert(hasInClassInitializer() &&
2453            InitStorage.getPointer() == nullptr &&
2454            "bit width, initializer or captured type already set");
2455     InitStorage.setPointer(Init);
2456   }
2457
2458   /// removeInClassInitializer - Remove the C++11 in-class initializer from this
2459   /// member.
2460   void removeInClassInitializer() {
2461     assert(hasInClassInitializer() && "no initializer to remove");
2462     InitStorage.setPointerAndInt(nullptr, ISK_BitWidthOrNothing);
2463   }
2464
2465   /// \brief Determine whether this member captures the variable length array
2466   /// type.
2467   bool hasCapturedVLAType() const {
2468     return InitStorage.getInt() == ISK_CapturedVLAType;
2469   }
2470
2471   /// \brief Get the captured variable length array type.
2472   const VariableArrayType *getCapturedVLAType() const {
2473     return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
2474                                       InitStorage.getPointer())
2475                                 : nullptr;
2476   }
2477   /// \brief Set the captured variable length array type for this field.
2478   void setCapturedVLAType(const VariableArrayType *VLAType);
2479
2480   /// getParent - Returns the parent of this field declaration, which
2481   /// is the struct in which this method is defined.
2482   const RecordDecl *getParent() const {
2483     return cast<RecordDecl>(getDeclContext());
2484   }
2485
2486   RecordDecl *getParent() {
2487     return cast<RecordDecl>(getDeclContext());
2488   }
2489
2490   SourceRange getSourceRange() const override LLVM_READONLY;
2491
2492   /// Retrieves the canonical declaration of this field.
2493   FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2494   const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2495
2496   // Implement isa/cast/dyncast/etc.
2497   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2498   static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2499
2500   friend class ASTDeclReader;
2501   friend class ASTDeclWriter;
2502 };
2503
2504 /// EnumConstantDecl - An instance of this object exists for each enum constant
2505 /// that is defined.  For example, in "enum X {a,b}", each of a/b are
2506 /// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2507 /// TagType for the X EnumDecl.
2508 class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> {
2509   Stmt *Init; // an integer constant expression
2510   llvm::APSInt Val; // The value.
2511 protected:
2512   EnumConstantDecl(DeclContext *DC, SourceLocation L,
2513                    IdentifierInfo *Id, QualType T, Expr *E,
2514                    const llvm::APSInt &V)
2515     : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2516
2517 public:
2518
2519   static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2520                                   SourceLocation L, IdentifierInfo *Id,
2521                                   QualType T, Expr *E,
2522                                   const llvm::APSInt &V);
2523   static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2524   
2525   const Expr *getInitExpr() const { return (const Expr*) Init; }
2526   Expr *getInitExpr() { return (Expr*) Init; }
2527   const llvm::APSInt &getInitVal() const { return Val; }
2528
2529   void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2530   void setInitVal(const llvm::APSInt &V) { Val = V; }
2531
2532   SourceRange getSourceRange() const override LLVM_READONLY;
2533
2534   /// Retrieves the canonical declaration of this enumerator.
2535   EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); }
2536   const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); }
2537
2538   // Implement isa/cast/dyncast/etc.
2539   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2540   static bool classofKind(Kind K) { return K == EnumConstant; }
2541
2542   friend class StmtIteratorBase;
2543 };
2544
2545 /// IndirectFieldDecl - An instance of this class is created to represent a
2546 /// field injected from an anonymous union/struct into the parent scope.
2547 /// IndirectFieldDecl are always implicit.
2548 class IndirectFieldDecl : public ValueDecl,
2549                           public Mergeable<IndirectFieldDecl> {
2550   void anchor() override;
2551   NamedDecl **Chaining;
2552   unsigned ChainingSize;
2553
2554   IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2555                     DeclarationName N, QualType T,
2556                     MutableArrayRef<NamedDecl *> CH);
2557
2558 public:
2559   static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2560                                    SourceLocation L, IdentifierInfo *Id,
2561                                    QualType T, llvm::MutableArrayRef<NamedDecl *> CH);
2562
2563   static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2564
2565   typedef ArrayRef<NamedDecl *>::const_iterator chain_iterator;
2566
2567   ArrayRef<NamedDecl *> chain() const {
2568     return llvm::makeArrayRef(Chaining, ChainingSize);
2569   }
2570   chain_iterator chain_begin() const { return chain().begin(); }
2571   chain_iterator chain_end() const { return chain().end(); }
2572
2573   unsigned getChainingSize() const { return ChainingSize; }
2574
2575   FieldDecl *getAnonField() const {
2576     assert(chain().size() >= 2);
2577     return cast<FieldDecl>(chain().back());
2578   }
2579
2580   VarDecl *getVarDecl() const {
2581     assert(chain().size() >= 2);
2582     return dyn_cast<VarDecl>(chain().front());
2583   }
2584
2585   IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2586   const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2587
2588   // Implement isa/cast/dyncast/etc.
2589   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2590   static bool classofKind(Kind K) { return K == IndirectField; }
2591   friend class ASTDeclReader;
2592 };
2593
2594 /// TypeDecl - Represents a declaration of a type.
2595 ///
2596 class TypeDecl : public NamedDecl {
2597   void anchor() override;
2598   /// TypeForDecl - This indicates the Type object that represents
2599   /// this TypeDecl.  It is a cache maintained by
2600   /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
2601   /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
2602   mutable const Type *TypeForDecl;
2603   /// LocStart - The start of the source range for this declaration.
2604   SourceLocation LocStart;
2605   friend class ASTContext;
2606
2607 protected:
2608   TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2609            SourceLocation StartL = SourceLocation())
2610     : NamedDecl(DK, DC, L, Id), TypeForDecl(nullptr), LocStart(StartL) {}
2611
2612 public:
2613   // Low-level accessor. If you just want the type defined by this node,
2614   // check out ASTContext::getTypeDeclType or one of
2615   // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
2616   // already know the specific kind of node this is.
2617   const Type *getTypeForDecl() const { return TypeForDecl; }
2618   void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
2619
2620   SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
2621   void setLocStart(SourceLocation L) { LocStart = L; }
2622   SourceRange getSourceRange() const override LLVM_READONLY {
2623     if (LocStart.isValid())
2624       return SourceRange(LocStart, getLocation());
2625     else
2626       return SourceRange(getLocation());
2627   }
2628
2629   // Implement isa/cast/dyncast/etc.
2630   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2631   static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
2632 };
2633
2634
2635 /// Base class for declarations which introduce a typedef-name.
2636 class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
2637   void anchor() override;
2638   typedef std::pair<TypeSourceInfo*, QualType> ModedTInfo;
2639   llvm::PointerUnion<TypeSourceInfo*, ModedTInfo*> MaybeModedTInfo;
2640
2641   // FIXME: This can be packed into the bitfields in Decl.
2642   /// If 0, we have not computed IsTransparentTag.
2643   /// Otherwise, IsTransparentTag is (CacheIsTransparentTag >> 1).
2644   mutable unsigned CacheIsTransparentTag : 2;
2645
2646 protected:
2647   TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC,
2648                   SourceLocation StartLoc, SourceLocation IdLoc,
2649                   IdentifierInfo *Id, TypeSourceInfo *TInfo)
2650       : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
2651         MaybeModedTInfo(TInfo), CacheIsTransparentTag(0) {}
2652
2653   typedef Redeclarable<TypedefNameDecl> redeclarable_base;
2654   TypedefNameDecl *getNextRedeclarationImpl() override {
2655     return getNextRedeclaration();
2656   }
2657   TypedefNameDecl *getPreviousDeclImpl() override {
2658     return getPreviousDecl();
2659   }
2660   TypedefNameDecl *getMostRecentDeclImpl() override {
2661     return getMostRecentDecl();
2662   }
2663
2664 public:
2665   typedef redeclarable_base::redecl_range redecl_range;
2666   typedef redeclarable_base::redecl_iterator redecl_iterator;
2667   using redeclarable_base::redecls_begin;
2668   using redeclarable_base::redecls_end;
2669   using redeclarable_base::redecls;
2670   using redeclarable_base::getPreviousDecl;
2671   using redeclarable_base::getMostRecentDecl;
2672   using redeclarable_base::isFirstDecl;
2673
2674   bool isModed() const { return MaybeModedTInfo.is<ModedTInfo*>(); }
2675
2676   TypeSourceInfo *getTypeSourceInfo() const {
2677     return isModed()
2678       ? MaybeModedTInfo.get<ModedTInfo*>()->first
2679       : MaybeModedTInfo.get<TypeSourceInfo*>();
2680   }
2681   QualType getUnderlyingType() const {
2682     return isModed()
2683       ? MaybeModedTInfo.get<ModedTInfo*>()->second
2684       : MaybeModedTInfo.get<TypeSourceInfo*>()->getType();
2685   }
2686   void setTypeSourceInfo(TypeSourceInfo *newType) {
2687     MaybeModedTInfo = newType;
2688   }
2689   void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
2690     MaybeModedTInfo = new (getASTContext()) ModedTInfo(unmodedTSI, modedTy);
2691   }
2692
2693   /// Retrieves the canonical declaration of this typedef-name.
2694   TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); }
2695   const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); }
2696
2697   /// Retrieves the tag declaration for which this is the typedef name for
2698   /// linkage purposes, if any.
2699   ///
2700   /// \param AnyRedecl Look for the tag declaration in any redeclaration of
2701   /// this typedef declaration.
2702   TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const;
2703
2704   /// Determines if this typedef shares a name and spelling location with its
2705   /// underlying tag type, as is the case with the NS_ENUM macro.
2706   bool isTransparentTag() const {
2707     if (CacheIsTransparentTag)
2708       return CacheIsTransparentTag & 0x2;
2709     return isTransparentTagSlow();
2710   }
2711
2712   // Implement isa/cast/dyncast/etc.
2713   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2714   static bool classofKind(Kind K) {
2715     return K >= firstTypedefName && K <= lastTypedefName;
2716   }
2717
2718 private:
2719   bool isTransparentTagSlow() const;
2720 };
2721
2722 /// TypedefDecl - Represents the declaration of a typedef-name via the 'typedef'
2723 /// type specifier.
2724 class TypedefDecl : public TypedefNameDecl {
2725   TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2726               SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
2727       : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {}
2728
2729 public:
2730   static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
2731                              SourceLocation StartLoc, SourceLocation IdLoc,
2732                              IdentifierInfo *Id, TypeSourceInfo *TInfo);
2733   static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2734
2735   SourceRange getSourceRange() const override LLVM_READONLY;
2736
2737   // Implement isa/cast/dyncast/etc.
2738   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2739   static bool classofKind(Kind K) { return K == Typedef; }
2740 };
2741
2742 /// TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x
2743 /// alias-declaration.
2744 class TypeAliasDecl : public TypedefNameDecl {
2745   /// The template for which this is the pattern, if any.
2746   TypeAliasTemplateDecl *Template;
2747
2748   TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2749                 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
2750       : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
2751         Template(nullptr) {}
2752
2753 public:
2754   static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
2755                                SourceLocation StartLoc, SourceLocation IdLoc,
2756                                IdentifierInfo *Id, TypeSourceInfo *TInfo);
2757   static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2758
2759   SourceRange getSourceRange() const override LLVM_READONLY;
2760
2761   TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; }
2762   void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; }
2763
2764   // Implement isa/cast/dyncast/etc.
2765   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2766   static bool classofKind(Kind K) { return K == TypeAlias; }
2767 };
2768
2769 /// TagDecl - Represents the declaration of a struct/union/class/enum.
2770 class TagDecl
2771   : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
2772 public:
2773   // This is really ugly.
2774   typedef TagTypeKind TagKind;
2775
2776 private:
2777   // FIXME: This can be packed into the bitfields in Decl.
2778   /// TagDeclKind - The TagKind enum.
2779   unsigned TagDeclKind : 3;
2780
2781   /// IsCompleteDefinition - True if this is a definition ("struct foo
2782   /// {};"), false if it is a declaration ("struct foo;").  It is not
2783   /// a definition until the definition has been fully processed.
2784   unsigned IsCompleteDefinition : 1;
2785
2786 protected:
2787   /// IsBeingDefined - True if this is currently being defined.
2788   unsigned IsBeingDefined : 1;
2789
2790 private:
2791   /// IsEmbeddedInDeclarator - True if this tag declaration is
2792   /// "embedded" (i.e., defined or declared for the very first time)
2793   /// in the syntax of a declarator.
2794   unsigned IsEmbeddedInDeclarator : 1;
2795
2796   /// \brief True if this tag is free standing, e.g. "struct foo;".
2797   unsigned IsFreeStanding : 1;
2798
2799 protected:
2800   // These are used by (and only defined for) EnumDecl.
2801   unsigned NumPositiveBits : 8;
2802   unsigned NumNegativeBits : 8;
2803
2804   /// IsScoped - True if this tag declaration is a scoped enumeration. Only
2805   /// possible in C++11 mode.
2806   unsigned IsScoped : 1;
2807   /// IsScopedUsingClassTag - If this tag declaration is a scoped enum,
2808   /// then this is true if the scoped enum was declared using the class
2809   /// tag, false if it was declared with the struct tag. No meaning is
2810   /// associated if this tag declaration is not a scoped enum.
2811   unsigned IsScopedUsingClassTag : 1;
2812
2813   /// IsFixed - True if this is an enumeration with fixed underlying type. Only
2814   /// possible in C++11, Microsoft extensions, or Objective C mode.
2815   unsigned IsFixed : 1;
2816
2817   /// \brief Indicates whether it is possible for declarations of this kind
2818   /// to have an out-of-date definition.
2819   ///
2820   /// This option is only enabled when modules are enabled.
2821   unsigned MayHaveOutOfDateDef : 1;
2822
2823   /// Has the full definition of this type been required by a use somewhere in
2824   /// the TU.
2825   unsigned IsCompleteDefinitionRequired : 1;
2826 private:
2827   SourceRange BraceRange;
2828
2829   // A struct representing syntactic qualifier info,
2830   // to be used for the (uncommon) case of out-of-line declarations.
2831   typedef QualifierInfo ExtInfo;
2832
2833   /// \brief If the (out-of-line) tag declaration name
2834   /// is qualified, it points to the qualifier info (nns and range);
2835   /// otherwise, if the tag declaration is anonymous and it is part of
2836   /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
2837   /// otherwise, if the tag declaration is anonymous and it is used as a
2838   /// declaration specifier for variables, it points to the first VarDecl (used
2839   /// for mangling);
2840   /// otherwise, it is a null (TypedefNameDecl) pointer.
2841   llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier;
2842
2843   bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); }
2844   ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); }
2845   const ExtInfo *getExtInfo() const {
2846     return TypedefNameDeclOrQualifier.get<ExtInfo *>();
2847   }
2848
2849 protected:
2850   TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
2851           SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
2852           SourceLocation StartL)
2853       : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
2854         TagDeclKind(TK), IsCompleteDefinition(false), IsBeingDefined(false),
2855         IsEmbeddedInDeclarator(false), IsFreeStanding(false),
2856         IsCompleteDefinitionRequired(false),
2857         TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
2858     assert((DK != Enum || TK == TTK_Enum) &&
2859            "EnumDecl not matched with TTK_Enum");
2860     setPreviousDecl(PrevDecl);
2861   }
2862
2863   typedef Redeclarable<TagDecl> redeclarable_base;
2864   TagDecl *getNextRedeclarationImpl() override {
2865     return getNextRedeclaration();
2866   }
2867   TagDecl *getPreviousDeclImpl() override {
2868     return getPreviousDecl();
2869   }
2870   TagDecl *getMostRecentDeclImpl() override {
2871     return getMostRecentDecl();
2872   }
2873
2874   /// @brief Completes the definition of this tag declaration.
2875   ///
2876   /// This is a helper function for derived classes.
2877   void completeDefinition();
2878
2879 public:
2880   typedef redeclarable_base::redecl_range redecl_range;
2881   typedef redeclarable_base::redecl_iterator redecl_iterator;
2882   using redeclarable_base::redecls_begin;
2883   using redeclarable_base::redecls_end;
2884   using redeclarable_base::redecls;
2885   using redeclarable_base::getPreviousDecl;
2886   using redeclarable_base::getMostRecentDecl;
2887   using redeclarable_base::isFirstDecl;
2888
2889   SourceRange getBraceRange() const { return BraceRange; }
2890   void setBraceRange(SourceRange R) { BraceRange = R; }
2891
2892   /// getInnerLocStart - Return SourceLocation representing start of source
2893   /// range ignoring outer template declarations.
2894   SourceLocation getInnerLocStart() const { return getLocStart(); }
2895
2896   /// getOuterLocStart - Return SourceLocation representing start of source
2897   /// range taking into account any outer template declarations.
2898   SourceLocation getOuterLocStart() const;
2899   SourceRange getSourceRange() const override LLVM_READONLY;
2900
2901   TagDecl *getCanonicalDecl() override;
2902   const TagDecl *getCanonicalDecl() const {
2903     return const_cast<TagDecl*>(this)->getCanonicalDecl();
2904   }
2905
2906   /// isThisDeclarationADefinition() - Return true if this declaration
2907   /// is a completion definition of the type.  Provided for consistency.
2908   bool isThisDeclarationADefinition() const {
2909     return isCompleteDefinition();
2910   }
2911
2912   /// isCompleteDefinition - Return true if this decl has its body
2913   /// fully specified.
2914   bool isCompleteDefinition() const {
2915     return IsCompleteDefinition;
2916   }
2917
2918   /// \brief Return true if this complete decl is
2919   /// required to be complete for some existing use.
2920   bool isCompleteDefinitionRequired() const {
2921     return IsCompleteDefinitionRequired;
2922   }
2923
2924   /// isBeingDefined - Return true if this decl is currently being defined.
2925   bool isBeingDefined() const {
2926     return IsBeingDefined;
2927   }
2928
2929   bool isEmbeddedInDeclarator() const {
2930     return IsEmbeddedInDeclarator;
2931   }
2932   void setEmbeddedInDeclarator(bool isInDeclarator) {
2933     IsEmbeddedInDeclarator = isInDeclarator;
2934   }
2935
2936   bool isFreeStanding() const { return IsFreeStanding; }
2937   void setFreeStanding(bool isFreeStanding = true) {
2938     IsFreeStanding = isFreeStanding;
2939   }
2940
2941   /// \brief Whether this declaration declares a type that is
2942   /// dependent, i.e., a type that somehow depends on template
2943   /// parameters.
2944   bool isDependentType() const { return isDependentContext(); }
2945
2946   /// @brief Starts the definition of this tag declaration.
2947   ///
2948   /// This method should be invoked at the beginning of the definition
2949   /// of this tag declaration. It will set the tag type into a state
2950   /// where it is in the process of being defined.
2951   void startDefinition();
2952
2953   /// getDefinition - Returns the TagDecl that actually defines this
2954   ///  struct/union/class/enum.  When determining whether or not a
2955   ///  struct/union/class/enum has a definition, one should use this
2956   ///  method as opposed to 'isDefinition'.  'isDefinition' indicates
2957   ///  whether or not a specific TagDecl is defining declaration, not
2958   ///  whether or not the struct/union/class/enum type is defined.
2959   ///  This method returns NULL if there is no TagDecl that defines
2960   ///  the struct/union/class/enum.
2961   TagDecl *getDefinition() const;
2962
2963   void setCompleteDefinition(bool V) { IsCompleteDefinition = V; }
2964
2965   void setCompleteDefinitionRequired(bool V = true) {
2966     IsCompleteDefinitionRequired = V;
2967   }
2968
2969   StringRef getKindName() const {
2970     return TypeWithKeyword::getTagTypeKindName(getTagKind());
2971   }
2972
2973   TagKind getTagKind() const {
2974     return TagKind(TagDeclKind);
2975   }
2976
2977   void setTagKind(TagKind TK) { TagDeclKind = TK; }
2978
2979   bool isStruct() const { return getTagKind() == TTK_Struct; }
2980   bool isInterface() const { return getTagKind() == TTK_Interface; }
2981   bool isClass()  const { return getTagKind() == TTK_Class; }
2982   bool isUnion()  const { return getTagKind() == TTK_Union; }
2983   bool isEnum()   const { return getTagKind() == TTK_Enum; }
2984
2985   /// Is this tag type named, either directly or via being defined in
2986   /// a typedef of this type?
2987   ///
2988   /// C++11 [basic.link]p8:
2989   ///   A type is said to have linkage if and only if:
2990   ///     - it is a class or enumeration type that is named (or has a
2991   ///       name for linkage purposes) and the name has linkage; ...
2992   /// C++11 [dcl.typedef]p9:
2993   ///   If the typedef declaration defines an unnamed class (or enum),
2994   ///   the first typedef-name declared by the declaration to be that
2995   ///   class type (or enum type) is used to denote the class type (or
2996   ///   enum type) for linkage purposes only.
2997   ///
2998   /// C does not have an analogous rule, but the same concept is
2999   /// nonetheless useful in some places.
3000   bool hasNameForLinkage() const {
3001     return (getDeclName() || getTypedefNameForAnonDecl());
3002   }
3003
3004   TypedefNameDecl *getTypedefNameForAnonDecl() const {
3005     return hasExtInfo() ? nullptr
3006                         : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>();
3007   }
3008
3009   void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
3010
3011   /// \brief Retrieve the nested-name-specifier that qualifies the name of this
3012   /// declaration, if it was present in the source.
3013   NestedNameSpecifier *getQualifier() const {
3014     return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
3015                         : nullptr;
3016   }
3017
3018   /// \brief Retrieve the nested-name-specifier (with source-location
3019   /// information) that qualifies the name of this declaration, if it was
3020   /// present in the source.
3021   NestedNameSpecifierLoc getQualifierLoc() const {
3022     return hasExtInfo() ? getExtInfo()->QualifierLoc
3023                         : NestedNameSpecifierLoc();
3024   }
3025
3026   void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
3027
3028   unsigned getNumTemplateParameterLists() const {
3029     return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
3030   }
3031   TemplateParameterList *getTemplateParameterList(unsigned i) const {
3032     assert(i < getNumTemplateParameterLists());
3033     return getExtInfo()->TemplParamLists[i];
3034   }
3035   void setTemplateParameterListsInfo(ASTContext &Context,
3036                                      ArrayRef<TemplateParameterList *> TPLists);
3037
3038   // Implement isa/cast/dyncast/etc.
3039   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3040   static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
3041
3042   static DeclContext *castToDeclContext(const TagDecl *D) {
3043     return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
3044   }
3045   static TagDecl *castFromDeclContext(const DeclContext *DC) {
3046     return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
3047   }
3048
3049   friend class ASTDeclReader;
3050   friend class ASTDeclWriter;
3051 };
3052
3053 /// EnumDecl - Represents an enum.  In C++11, enums can be forward-declared
3054 /// with a fixed underlying type, and in C we allow them to be forward-declared
3055 /// with no underlying type as an extension.
3056 class EnumDecl : public TagDecl {
3057   void anchor() override;
3058   /// IntegerType - This represent the integer type that the enum corresponds
3059   /// to for code generation purposes.  Note that the enumerator constants may
3060   /// have a different type than this does.
3061   ///
3062   /// If the underlying integer type was explicitly stated in the source
3063   /// code, this is a TypeSourceInfo* for that type. Otherwise this type
3064   /// was automatically deduced somehow, and this is a Type*.
3065   ///
3066   /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
3067   /// some cases it won't.
3068   ///
3069   /// The underlying type of an enumeration never has any qualifiers, so
3070   /// we can get away with just storing a raw Type*, and thus save an
3071   /// extra pointer when TypeSourceInfo is needed.
3072
3073   llvm::PointerUnion<const Type*, TypeSourceInfo*> IntegerType;
3074
3075   /// PromotionType - The integer type that values of this type should
3076   /// promote to.  In C, enumerators are generally of an integer type
3077   /// directly, but gcc-style large enumerators (and all enumerators
3078   /// in C++) are of the enum type instead.
3079   QualType PromotionType;
3080
3081   /// \brief If this enumeration is an instantiation of a member enumeration
3082   /// of a class template specialization, this is the member specialization
3083   /// information.
3084   MemberSpecializationInfo *SpecializationInfo;
3085
3086   EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3087            SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
3088            bool Scoped, bool ScopedUsingClassTag, bool Fixed)
3089       : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc),
3090         SpecializationInfo(nullptr) {
3091     assert(Scoped || !ScopedUsingClassTag);
3092     IntegerType = (const Type *)nullptr;
3093     NumNegativeBits = 0;
3094     NumPositiveBits = 0;
3095     IsScoped = Scoped;
3096     IsScopedUsingClassTag = ScopedUsingClassTag;
3097     IsFixed = Fixed;
3098   }
3099
3100   void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3101                                     TemplateSpecializationKind TSK);
3102 public:
3103   EnumDecl *getCanonicalDecl() override {
3104     return cast<EnumDecl>(TagDecl::getCanonicalDecl());
3105   }
3106   const EnumDecl *getCanonicalDecl() const {
3107     return const_cast<EnumDecl*>(this)->getCanonicalDecl();
3108   }
3109
3110   EnumDecl *getPreviousDecl() {
3111     return cast_or_null<EnumDecl>(
3112             static_cast<TagDecl *>(this)->getPreviousDecl());
3113   }
3114   const EnumDecl *getPreviousDecl() const {
3115     return const_cast<EnumDecl*>(this)->getPreviousDecl();
3116   }
3117
3118   EnumDecl *getMostRecentDecl() {
3119     return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3120   }
3121   const EnumDecl *getMostRecentDecl() const {
3122     return const_cast<EnumDecl*>(this)->getMostRecentDecl();
3123   }
3124
3125   EnumDecl *getDefinition() const {
3126     return cast_or_null<EnumDecl>(TagDecl::getDefinition());
3127   }
3128
3129   static EnumDecl *Create(ASTContext &C, DeclContext *DC,
3130                           SourceLocation StartLoc, SourceLocation IdLoc,
3131                           IdentifierInfo *Id, EnumDecl *PrevDecl,
3132                           bool IsScoped, bool IsScopedUsingClassTag,
3133                           bool IsFixed);
3134   static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3135
3136   /// completeDefinition - When created, the EnumDecl corresponds to a
3137   /// forward-declared enum. This method is used to mark the
3138   /// declaration as being defined; it's enumerators have already been
3139   /// added (via DeclContext::addDecl). NewType is the new underlying
3140   /// type of the enumeration type.
3141   void completeDefinition(QualType NewType,
3142                           QualType PromotionType,
3143                           unsigned NumPositiveBits,
3144                           unsigned NumNegativeBits);
3145
3146   // enumerator_iterator - Iterates through the enumerators of this
3147   // enumeration.
3148   typedef specific_decl_iterator<EnumConstantDecl> enumerator_iterator;
3149   typedef llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>
3150     enumerator_range;
3151
3152   enumerator_range enumerators() const {
3153     return enumerator_range(enumerator_begin(), enumerator_end());
3154   }
3155
3156   enumerator_iterator enumerator_begin() const {
3157     const EnumDecl *E = getDefinition();
3158     if (!E)
3159       E = this;
3160     return enumerator_iterator(E->decls_begin());
3161   }
3162
3163   enumerator_iterator enumerator_end() const {
3164     const EnumDecl *E = getDefinition();
3165     if (!E)
3166       E = this;
3167     return enumerator_iterator(E->decls_end());
3168   }
3169
3170   /// getPromotionType - Return the integer type that enumerators
3171   /// should promote to.
3172   QualType getPromotionType() const { return PromotionType; }
3173
3174   /// \brief Set the promotion type.
3175   void setPromotionType(QualType T) { PromotionType = T; }
3176
3177   /// getIntegerType - Return the integer type this enum decl corresponds to.
3178   /// This returns a null QualType for an enum forward definition with no fixed
3179   /// underlying type.
3180   QualType getIntegerType() const {
3181     if (!IntegerType)
3182       return QualType();
3183     if (const Type *T = IntegerType.dyn_cast<const Type*>())
3184       return QualType(T, 0);
3185     return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType();
3186   }
3187
3188   /// \brief Set the underlying integer type.
3189   void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
3190
3191   /// \brief Set the underlying integer type source info.
3192   void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; }
3193
3194   /// \brief Return the type source info for the underlying integer type,
3195   /// if no type source info exists, return 0.
3196   TypeSourceInfo *getIntegerTypeSourceInfo() const {
3197     return IntegerType.dyn_cast<TypeSourceInfo*>();
3198   }
3199
3200   /// \brief Retrieve the source range that covers the underlying type if
3201   /// specified.
3202   SourceRange getIntegerTypeRange() const LLVM_READONLY;
3203
3204   /// \brief Returns the width in bits required to store all the
3205   /// non-negative enumerators of this enum.
3206   unsigned getNumPositiveBits() const {
3207     return NumPositiveBits;
3208   }
3209   void setNumPositiveBits(unsigned Num) {
3210     NumPositiveBits = Num;
3211     assert(NumPositiveBits == Num && "can't store this bitcount");
3212   }
3213
3214   /// \brief Returns the width in bits required to store all the
3215   /// negative enumerators of this enum.  These widths include
3216   /// the rightmost leading 1;  that is:
3217   ///
3218   /// MOST NEGATIVE ENUMERATOR     PATTERN     NUM NEGATIVE BITS
3219   /// ------------------------     -------     -----------------
3220   ///                       -1     1111111                     1
3221   ///                      -10     1110110                     5
3222   ///                     -101     1001011                     8
3223   unsigned getNumNegativeBits() const {
3224     return NumNegativeBits;
3225   }
3226   void setNumNegativeBits(unsigned Num) {
3227     NumNegativeBits = Num;
3228   }
3229
3230   /// \brief Returns true if this is a C++11 scoped enumeration.
3231   bool isScoped() const {
3232     return IsScoped;
3233   }
3234
3235   /// \brief Returns true if this is a C++11 scoped enumeration.
3236   bool isScopedUsingClassTag() const {
3237     return IsScopedUsingClassTag;
3238   }
3239
3240   /// \brief Returns true if this is an Objective-C, C++11, or
3241   /// Microsoft-style enumeration with a fixed underlying type.
3242   bool isFixed() const {
3243     return IsFixed;
3244   }
3245
3246   /// \brief Returns true if this can be considered a complete type.
3247   bool isComplete() const {
3248     return isCompleteDefinition() || isFixed();
3249   }
3250
3251   /// Returns true if this enum is either annotated with
3252   /// enum_extensibility(closed) or isn't annotated with enum_extensibility.
3253   bool isClosed() const;
3254
3255   /// Returns true if this enum is annotated with flag_enum and isn't annotated
3256   /// with enum_extensibility(open).
3257   bool isClosedFlag() const;
3258
3259   /// Returns true if this enum is annotated with neither flag_enum nor
3260   /// enum_extensibility(open).
3261   bool isClosedNonFlag() const;
3262
3263   /// \brief Retrieve the enum definition from which this enumeration could
3264   /// be instantiated, if it is an instantiation (rather than a non-template).
3265   EnumDecl *getTemplateInstantiationPattern() const;
3266
3267   /// \brief Returns the enumeration (declared within the template)
3268   /// from which this enumeration type was instantiated, or NULL if
3269   /// this enumeration was not instantiated from any template.
3270   EnumDecl *getInstantiatedFromMemberEnum() const;
3271
3272   /// \brief If this enumeration is a member of a specialization of a
3273   /// templated class, determine what kind of template specialization
3274   /// or instantiation this is.
3275   TemplateSpecializationKind getTemplateSpecializationKind() const;
3276
3277   /// \brief For an enumeration member that was instantiated from a member
3278   /// enumeration of a templated class, set the template specialiation kind.
3279   void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3280                         SourceLocation PointOfInstantiation = SourceLocation());
3281
3282   /// \brief If this enumeration is an instantiation of a member enumeration of
3283   /// a class template specialization, retrieves the member specialization
3284   /// information.
3285   MemberSpecializationInfo *getMemberSpecializationInfo() const {
3286     return SpecializationInfo;
3287   }
3288
3289   /// \brief Specify that this enumeration is an instantiation of the
3290   /// member enumeration ED.
3291   void setInstantiationOfMemberEnum(EnumDecl *ED,
3292                                     TemplateSpecializationKind TSK) {
3293     setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
3294   }
3295
3296   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3297   static bool classofKind(Kind K) { return K == Enum; }
3298
3299   friend class ASTDeclReader;
3300 };
3301
3302
3303 /// RecordDecl - Represents a struct/union/class.  For example:
3304 ///   struct X;                  // Forward declaration, no "body".
3305 ///   union Y { int A, B; };     // Has body with members A and B (FieldDecls).
3306 /// This decl will be marked invalid if *any* members are invalid.
3307 ///
3308 class RecordDecl : public TagDecl {
3309   // FIXME: This can be packed into the bitfields in Decl.
3310   /// HasFlexibleArrayMember - This is true if this struct ends with a flexible
3311   /// array member (e.g. int X[]) or if this union contains a struct that does.
3312   /// If so, this cannot be contained in arrays or other structs as a member.
3313   bool HasFlexibleArrayMember : 1;
3314
3315   /// AnonymousStructOrUnion - Whether this is the type of an anonymous struct
3316   /// or union.
3317   bool AnonymousStructOrUnion : 1;
3318
3319   /// HasObjectMember - This is true if this struct has at least one member
3320   /// containing an Objective-C object pointer type.
3321   bool HasObjectMember : 1;
3322   
3323   /// HasVolatileMember - This is true if struct has at least one member of
3324   /// 'volatile' type.
3325   bool HasVolatileMember : 1;
3326
3327   /// \brief Whether the field declarations of this record have been loaded
3328   /// from external storage. To avoid unnecessary deserialization of
3329   /// methods/nested types we allow deserialization of just the fields
3330   /// when needed.
3331   mutable bool LoadedFieldsFromExternalStorage : 1;
3332   friend class DeclContext;
3333
3334 protected:
3335   RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3336              SourceLocation StartLoc, SourceLocation IdLoc,
3337              IdentifierInfo *Id, RecordDecl *PrevDecl);
3338
3339 public:
3340   static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3341                             SourceLocation StartLoc, SourceLocation IdLoc,
3342                             IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr);
3343   static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
3344
3345   RecordDecl *getPreviousDecl() {
3346     return cast_or_null<RecordDecl>(
3347             static_cast<TagDecl *>(this)->getPreviousDecl());
3348   }
3349   const RecordDecl *getPreviousDecl() const {
3350     return const_cast<RecordDecl*>(this)->getPreviousDecl();
3351   }
3352
3353   RecordDecl *getMostRecentDecl() {
3354     return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3355   }
3356   const RecordDecl *getMostRecentDecl() const {
3357     return const_cast<RecordDecl*>(this)->getMostRecentDecl();
3358   }
3359
3360   bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
3361   void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
3362
3363   /// isAnonymousStructOrUnion - Whether this is an anonymous struct
3364   /// or union. To be an anonymous struct or union, it must have been
3365   /// declared without a name and there must be no objects of this
3366   /// type declared, e.g.,
3367   /// @code
3368   ///   union { int i; float f; };
3369   /// @endcode
3370   /// is an anonymous union but neither of the following are:
3371   /// @code
3372   ///  union X { int i; float f; };
3373   ///  union { int i; float f; } obj;
3374   /// @endcode
3375   bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
3376   void setAnonymousStructOrUnion(bool Anon) {
3377     AnonymousStructOrUnion = Anon;
3378   }
3379
3380   bool hasObjectMember() const { return HasObjectMember; }
3381   void setHasObjectMember (bool val) { HasObjectMember = val; }
3382
3383   bool hasVolatileMember() const { return HasVolatileMember; }
3384   void setHasVolatileMember (bool val) { HasVolatileMember = val; }
3385
3386   bool hasLoadedFieldsFromExternalStorage() const {
3387     return LoadedFieldsFromExternalStorage;
3388   }
3389   void setHasLoadedFieldsFromExternalStorage(bool val) {
3390     LoadedFieldsFromExternalStorage = val;
3391   }
3392
3393   /// \brief Determines whether this declaration represents the
3394   /// injected class name.
3395   ///
3396   /// The injected class name in C++ is the name of the class that
3397   /// appears inside the class itself. For example:
3398   ///
3399   /// \code
3400   /// struct C {
3401   ///   // C is implicitly declared here as a synonym for the class name.
3402   /// };
3403   ///
3404   /// C::C c; // same as "C c;"
3405   /// \endcode
3406   bool isInjectedClassName() const;
3407
3408   /// \brief Determine whether this record is a class describing a lambda
3409   /// function object.
3410   bool isLambda() const;
3411
3412   /// \brief Determine whether this record is a record for captured variables in
3413   /// CapturedStmt construct.
3414   bool isCapturedRecord() const;
3415   /// \brief Mark the record as a record for captured variables in CapturedStmt
3416   /// construct.
3417   void setCapturedRecord();
3418
3419   /// getDefinition - Returns the RecordDecl that actually defines
3420   ///  this struct/union/class.  When determining whether or not a
3421   ///  struct/union/class is completely defined, one should use this
3422   ///  method as opposed to 'isCompleteDefinition'.
3423   ///  'isCompleteDefinition' indicates whether or not a specific
3424   ///  RecordDecl is a completed definition, not whether or not the
3425   ///  record type is defined.  This method returns NULL if there is
3426   ///  no RecordDecl that defines the struct/union/tag.
3427   RecordDecl *getDefinition() const {
3428     return cast_or_null<RecordDecl>(TagDecl::getDefinition());
3429   }
3430
3431   // Iterator access to field members. The field iterator only visits
3432   // the non-static data members of this class, ignoring any static
3433   // data members, functions, constructors, destructors, etc.
3434   typedef specific_decl_iterator<FieldDecl> field_iterator;
3435   typedef llvm::iterator_range<specific_decl_iterator<FieldDecl>> field_range;
3436
3437   field_range fields() const { return field_range(field_begin(), field_end()); }
3438   field_iterator field_begin() const;
3439
3440   field_iterator field_end() const {
3441     return field_iterator(decl_iterator());
3442   }
3443
3444   // field_empty - Whether there are any fields (non-static data
3445   // members) in this record.
3446   bool field_empty() const {
3447     return field_begin() == field_end();
3448   }
3449
3450   /// completeDefinition - Notes that the definition of this type is
3451   /// now complete.
3452   virtual void completeDefinition();
3453
3454   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3455   static bool classofKind(Kind K) {
3456     return K >= firstRecord && K <= lastRecord;
3457   }
3458
3459   /// isMsStrust - Get whether or not this is an ms_struct which can
3460   /// be turned on with an attribute, pragma, or -mms-bitfields
3461   /// commandline option.
3462   bool isMsStruct(const ASTContext &C) const;
3463
3464   /// \brief Whether we are allowed to insert extra padding between fields.
3465   /// These padding are added to help AddressSanitizer detect
3466   /// intra-object-overflow bugs.
3467   bool mayInsertExtraPadding(bool EmitRemark = false) const;
3468
3469   /// Finds the first data member which has a name.
3470   /// nullptr is returned if no named data member exists.
3471   const FieldDecl *findFirstNamedDataMember() const;  
3472
3473 private:
3474   /// \brief Deserialize just the fields.
3475   void LoadFieldsFromExternalStorage() const;
3476 };
3477
3478 class FileScopeAsmDecl : public Decl {
3479   virtual void anchor();
3480   StringLiteral *AsmString;
3481   SourceLocation RParenLoc;
3482   FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
3483                    SourceLocation StartL, SourceLocation EndL)
3484     : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
3485 public:
3486   static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
3487                                   StringLiteral *Str, SourceLocation AsmLoc,
3488                                   SourceLocation RParenLoc);
3489
3490   static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3491   
3492   SourceLocation getAsmLoc() const { return getLocation(); }
3493   SourceLocation getRParenLoc() const { return RParenLoc; }
3494   void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3495   SourceRange getSourceRange() const override LLVM_READONLY {
3496     return SourceRange(getAsmLoc(), getRParenLoc());
3497   }
3498
3499   const StringLiteral *getAsmString() const { return AsmString; }
3500   StringLiteral *getAsmString() { return AsmString; }
3501   void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
3502
3503   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3504   static bool classofKind(Kind K) { return K == FileScopeAsm; }
3505 };
3506
3507 /// BlockDecl - This represents a block literal declaration, which is like an
3508 /// unnamed FunctionDecl.  For example:
3509 /// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
3510 ///
3511 class BlockDecl : public Decl, public DeclContext {
3512 public:
3513   /// A class which contains all the information about a particular
3514   /// captured value.
3515   class Capture {
3516     enum {
3517       flag_isByRef = 0x1,
3518       flag_isNested = 0x2
3519     };
3520
3521     /// The variable being captured.
3522     llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
3523
3524     /// The copy expression, expressed in terms of a DeclRef (or
3525     /// BlockDeclRef) to the captured variable.  Only required if the
3526     /// variable has a C++ class type.
3527     Expr *CopyExpr;
3528
3529   public:
3530     Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
3531       : VariableAndFlags(variable,
3532                   (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
3533         CopyExpr(copy) {}
3534
3535     /// The variable being captured.
3536     VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
3537
3538     /// Whether this is a "by ref" capture, i.e. a capture of a __block
3539     /// variable.
3540     bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
3541
3542     /// Whether this is a nested capture, i.e. the variable captured
3543     /// is not from outside the immediately enclosing function/block.
3544     bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
3545
3546     bool hasCopyExpr() const { return CopyExpr != nullptr; }
3547     Expr *getCopyExpr() const { return CopyExpr; }
3548     void setCopyExpr(Expr *e) { CopyExpr = e; }
3549   };
3550
3551 private:
3552   // FIXME: This can be packed into the bitfields in Decl.
3553   bool IsVariadic : 1;
3554   bool CapturesCXXThis : 1;
3555   bool BlockMissingReturnType : 1;
3556   bool IsConversionFromLambda : 1;
3557   /// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal
3558   /// parameters of this function.  This is null if a prototype or if there are
3559   /// no formals.
3560   ParmVarDecl **ParamInfo;
3561   unsigned NumParams;
3562
3563   Stmt *Body;
3564   TypeSourceInfo *SignatureAsWritten;
3565
3566   const Capture *Captures;
3567   unsigned NumCaptures;
3568
3569   unsigned ManglingNumber;
3570   Decl *ManglingContextDecl;
3571
3572 protected:
3573   BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
3574     : Decl(Block, DC, CaretLoc), DeclContext(Block),
3575       IsVariadic(false), CapturesCXXThis(false),
3576       BlockMissingReturnType(true), IsConversionFromLambda(false),
3577       ParamInfo(nullptr), NumParams(0), Body(nullptr),
3578       SignatureAsWritten(nullptr), Captures(nullptr), NumCaptures(0),
3579       ManglingNumber(0), ManglingContextDecl(nullptr) {}
3580
3581 public:
3582   static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L); 
3583   static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3584   
3585   SourceLocation getCaretLocation() const { return getLocation(); }
3586
3587   bool isVariadic() const { return IsVariadic; }
3588   void setIsVariadic(bool value) { IsVariadic = value; }
3589
3590   CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
3591   Stmt *getBody() const override { return (Stmt*) Body; }
3592   void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
3593
3594   void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
3595   TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
3596
3597   // ArrayRef access to formal parameters.
3598   ArrayRef<ParmVarDecl *> parameters() const {
3599     return {ParamInfo, getNumParams()};
3600   }
3601   MutableArrayRef<ParmVarDecl *> parameters() {
3602     return {ParamInfo, getNumParams()};
3603   }
3604
3605   // Iterator access to formal parameters.
3606   typedef MutableArrayRef<ParmVarDecl *>::iterator param_iterator;
3607   typedef ArrayRef<ParmVarDecl *>::const_iterator param_const_iterator;
3608   bool param_empty() const { return parameters().empty(); }
3609   param_iterator param_begin() { return parameters().begin(); }
3610   param_iterator param_end() { return parameters().end(); }
3611   param_const_iterator param_begin() const { return parameters().begin(); }
3612   param_const_iterator param_end() const { return parameters().end(); }
3613   size_t param_size() const { return parameters().size(); }
3614
3615   unsigned getNumParams() const { return NumParams; }
3616   const ParmVarDecl *getParamDecl(unsigned i) const {
3617     assert(i < getNumParams() && "Illegal param #");
3618     return ParamInfo[i];
3619   }
3620   ParmVarDecl *getParamDecl(unsigned i) {
3621     assert(i < getNumParams() && "Illegal param #");
3622     return ParamInfo[i];
3623   }
3624   void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
3625
3626   /// hasCaptures - True if this block (or its nested blocks) captures
3627   /// anything of local storage from its enclosing scopes.
3628   bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; }
3629
3630   /// getNumCaptures - Returns the number of captured variables.
3631   /// Does not include an entry for 'this'.
3632   unsigned getNumCaptures() const { return NumCaptures; }
3633
3634   typedef ArrayRef<Capture>::const_iterator capture_const_iterator;
3635
3636   ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; }
3637
3638   capture_const_iterator capture_begin() const { return captures().begin(); }
3639   capture_const_iterator capture_end() const { return captures().end(); }
3640
3641   bool capturesCXXThis() const { return CapturesCXXThis; }
3642   bool blockMissingReturnType() const { return BlockMissingReturnType; }
3643   void setBlockMissingReturnType(bool val) { BlockMissingReturnType = val; }
3644
3645   bool isConversionFromLambda() const { return IsConversionFromLambda; }
3646   void setIsConversionFromLambda(bool val) { IsConversionFromLambda = val; }
3647
3648   bool capturesVariable(const VarDecl *var) const;
3649
3650   void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
3651                    bool CapturesCXXThis);
3652
3653    unsigned getBlockManglingNumber() const {
3654      return ManglingNumber;
3655    }
3656    Decl *getBlockManglingContextDecl() const {
3657      return ManglingContextDecl;    
3658    }
3659
3660   void setBlockMangling(unsigned Number, Decl *Ctx) {
3661     ManglingNumber = Number;
3662     ManglingContextDecl = Ctx;
3663   }
3664
3665   SourceRange getSourceRange() const override LLVM_READONLY;
3666
3667   // Implement isa/cast/dyncast/etc.
3668   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3669   static bool classofKind(Kind K) { return K == Block; }
3670   static DeclContext *castToDeclContext(const BlockDecl *D) {
3671     return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
3672   }
3673   static BlockDecl *castFromDeclContext(const DeclContext *DC) {
3674     return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
3675   }
3676 };
3677
3678 /// \brief This represents the body of a CapturedStmt, and serves as its
3679 /// DeclContext.
3680 class CapturedDecl final
3681     : public Decl,
3682       public DeclContext,
3683       private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> {
3684 protected:
3685   size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) {
3686     return NumParams;
3687   }
3688
3689 private:
3690   /// \brief The number of parameters to the outlined function.
3691   unsigned NumParams;
3692   /// \brief The position of context parameter in list of parameters.
3693   unsigned ContextParam;
3694   /// \brief The body of the outlined function.
3695   llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow;
3696
3697   explicit CapturedDecl(DeclContext *DC, unsigned NumParams);
3698
3699   ImplicitParamDecl *const *getParams() const {
3700     return getTrailingObjects<ImplicitParamDecl *>();
3701   }
3702
3703   ImplicitParamDecl **getParams() {
3704     return getTrailingObjects<ImplicitParamDecl *>();
3705   }
3706
3707 public:
3708   static CapturedDecl *Create(ASTContext &C, DeclContext *DC,
3709                               unsigned NumParams);
3710   static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3711                                           unsigned NumParams);
3712
3713   Stmt *getBody() const override;
3714   void setBody(Stmt *B);
3715
3716   bool isNothrow() const;
3717   void setNothrow(bool Nothrow = true);
3718
3719   unsigned getNumParams() const { return NumParams; }
3720
3721   ImplicitParamDecl *getParam(unsigned i) const {
3722     assert(i < NumParams);
3723     return getParams()[i];
3724   }
3725   void setParam(unsigned i, ImplicitParamDecl *P) {
3726     assert(i < NumParams);
3727     getParams()[i] = P;
3728   }
3729
3730   // ArrayRef interface to parameters.
3731   ArrayRef<ImplicitParamDecl *> parameters() const {
3732     return {getParams(), getNumParams()};
3733   }
3734   MutableArrayRef<ImplicitParamDecl *> parameters() {
3735     return {getParams(), getNumParams()};
3736   }
3737
3738   /// \brief Retrieve the parameter containing captured variables.
3739   ImplicitParamDecl *getContextParam() const {
3740     assert(ContextParam < NumParams);
3741     return getParam(ContextParam);
3742   }
3743   void setContextParam(unsigned i, ImplicitParamDecl *P) {
3744     assert(i < NumParams);
3745     ContextParam = i;
3746     setParam(i, P);
3747   }
3748   unsigned getContextParamPosition() const { return ContextParam; }
3749
3750   typedef ImplicitParamDecl *const *param_iterator;
3751   typedef llvm::iterator_range<param_iterator> param_range;
3752
3753   /// \brief Retrieve an iterator pointing to the first parameter decl.
3754   param_iterator param_begin() const { return getParams(); }
3755   /// \brief Retrieve an iterator one past the last parameter decl.
3756   param_iterator param_end() const { return getParams() + NumParams; }
3757
3758   // Implement isa/cast/dyncast/etc.
3759   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3760   static bool classofKind(Kind K) { return K == Captured; }
3761   static DeclContext *castToDeclContext(const CapturedDecl *D) {
3762     return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D));
3763   }
3764   static CapturedDecl *castFromDeclContext(const DeclContext *DC) {
3765     return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC));
3766   }
3767
3768   friend class ASTDeclReader;
3769   friend class ASTDeclWriter;
3770   friend TrailingObjects;
3771 };
3772
3773 /// \brief Describes a module import declaration, which makes the contents
3774 /// of the named module visible in the current translation unit.
3775 ///
3776 /// An import declaration imports the named module (or submodule). For example:
3777 /// \code
3778 ///   @import std.vector;
3779 /// \endcode
3780 ///
3781 /// Import declarations can also be implicitly generated from
3782 /// \#include/\#import directives.
3783 class ImportDecl final : public Decl,
3784                          llvm::TrailingObjects<ImportDecl, SourceLocation> {
3785   /// \brief The imported module, along with a bit that indicates whether
3786   /// we have source-location information for each identifier in the module
3787   /// name. 
3788   ///
3789   /// When the bit is false, we only have a single source location for the
3790   /// end of the import declaration.
3791   llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete;
3792   
3793   /// \brief The next import in the list of imports local to the translation
3794   /// unit being parsed (not loaded from an AST file).
3795   ImportDecl *NextLocalImport;
3796   
3797   friend class ASTReader;
3798   friend class ASTDeclReader;
3799   friend class ASTContext;
3800   friend TrailingObjects;
3801
3802   ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3803              ArrayRef<SourceLocation> IdentifierLocs);
3804
3805   ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3806              SourceLocation EndLoc);
3807
3808   ImportDecl(EmptyShell Empty) : Decl(Import, Empty), NextLocalImport() { }
3809   
3810 public:
3811   /// \brief Create a new module import declaration.
3812   static ImportDecl *Create(ASTContext &C, DeclContext *DC, 
3813                             SourceLocation StartLoc, Module *Imported,
3814                             ArrayRef<SourceLocation> IdentifierLocs);
3815   
3816   /// \brief Create a new module import declaration for an implicitly-generated
3817   /// import.
3818   static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC, 
3819                                     SourceLocation StartLoc, Module *Imported, 
3820                                     SourceLocation EndLoc);
3821   
3822   /// \brief Create a new, deserialized module import declaration.
3823   static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID, 
3824                                         unsigned NumLocations);
3825   
3826   /// \brief Retrieve the module that was imported by the import declaration.
3827   Module *getImportedModule() const { return ImportedAndComplete.getPointer(); }
3828   
3829   /// \brief Retrieves the locations of each of the identifiers that make up
3830   /// the complete module name in the import declaration.
3831   ///
3832   /// This will return an empty array if the locations of the individual
3833   /// identifiers aren't available.
3834   ArrayRef<SourceLocation> getIdentifierLocs() const;
3835
3836   SourceRange getSourceRange() const override LLVM_READONLY;
3837
3838   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3839   static bool classofKind(Kind K) { return K == Import; }
3840 };
3841
3842 /// \brief Represents a C++ Modules TS module export declaration.
3843 ///
3844 /// For example:
3845 /// \code
3846 ///   export void foo();
3847 /// \endcode
3848 class ExportDecl final : public Decl, public DeclContext {
3849   virtual void anchor();
3850 private:
3851   /// \brief The source location for the right brace (if valid).
3852   SourceLocation RBraceLoc;
3853
3854   ExportDecl(DeclContext *DC, SourceLocation ExportLoc)
3855     : Decl(Export, DC, ExportLoc), DeclContext(Export),
3856       RBraceLoc(SourceLocation()) { }
3857
3858   friend class ASTDeclReader;
3859
3860 public:
3861   static ExportDecl *Create(ASTContext &C, DeclContext *DC,
3862                             SourceLocation ExportLoc);
3863   static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3864   
3865   SourceLocation getExportLoc() const { return getLocation(); }
3866   SourceLocation getRBraceLoc() const { return RBraceLoc; }
3867   void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
3868
3869   SourceLocation getLocEnd() const LLVM_READONLY {
3870     if (RBraceLoc.isValid())
3871       return RBraceLoc;
3872     // No braces: get the end location of the (only) declaration in context
3873     // (if present).
3874     return decls_empty() ? getLocation() : decls_begin()->getLocEnd();
3875   }
3876
3877   SourceRange getSourceRange() const override LLVM_READONLY {
3878     return SourceRange(getLocation(), getLocEnd());
3879   }
3880
3881   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3882   static bool classofKind(Kind K) { return K == Export; }
3883   static DeclContext *castToDeclContext(const ExportDecl *D) {
3884     return static_cast<DeclContext *>(const_cast<ExportDecl*>(D));
3885   }
3886   static ExportDecl *castFromDeclContext(const DeclContext *DC) {
3887     return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC));
3888   }
3889 };
3890
3891 /// \brief Represents an empty-declaration.
3892 class EmptyDecl : public Decl {
3893   virtual void anchor();
3894   EmptyDecl(DeclContext *DC, SourceLocation L)
3895     : Decl(Empty, DC, L) { }
3896
3897 public:
3898   static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
3899                            SourceLocation L);
3900   static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3901
3902   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3903   static bool classofKind(Kind K) { return K == Empty; }
3904 };
3905
3906 /// Insertion operator for diagnostics.  This allows sending NamedDecl's
3907 /// into a diagnostic with <<.
3908 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
3909                                            const NamedDecl* ND) {
3910   DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
3911                   DiagnosticsEngine::ak_nameddecl);
3912   return DB;
3913 }
3914 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
3915                                            const NamedDecl* ND) {
3916   PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
3917                   DiagnosticsEngine::ak_nameddecl);
3918   return PD;
3919 }
3920
3921 template<typename decl_type>
3922 void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) {
3923   // Note: This routine is implemented here because we need both NamedDecl
3924   // and Redeclarable to be defined.
3925   assert(RedeclLink.NextIsLatest() &&
3926          "setPreviousDecl on a decl already in a redeclaration chain");
3927
3928   if (PrevDecl) {
3929     // Point to previous. Make sure that this is actually the most recent
3930     // redeclaration, or we can build invalid chains. If the most recent
3931     // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
3932     First = PrevDecl->getFirstDecl();
3933     assert(First->RedeclLink.NextIsLatest() && "Expected first");
3934     decl_type *MostRecent = First->getNextRedeclaration();
3935     RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent));
3936
3937     // If the declaration was previously visible, a redeclaration of it remains
3938     // visible even if it wouldn't be visible by itself.
3939     static_cast<decl_type*>(this)->IdentifierNamespace |=
3940       MostRecent->getIdentifierNamespace() &
3941       (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
3942   } else {
3943     // Make this first.
3944     First = static_cast<decl_type*>(this);
3945   }
3946
3947   // First one will point to this one as latest.
3948   First->RedeclLink.setLatest(static_cast<decl_type*>(this));
3949
3950   assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
3951          cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid());
3952 }
3953
3954 // Inline function definitions.
3955
3956 /// \brief Check if the given decl is complete.
3957 ///
3958 /// We use this function to break a cycle between the inline definitions in
3959 /// Type.h and Decl.h.
3960 inline bool IsEnumDeclComplete(EnumDecl *ED) {
3961   return ED->isComplete();
3962 }
3963
3964 /// \brief Check if the given decl is scoped.
3965 ///
3966 /// We use this function to break a cycle between the inline definitions in
3967 /// Type.h and Decl.h.
3968 inline bool IsEnumDeclScoped(EnumDecl *ED) {
3969   return ED->isScoped();
3970 }
3971
3972 }  // end namespace clang
3973
3974 #endif