]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/AST/Decl.h
MFV r316917: 7968 multi-threaded spa_sync()
[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 initalizer expression unless we were unble 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 : 2;
1609   unsigned IsInline : 1;
1610   unsigned IsInlineSpecified : 1;
1611   unsigned IsVirtualAsWritten : 1;
1612   unsigned IsPure : 1;
1613   unsigned HasInheritedPrototype : 1;
1614   unsigned HasWrittenPrototype : 1;
1615   unsigned IsDeleted : 1;
1616   unsigned IsTrivial : 1; // sunk from CXXMethodDecl
1617   unsigned IsDefaulted : 1; // sunk from CXXMethoDecl
1618   unsigned IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl
1619   unsigned HasImplicitReturnZero : 1;
1620   unsigned IsLateTemplateParsed : 1;
1621   unsigned IsConstexpr : 1;
1622
1623   /// \brief Indicates if the function uses __try.
1624   unsigned UsesSEHTry : 1;
1625
1626   /// \brief Indicates if the function was a definition but its body was
1627   /// skipped.
1628   unsigned HasSkippedBody : 1;
1629
1630   /// Indicates if the function declaration will have a body, once we're done
1631   /// parsing it.  (We don't set it to false when we're done parsing, in the
1632   /// hopes this is simpler.)
1633   unsigned WillHaveBody : 1;
1634
1635   /// \brief End part of this FunctionDecl's source range.
1636   ///
1637   /// We could compute the full range in getSourceRange(). However, when we're
1638   /// dealing with a function definition deserialized from a PCH/AST file,
1639   /// we can only compute the full range once the function body has been
1640   /// de-serialized, so it's far better to have the (sometimes-redundant)
1641   /// EndRangeLoc.
1642   SourceLocation EndRangeLoc;
1643
1644   /// \brief The template or declaration that this declaration
1645   /// describes or was instantiated from, respectively.
1646   ///
1647   /// For non-templates, this value will be NULL. For function
1648   /// declarations that describe a function template, this will be a
1649   /// pointer to a FunctionTemplateDecl. For member functions
1650   /// of class template specializations, this will be a MemberSpecializationInfo
1651   /// pointer containing information about the specialization.
1652   /// For function template specializations, this will be a
1653   /// FunctionTemplateSpecializationInfo, which contains information about
1654   /// the template being specialized and the template arguments involved in
1655   /// that specialization.
1656   llvm::PointerUnion4<FunctionTemplateDecl *,
1657                       MemberSpecializationInfo *,
1658                       FunctionTemplateSpecializationInfo *,
1659                       DependentFunctionTemplateSpecializationInfo *>
1660     TemplateOrSpecialization;
1661
1662   /// DNLoc - Provides source/type location info for the
1663   /// declaration name embedded in the DeclaratorDecl base class.
1664   DeclarationNameLoc DNLoc;
1665
1666   /// \brief Specify that this function declaration is actually a function
1667   /// template specialization.
1668   ///
1669   /// \param C the ASTContext.
1670   ///
1671   /// \param Template the function template that this function template
1672   /// specialization specializes.
1673   ///
1674   /// \param TemplateArgs the template arguments that produced this
1675   /// function template specialization from the template.
1676   ///
1677   /// \param InsertPos If non-NULL, the position in the function template
1678   /// specialization set where the function template specialization data will
1679   /// be inserted.
1680   ///
1681   /// \param TSK the kind of template specialization this is.
1682   ///
1683   /// \param TemplateArgsAsWritten location info of template arguments.
1684   ///
1685   /// \param PointOfInstantiation point at which the function template
1686   /// specialization was first instantiated.
1687   void setFunctionTemplateSpecialization(ASTContext &C,
1688                                          FunctionTemplateDecl *Template,
1689                                        const TemplateArgumentList *TemplateArgs,
1690                                          void *InsertPos,
1691                                          TemplateSpecializationKind TSK,
1692                           const TemplateArgumentListInfo *TemplateArgsAsWritten,
1693                                          SourceLocation PointOfInstantiation);
1694
1695   /// \brief Specify that this record is an instantiation of the
1696   /// member function FD.
1697   void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1698                                         TemplateSpecializationKind TSK);
1699
1700   void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
1701
1702 protected:
1703   FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1704                const DeclarationNameInfo &NameInfo, QualType T,
1705                TypeSourceInfo *TInfo, StorageClass S, bool isInlineSpecified,
1706                bool isConstexprSpecified)
1707       : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
1708                        StartLoc),
1709         DeclContext(DK), redeclarable_base(C), ParamInfo(nullptr), Body(),
1710         SClass(S), IsInline(isInlineSpecified),
1711         IsInlineSpecified(isInlineSpecified), IsVirtualAsWritten(false),
1712         IsPure(false), HasInheritedPrototype(false), HasWrittenPrototype(true),
1713         IsDeleted(false), IsTrivial(false), IsDefaulted(false),
1714         IsExplicitlyDefaulted(false), HasImplicitReturnZero(false),
1715         IsLateTemplateParsed(false), IsConstexpr(isConstexprSpecified),
1716         UsesSEHTry(false), HasSkippedBody(false), WillHaveBody(false),
1717         EndRangeLoc(NameInfo.getEndLoc()), TemplateOrSpecialization(),
1718         DNLoc(NameInfo.getInfo()) {}
1719
1720   typedef Redeclarable<FunctionDecl> redeclarable_base;
1721   FunctionDecl *getNextRedeclarationImpl() override {
1722     return getNextRedeclaration();
1723   }
1724   FunctionDecl *getPreviousDeclImpl() override {
1725     return getPreviousDecl();
1726   }
1727   FunctionDecl *getMostRecentDeclImpl() override {
1728     return getMostRecentDecl();
1729   }
1730
1731 public:
1732   typedef redeclarable_base::redecl_range redecl_range;
1733   typedef redeclarable_base::redecl_iterator redecl_iterator;
1734   using redeclarable_base::redecls_begin;
1735   using redeclarable_base::redecls_end;
1736   using redeclarable_base::redecls;
1737   using redeclarable_base::getPreviousDecl;
1738   using redeclarable_base::getMostRecentDecl;
1739   using redeclarable_base::isFirstDecl;
1740
1741   static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1742                               SourceLocation StartLoc, SourceLocation NLoc,
1743                               DeclarationName N, QualType T,
1744                               TypeSourceInfo *TInfo,
1745                               StorageClass SC,
1746                               bool isInlineSpecified = false,
1747                               bool hasWrittenPrototype = true,
1748                               bool isConstexprSpecified = false) {
1749     DeclarationNameInfo NameInfo(N, NLoc);
1750     return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo,
1751                                 SC,
1752                                 isInlineSpecified, hasWrittenPrototype,
1753                                 isConstexprSpecified);
1754   }
1755
1756   static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1757                               SourceLocation StartLoc,
1758                               const DeclarationNameInfo &NameInfo,
1759                               QualType T, TypeSourceInfo *TInfo,
1760                               StorageClass SC,
1761                               bool isInlineSpecified,
1762                               bool hasWrittenPrototype,
1763                               bool isConstexprSpecified = false);
1764
1765   static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1766                        
1767   DeclarationNameInfo getNameInfo() const {
1768     return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1769   }
1770
1771   void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1772                             bool Qualified) const override;
1773
1774   void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1775
1776   SourceRange getSourceRange() const override LLVM_READONLY;
1777
1778   /// \brief Returns true if the function has a body (definition). The
1779   /// function body might be in any of the (re-)declarations of this
1780   /// function. The variant that accepts a FunctionDecl pointer will
1781   /// set that function declaration to the actual declaration
1782   /// containing the body (if there is one).
1783   bool hasBody(const FunctionDecl *&Definition) const;
1784
1785   bool hasBody() const override {
1786     const FunctionDecl* Definition;
1787     return hasBody(Definition);
1788   }
1789
1790   /// hasTrivialBody - Returns whether the function has a trivial body that does
1791   /// not require any specific codegen.
1792   bool hasTrivialBody() const;
1793
1794   /// isDefined - Returns true if the function is defined at all, including
1795   /// a deleted definition. Except for the behavior when the function is
1796   /// deleted, behaves like hasBody.
1797   bool isDefined(const FunctionDecl *&Definition) const;
1798
1799   virtual bool isDefined() const {
1800     const FunctionDecl* Definition;
1801     return isDefined(Definition);
1802   }
1803
1804   /// \brief Get the definition for this declaration.
1805   FunctionDecl *getDefinition() {
1806     const FunctionDecl *Definition;
1807     if (isDefined(Definition))
1808       return const_cast<FunctionDecl *>(Definition);
1809     return nullptr;
1810   }
1811   const FunctionDecl *getDefinition() const {
1812     return const_cast<FunctionDecl *>(this)->getDefinition();
1813   }
1814
1815   /// getBody - Retrieve the body (definition) of the function. The
1816   /// function body might be in any of the (re-)declarations of this
1817   /// function. The variant that accepts a FunctionDecl pointer will
1818   /// set that function declaration to the actual declaration
1819   /// containing the body (if there is one).
1820   /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
1821   /// unnecessary AST de-serialization of the body.
1822   Stmt *getBody(const FunctionDecl *&Definition) const;
1823
1824   Stmt *getBody() const override {
1825     const FunctionDecl* Definition;
1826     return getBody(Definition);
1827   }
1828
1829   /// isThisDeclarationADefinition - Returns whether this specific
1830   /// declaration of the function is also a definition. This does not
1831   /// determine whether the function has been defined (e.g., in a
1832   /// previous definition); for that information, use isDefined. Note
1833   /// that this returns false for a defaulted function unless that function
1834   /// has been implicitly defined (possibly as deleted).
1835   bool isThisDeclarationADefinition() const {
1836     return IsDeleted || Body || IsLateTemplateParsed;
1837   }
1838
1839   /// doesThisDeclarationHaveABody - Returns whether this specific
1840   /// declaration of the function has a body - that is, if it is a non-
1841   /// deleted definition.
1842   bool doesThisDeclarationHaveABody() const {
1843     return Body || IsLateTemplateParsed;
1844   }
1845
1846   void setBody(Stmt *B);
1847   void setLazyBody(uint64_t Offset) { Body = Offset; }
1848
1849   /// Whether this function is variadic.
1850   bool isVariadic() const;
1851
1852   /// Whether this function is marked as virtual explicitly.
1853   bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
1854   void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
1855
1856   /// Whether this virtual function is pure, i.e. makes the containing class
1857   /// abstract.
1858   bool isPure() const { return IsPure; }
1859   void setPure(bool P = true);
1860
1861   /// Whether this templated function will be late parsed.
1862   bool isLateTemplateParsed() const { return IsLateTemplateParsed; }
1863   void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; }
1864
1865   /// Whether this function is "trivial" in some specialized C++ senses.
1866   /// Can only be true for default constructors, copy constructors,
1867   /// copy assignment operators, and destructors.  Not meaningful until
1868   /// the class has been fully built by Sema.
1869   bool isTrivial() const { return IsTrivial; }
1870   void setTrivial(bool IT) { IsTrivial = IT; }
1871
1872   /// Whether this function is defaulted per C++0x. Only valid for
1873   /// special member functions.
1874   bool isDefaulted() const { return IsDefaulted; }
1875   void setDefaulted(bool D = true) { IsDefaulted = D; }
1876
1877   /// Whether this function is explicitly defaulted per C++0x. Only valid
1878   /// for special member functions.
1879   bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; }
1880   void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; }
1881
1882   /// Whether falling off this function implicitly returns null/zero.
1883   /// If a more specific implicit return value is required, front-ends
1884   /// should synthesize the appropriate return statements.
1885   bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
1886   void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
1887
1888   /// \brief Whether this function has a prototype, either because one
1889   /// was explicitly written or because it was "inherited" by merging
1890   /// a declaration without a prototype with a declaration that has a
1891   /// prototype.
1892   bool hasPrototype() const {
1893     return HasWrittenPrototype || HasInheritedPrototype;
1894   }
1895
1896   bool hasWrittenPrototype() const { return HasWrittenPrototype; }
1897
1898   /// \brief Whether this function inherited its prototype from a
1899   /// previous declaration.
1900   bool hasInheritedPrototype() const { return HasInheritedPrototype; }
1901   void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
1902
1903   /// Whether this is a (C++11) constexpr function or constexpr constructor.
1904   bool isConstexpr() const { return IsConstexpr; }
1905   void setConstexpr(bool IC) { IsConstexpr = IC; }
1906
1907   /// \brief Indicates the function uses __try.
1908   bool usesSEHTry() const { return UsesSEHTry; }
1909   void setUsesSEHTry(bool UST) { UsesSEHTry = UST; }
1910
1911   /// \brief Whether this function has been deleted.
1912   ///
1913   /// A function that is "deleted" (via the C++0x "= delete" syntax)
1914   /// acts like a normal function, except that it cannot actually be
1915   /// called or have its address taken. Deleted functions are
1916   /// typically used in C++ overload resolution to attract arguments
1917   /// whose type or lvalue/rvalue-ness would permit the use of a
1918   /// different overload that would behave incorrectly. For example,
1919   /// one might use deleted functions to ban implicit conversion from
1920   /// a floating-point number to an Integer type:
1921   ///
1922   /// @code
1923   /// struct Integer {
1924   ///   Integer(long); // construct from a long
1925   ///   Integer(double) = delete; // no construction from float or double
1926   ///   Integer(long double) = delete; // no construction from long double
1927   /// };
1928   /// @endcode
1929   // If a function is deleted, its first declaration must be.
1930   bool isDeleted() const { return getCanonicalDecl()->IsDeleted; }
1931   bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; }
1932   void setDeletedAsWritten(bool D = true) { IsDeleted = D; }
1933
1934   /// \brief Determines whether this function is "main", which is the
1935   /// entry point into an executable program.
1936   bool isMain() const;
1937
1938   /// \brief Determines whether this function is a MSVCRT user defined entry
1939   /// point.
1940   bool isMSVCRTEntryPoint() const;
1941
1942   /// \brief Determines whether this operator new or delete is one
1943   /// of the reserved global placement operators:
1944   ///    void *operator new(size_t, void *);
1945   ///    void *operator new[](size_t, void *);
1946   ///    void operator delete(void *, void *);
1947   ///    void operator delete[](void *, void *);
1948   /// These functions have special behavior under [new.delete.placement]:
1949   ///    These functions are reserved, a C++ program may not define
1950   ///    functions that displace the versions in the Standard C++ library.
1951   ///    The provisions of [basic.stc.dynamic] do not apply to these
1952   ///    reserved placement forms of operator new and operator delete.
1953   ///
1954   /// This function must be an allocation or deallocation function.
1955   bool isReservedGlobalPlacementOperator() const;
1956
1957   /// \brief Determines whether this function is one of the replaceable
1958   /// global allocation functions:
1959   ///    void *operator new(size_t);
1960   ///    void *operator new(size_t, const std::nothrow_t &) noexcept;
1961   ///    void *operator new[](size_t);
1962   ///    void *operator new[](size_t, const std::nothrow_t &) noexcept;
1963   ///    void operator delete(void *) noexcept;
1964   ///    void operator delete(void *, std::size_t) noexcept;      [C++1y]
1965   ///    void operator delete(void *, const std::nothrow_t &) noexcept;
1966   ///    void operator delete[](void *) noexcept;
1967   ///    void operator delete[](void *, std::size_t) noexcept;    [C++1y]
1968   ///    void operator delete[](void *, const std::nothrow_t &) noexcept;
1969   /// These functions have special behavior under C++1y [expr.new]:
1970   ///    An implementation is allowed to omit a call to a replaceable global
1971   ///    allocation function. [...]
1972   bool isReplaceableGlobalAllocationFunction() const;
1973
1974   /// Compute the language linkage.
1975   LanguageLinkage getLanguageLinkage() const;
1976
1977   /// \brief Determines whether this function is a function with
1978   /// external, C linkage.
1979   bool isExternC() const;
1980
1981   /// \brief Determines whether this function's context is, or is nested within,
1982   /// a C++ extern "C" linkage spec.
1983   bool isInExternCContext() const;
1984
1985   /// \brief Determines whether this function's context is, or is nested within,
1986   /// a C++ extern "C++" linkage spec.
1987   bool isInExternCXXContext() const;
1988
1989   /// \brief Determines whether this is a global function.
1990   bool isGlobal() const;
1991
1992   /// \brief Determines whether this function is known to be 'noreturn', through
1993   /// an attribute on its declaration or its type.
1994   bool isNoReturn() const;
1995
1996   /// \brief True if the function was a definition but its body was skipped.
1997   bool hasSkippedBody() const { return HasSkippedBody; }
1998   void setHasSkippedBody(bool Skipped = true) { HasSkippedBody = Skipped; }
1999
2000   /// True if this function will eventually have a body, once it's fully parsed.
2001   bool willHaveBody() const { return WillHaveBody; }
2002   void setWillHaveBody(bool V = true) { WillHaveBody = V; }
2003
2004   void setPreviousDeclaration(FunctionDecl * PrevDecl);
2005
2006   FunctionDecl *getCanonicalDecl() override;
2007   const FunctionDecl *getCanonicalDecl() const {
2008     return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
2009   }
2010
2011   unsigned getBuiltinID() const;
2012
2013   // ArrayRef interface to parameters.
2014   ArrayRef<ParmVarDecl *> parameters() const {
2015     return {ParamInfo, getNumParams()};
2016   }
2017   MutableArrayRef<ParmVarDecl *> parameters() {
2018     return {ParamInfo, getNumParams()};
2019   }
2020
2021   // Iterator access to formal parameters.
2022   typedef MutableArrayRef<ParmVarDecl *>::iterator param_iterator;
2023   typedef ArrayRef<ParmVarDecl *>::const_iterator param_const_iterator;
2024   bool param_empty() const { return parameters().empty(); }
2025   param_iterator param_begin() { return parameters().begin(); }
2026   param_iterator param_end() { return parameters().end(); }
2027   param_const_iterator param_begin() const { return parameters().begin(); }
2028   param_const_iterator param_end() const { return parameters().end(); }
2029   size_t param_size() const { return parameters().size(); }
2030
2031   /// getNumParams - Return the number of parameters this function must have
2032   /// based on its FunctionType.  This is the length of the ParamInfo array
2033   /// after it has been created.
2034   unsigned getNumParams() const;
2035
2036   const ParmVarDecl *getParamDecl(unsigned i) const {
2037     assert(i < getNumParams() && "Illegal param #");
2038     return ParamInfo[i];
2039   }
2040   ParmVarDecl *getParamDecl(unsigned i) {
2041     assert(i < getNumParams() && "Illegal param #");
2042     return ParamInfo[i];
2043   }
2044   void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
2045     setParams(getASTContext(), NewParamInfo);
2046   }
2047
2048   /// getMinRequiredArguments - Returns the minimum number of arguments
2049   /// needed to call this function. This may be fewer than the number of
2050   /// function parameters, if some of the parameters have default
2051   /// arguments (in C++).
2052   unsigned getMinRequiredArguments() const;
2053
2054   QualType getReturnType() const {
2055     assert(getType()->getAs<FunctionType>() && "Expected a FunctionType!");
2056     return getType()->getAs<FunctionType>()->getReturnType();
2057   }
2058
2059   /// \brief Attempt to compute an informative source range covering the
2060   /// function return type. This may omit qualifiers and other information with
2061   /// limited representation in the AST.
2062   SourceRange getReturnTypeSourceRange() const;
2063
2064   /// \brief Attempt to compute an informative source range covering the
2065   /// function exception specification, if any.
2066   SourceRange getExceptionSpecSourceRange() const;
2067
2068   /// \brief Determine the type of an expression that calls this function.
2069   QualType getCallResultType() const {
2070     assert(getType()->getAs<FunctionType>() && "Expected a FunctionType!");
2071     return getType()->getAs<FunctionType>()->getCallResultType(getASTContext());
2072   }
2073
2074   /// \brief Returns the WarnUnusedResultAttr that is either declared on this
2075   /// function, or its return type declaration.
2076   const Attr *getUnusedResultAttr() const;
2077
2078   /// \brief Returns true if this function or its return type has the
2079   /// warn_unused_result attribute. If the return type has the attribute and
2080   /// this function is a method of the return type's class, then false will be
2081   /// returned to avoid spurious warnings on member methods such as assignment
2082   /// operators.
2083   bool hasUnusedResultAttr() const { return getUnusedResultAttr() != nullptr; }
2084
2085   /// \brief Returns the storage class as written in the source. For the
2086   /// computed linkage of symbol, see getLinkage.
2087   StorageClass getStorageClass() const { return StorageClass(SClass); }
2088
2089   /// \brief Determine whether the "inline" keyword was specified for this
2090   /// function.
2091   bool isInlineSpecified() const { return IsInlineSpecified; }
2092
2093   /// Set whether the "inline" keyword was specified for this function.
2094   void setInlineSpecified(bool I) {
2095     IsInlineSpecified = I;
2096     IsInline = I;
2097   }
2098
2099   /// Flag that this function is implicitly inline.
2100   void setImplicitlyInline() {
2101     IsInline = true;
2102   }
2103
2104   /// \brief Determine whether this function should be inlined, because it is
2105   /// either marked "inline" or "constexpr" or is a member function of a class
2106   /// that was defined in the class body.
2107   bool isInlined() const { return IsInline; }
2108
2109   bool isInlineDefinitionExternallyVisible() const;
2110
2111   bool isMSExternInline() const;
2112
2113   bool doesDeclarationForceExternallyVisibleDefinition() const;
2114
2115   /// isOverloadedOperator - Whether this function declaration
2116   /// represents an C++ overloaded operator, e.g., "operator+".
2117   bool isOverloadedOperator() const {
2118     return getOverloadedOperator() != OO_None;
2119   }
2120
2121   OverloadedOperatorKind getOverloadedOperator() const;
2122
2123   const IdentifierInfo *getLiteralIdentifier() const;
2124
2125   /// \brief If this function is an instantiation of a member function
2126   /// of a class template specialization, retrieves the function from
2127   /// which it was instantiated.
2128   ///
2129   /// This routine will return non-NULL for (non-templated) member
2130   /// functions of class templates and for instantiations of function
2131   /// templates. For example, given:
2132   ///
2133   /// \code
2134   /// template<typename T>
2135   /// struct X {
2136   ///   void f(T);
2137   /// };
2138   /// \endcode
2139   ///
2140   /// The declaration for X<int>::f is a (non-templated) FunctionDecl
2141   /// whose parent is the class template specialization X<int>. For
2142   /// this declaration, getInstantiatedFromFunction() will return
2143   /// the FunctionDecl X<T>::A. When a complete definition of
2144   /// X<int>::A is required, it will be instantiated from the
2145   /// declaration returned by getInstantiatedFromMemberFunction().
2146   FunctionDecl *getInstantiatedFromMemberFunction() const;
2147
2148   /// \brief What kind of templated function this is.
2149   TemplatedKind getTemplatedKind() const;
2150
2151   /// \brief If this function is an instantiation of a member function of a
2152   /// class template specialization, retrieves the member specialization
2153   /// information.
2154   MemberSpecializationInfo *getMemberSpecializationInfo() const;
2155
2156   /// \brief Specify that this record is an instantiation of the
2157   /// member function FD.
2158   void setInstantiationOfMemberFunction(FunctionDecl *FD,
2159                                         TemplateSpecializationKind TSK) {
2160     setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
2161   }
2162
2163   /// \brief Retrieves the function template that is described by this
2164   /// function declaration.
2165   ///
2166   /// Every function template is represented as a FunctionTemplateDecl
2167   /// and a FunctionDecl (or something derived from FunctionDecl). The
2168   /// former contains template properties (such as the template
2169   /// parameter lists) while the latter contains the actual
2170   /// description of the template's
2171   /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
2172   /// FunctionDecl that describes the function template,
2173   /// getDescribedFunctionTemplate() retrieves the
2174   /// FunctionTemplateDecl from a FunctionDecl.
2175   FunctionTemplateDecl *getDescribedFunctionTemplate() const;
2176
2177   void setDescribedFunctionTemplate(FunctionTemplateDecl *Template);
2178
2179   /// \brief Determine whether this function is a function template
2180   /// specialization.
2181   bool isFunctionTemplateSpecialization() const {
2182     return getPrimaryTemplate() != nullptr;
2183   }
2184
2185   /// \brief Retrieve the class scope template pattern that this function
2186   ///  template specialization is instantiated from.
2187   FunctionDecl *getClassScopeSpecializationPattern() const;
2188
2189   /// \brief If this function is actually a function template specialization,
2190   /// retrieve information about this function template specialization.
2191   /// Otherwise, returns NULL.
2192   FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const;
2193
2194   /// \brief Determines whether this function is a function template
2195   /// specialization or a member of a class template specialization that can
2196   /// be implicitly instantiated.
2197   bool isImplicitlyInstantiable() const;
2198
2199   /// \brief Determines if the given function was instantiated from a
2200   /// function template.
2201   bool isTemplateInstantiation() const;
2202
2203   /// \brief Retrieve the function declaration from which this function could
2204   /// be instantiated, if it is an instantiation (rather than a non-template
2205   /// or a specialization, for example).
2206   FunctionDecl *getTemplateInstantiationPattern() const;
2207
2208   /// \brief Retrieve the primary template that this function template
2209   /// specialization either specializes or was instantiated from.
2210   ///
2211   /// If this function declaration is not a function template specialization,
2212   /// returns NULL.
2213   FunctionTemplateDecl *getPrimaryTemplate() const;
2214
2215   /// \brief Retrieve the template arguments used to produce this function
2216   /// template specialization from the primary template.
2217   ///
2218   /// If this function declaration is not a function template specialization,
2219   /// returns NULL.
2220   const TemplateArgumentList *getTemplateSpecializationArgs() const;
2221
2222   /// \brief Retrieve the template argument list as written in the sources,
2223   /// if any.
2224   ///
2225   /// If this function declaration is not a function template specialization
2226   /// or if it had no explicit template argument list, returns NULL.
2227   /// Note that it an explicit template argument list may be written empty,
2228   /// e.g., template<> void foo<>(char* s);
2229   const ASTTemplateArgumentListInfo*
2230   getTemplateSpecializationArgsAsWritten() const;
2231
2232   /// \brief Specify that this function declaration is actually a function
2233   /// template specialization.
2234   ///
2235   /// \param Template the function template that this function template
2236   /// specialization specializes.
2237   ///
2238   /// \param TemplateArgs the template arguments that produced this
2239   /// function template specialization from the template.
2240   ///
2241   /// \param InsertPos If non-NULL, the position in the function template
2242   /// specialization set where the function template specialization data will
2243   /// be inserted.
2244   ///
2245   /// \param TSK the kind of template specialization this is.
2246   ///
2247   /// \param TemplateArgsAsWritten location info of template arguments.
2248   ///
2249   /// \param PointOfInstantiation point at which the function template
2250   /// specialization was first instantiated.
2251   void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2252                 const TemplateArgumentList *TemplateArgs,
2253                 void *InsertPos,
2254                 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2255                 const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
2256                 SourceLocation PointOfInstantiation = SourceLocation()) {
2257     setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2258                                       InsertPos, TSK, TemplateArgsAsWritten,
2259                                       PointOfInstantiation);
2260   }
2261
2262   /// \brief Specifies that this function declaration is actually a
2263   /// dependent function template specialization.
2264   void setDependentTemplateSpecialization(ASTContext &Context,
2265                              const UnresolvedSetImpl &Templates,
2266                       const TemplateArgumentListInfo &TemplateArgs);
2267
2268   DependentFunctionTemplateSpecializationInfo *
2269   getDependentSpecializationInfo() const;
2270
2271   /// \brief Determine what kind of template instantiation this function
2272   /// represents.
2273   TemplateSpecializationKind getTemplateSpecializationKind() const;
2274
2275   /// \brief Determine what kind of template instantiation this function
2276   /// represents.
2277   void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2278                         SourceLocation PointOfInstantiation = SourceLocation());
2279
2280   /// \brief Retrieve the (first) point of instantiation of a function template
2281   /// specialization or a member of a class template specialization.
2282   ///
2283   /// \returns the first point of instantiation, if this function was
2284   /// instantiated from a template; otherwise, returns an invalid source
2285   /// location.
2286   SourceLocation getPointOfInstantiation() const;
2287
2288   /// \brief Determine whether this is or was instantiated from an out-of-line
2289   /// definition of a member function.
2290   bool isOutOfLine() const override;
2291
2292   /// \brief Identify a memory copying or setting function.
2293   /// If the given function is a memory copy or setting function, returns
2294   /// the corresponding Builtin ID. If the function is not a memory function,
2295   /// returns 0.
2296   unsigned getMemoryFunctionKind() const;
2297
2298   // Implement isa/cast/dyncast/etc.
2299   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2300   static bool classofKind(Kind K) {
2301     return K >= firstFunction && K <= lastFunction;
2302   }
2303   static DeclContext *castToDeclContext(const FunctionDecl *D) {
2304     return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2305   }
2306   static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2307     return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2308   }
2309
2310   friend class ASTDeclReader;
2311   friend class ASTDeclWriter;
2312 };
2313
2314
2315 /// FieldDecl - An instance of this class is created by Sema::ActOnField to
2316 /// represent a member of a struct/union/class.
2317 class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
2318   // FIXME: This can be packed into the bitfields in Decl.
2319   unsigned Mutable : 1;
2320   mutable unsigned CachedFieldIndex : 31;
2321
2322   /// The kinds of value we can store in InitializerOrBitWidth.
2323   ///
2324   /// Note that this is compatible with InClassInitStyle except for
2325   /// ISK_CapturedVLAType.
2326   enum InitStorageKind {
2327     /// If the pointer is null, there's nothing special.  Otherwise,
2328     /// this is a bitfield and the pointer is the Expr* storing the
2329     /// bit-width.
2330     ISK_BitWidthOrNothing = (unsigned) ICIS_NoInit,
2331
2332     /// The pointer is an (optional due to delayed parsing) Expr*
2333     /// holding the copy-initializer.
2334     ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
2335
2336     /// The pointer is an (optional due to delayed parsing) Expr*
2337     /// holding the list-initializer.
2338     ISK_InClassListInit = (unsigned) ICIS_ListInit,
2339
2340     /// The pointer is a VariableArrayType* that's been captured;
2341     /// the enclosing context is a lambda or captured statement.
2342     ISK_CapturedVLAType,
2343   };
2344
2345   /// \brief Storage for either the bit-width, the in-class
2346   /// initializer, or the captured variable length array bound.
2347   ///
2348   /// We can safely combine these because in-class initializers are
2349   /// not permitted for bit-fields, and both are exclusive with VLA
2350   /// captures.
2351   ///
2352   /// If the storage kind is ISK_InClassCopyInit or
2353   /// ISK_InClassListInit, but the initializer is null, then this
2354   /// field has an in-class initializer which has not yet been parsed
2355   /// and attached.
2356   llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
2357 protected:
2358   FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2359             SourceLocation IdLoc, IdentifierInfo *Id,
2360             QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2361             InClassInitStyle InitStyle)
2362     : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2363       Mutable(Mutable), CachedFieldIndex(0),
2364       InitStorage(BW, (InitStorageKind) InitStyle) {
2365     assert((!BW || InitStyle == ICIS_NoInit) && "got initializer for bitfield");
2366   }
2367
2368 public:
2369   static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2370                            SourceLocation StartLoc, SourceLocation IdLoc,
2371                            IdentifierInfo *Id, QualType T,
2372                            TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2373                            InClassInitStyle InitStyle);
2374
2375   static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2376   
2377   /// getFieldIndex - Returns the index of this field within its record,
2378   /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2379   unsigned getFieldIndex() const;
2380
2381   /// isMutable - Determines whether this field is mutable (C++ only).
2382   bool isMutable() const { return Mutable; }
2383
2384   /// \brief Determines whether this field is a bitfield.
2385   bool isBitField() const {
2386     return InitStorage.getInt() == ISK_BitWidthOrNothing &&
2387            InitStorage.getPointer() != nullptr;
2388   }
2389
2390   /// @brief Determines whether this is an unnamed bitfield.
2391   bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2392
2393   /// isAnonymousStructOrUnion - Determines whether this field is a
2394   /// representative for an anonymous struct or union. Such fields are
2395   /// unnamed and are implicitly generated by the implementation to
2396   /// store the data for the anonymous union or struct.
2397   bool isAnonymousStructOrUnion() const;
2398
2399   Expr *getBitWidth() const {
2400     return isBitField()
2401                ? static_cast<Expr *>(InitStorage.getPointer())
2402                : nullptr;
2403   }
2404   unsigned getBitWidthValue(const ASTContext &Ctx) const;
2405
2406   /// setBitWidth - Set the bit-field width for this member.
2407   // Note: used by some clients (i.e., do not remove it).
2408   void setBitWidth(Expr *Width) {
2409     assert(InitStorage.getInt() == ISK_BitWidthOrNothing &&
2410            InitStorage.getPointer() == nullptr &&
2411            "bit width, initializer or captured type already set");
2412     InitStorage.setPointerAndInt(Width, ISK_BitWidthOrNothing);
2413   }
2414
2415   /// removeBitWidth - Remove the bit-field width from this member.
2416   // Note: used by some clients (i.e., do not remove it).
2417   void removeBitWidth() {
2418     assert(isBitField() && "no bitfield width to remove");
2419     InitStorage.setPointerAndInt(nullptr, ISK_BitWidthOrNothing);
2420   }
2421
2422   /// getInClassInitStyle - Get the kind of (C++11) in-class initializer which
2423   /// this field has.
2424   InClassInitStyle getInClassInitStyle() const {
2425     InitStorageKind storageKind = InitStorage.getInt();
2426     return (storageKind == ISK_CapturedVLAType
2427               ? ICIS_NoInit : (InClassInitStyle) storageKind);
2428   }
2429
2430   /// hasInClassInitializer - Determine whether this member has a C++11 in-class
2431   /// initializer.
2432   bool hasInClassInitializer() const {
2433     return getInClassInitStyle() != ICIS_NoInit;
2434   }
2435
2436   /// getInClassInitializer - Get the C++11 in-class initializer for this
2437   /// member, or null if one has not been set. If a valid declaration has an
2438   /// in-class initializer, but this returns null, then we have not parsed and
2439   /// attached it yet.
2440   Expr *getInClassInitializer() const {
2441     return hasInClassInitializer()
2442                ? static_cast<Expr *>(InitStorage.getPointer())
2443                : nullptr;
2444   }
2445
2446   /// setInClassInitializer - Set the C++11 in-class initializer for this
2447   /// member.
2448   void setInClassInitializer(Expr *Init) {
2449     assert(hasInClassInitializer() &&
2450            InitStorage.getPointer() == nullptr &&
2451            "bit width, initializer or captured type already set");
2452     InitStorage.setPointer(Init);
2453   }
2454
2455   /// removeInClassInitializer - Remove the C++11 in-class initializer from this
2456   /// member.
2457   void removeInClassInitializer() {
2458     assert(hasInClassInitializer() && "no initializer to remove");
2459     InitStorage.setPointerAndInt(nullptr, ISK_BitWidthOrNothing);
2460   }
2461
2462   /// \brief Determine whether this member captures the variable length array
2463   /// type.
2464   bool hasCapturedVLAType() const {
2465     return InitStorage.getInt() == ISK_CapturedVLAType;
2466   }
2467
2468   /// \brief Get the captured variable length array type.
2469   const VariableArrayType *getCapturedVLAType() const {
2470     return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
2471                                       InitStorage.getPointer())
2472                                 : nullptr;
2473   }
2474   /// \brief Set the captured variable length array type for this field.
2475   void setCapturedVLAType(const VariableArrayType *VLAType);
2476
2477   /// getParent - Returns the parent of this field declaration, which
2478   /// is the struct in which this method is defined.
2479   const RecordDecl *getParent() const {
2480     return cast<RecordDecl>(getDeclContext());
2481   }
2482
2483   RecordDecl *getParent() {
2484     return cast<RecordDecl>(getDeclContext());
2485   }
2486
2487   SourceRange getSourceRange() const override LLVM_READONLY;
2488
2489   /// Retrieves the canonical declaration of this field.
2490   FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2491   const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2492
2493   // Implement isa/cast/dyncast/etc.
2494   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2495   static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2496
2497   friend class ASTDeclReader;
2498   friend class ASTDeclWriter;
2499 };
2500
2501 /// EnumConstantDecl - An instance of this object exists for each enum constant
2502 /// that is defined.  For example, in "enum X {a,b}", each of a/b are
2503 /// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2504 /// TagType for the X EnumDecl.
2505 class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> {
2506   Stmt *Init; // an integer constant expression
2507   llvm::APSInt Val; // The value.
2508 protected:
2509   EnumConstantDecl(DeclContext *DC, SourceLocation L,
2510                    IdentifierInfo *Id, QualType T, Expr *E,
2511                    const llvm::APSInt &V)
2512     : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2513
2514 public:
2515
2516   static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2517                                   SourceLocation L, IdentifierInfo *Id,
2518                                   QualType T, Expr *E,
2519                                   const llvm::APSInt &V);
2520   static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2521   
2522   const Expr *getInitExpr() const { return (const Expr*) Init; }
2523   Expr *getInitExpr() { return (Expr*) Init; }
2524   const llvm::APSInt &getInitVal() const { return Val; }
2525
2526   void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2527   void setInitVal(const llvm::APSInt &V) { Val = V; }
2528
2529   SourceRange getSourceRange() const override LLVM_READONLY;
2530
2531   /// Retrieves the canonical declaration of this enumerator.
2532   EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); }
2533   const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); }
2534
2535   // Implement isa/cast/dyncast/etc.
2536   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2537   static bool classofKind(Kind K) { return K == EnumConstant; }
2538
2539   friend class StmtIteratorBase;
2540 };
2541
2542 /// IndirectFieldDecl - An instance of this class is created to represent a
2543 /// field injected from an anonymous union/struct into the parent scope.
2544 /// IndirectFieldDecl are always implicit.
2545 class IndirectFieldDecl : public ValueDecl,
2546                           public Mergeable<IndirectFieldDecl> {
2547   void anchor() override;
2548   NamedDecl **Chaining;
2549   unsigned ChainingSize;
2550
2551   IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2552                     DeclarationName N, QualType T,
2553                     MutableArrayRef<NamedDecl *> CH);
2554
2555 public:
2556   static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2557                                    SourceLocation L, IdentifierInfo *Id,
2558                                    QualType T, llvm::MutableArrayRef<NamedDecl *> CH);
2559
2560   static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2561
2562   typedef ArrayRef<NamedDecl *>::const_iterator chain_iterator;
2563
2564   ArrayRef<NamedDecl *> chain() const {
2565     return llvm::makeArrayRef(Chaining, ChainingSize);
2566   }
2567   chain_iterator chain_begin() const { return chain().begin(); }
2568   chain_iterator chain_end() const { return chain().end(); }
2569
2570   unsigned getChainingSize() const { return ChainingSize; }
2571
2572   FieldDecl *getAnonField() const {
2573     assert(chain().size() >= 2);
2574     return cast<FieldDecl>(chain().back());
2575   }
2576
2577   VarDecl *getVarDecl() const {
2578     assert(chain().size() >= 2);
2579     return dyn_cast<VarDecl>(chain().front());
2580   }
2581
2582   IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2583   const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2584
2585   // Implement isa/cast/dyncast/etc.
2586   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2587   static bool classofKind(Kind K) { return K == IndirectField; }
2588   friend class ASTDeclReader;
2589 };
2590
2591 /// TypeDecl - Represents a declaration of a type.
2592 ///
2593 class TypeDecl : public NamedDecl {
2594   void anchor() override;
2595   /// TypeForDecl - This indicates the Type object that represents
2596   /// this TypeDecl.  It is a cache maintained by
2597   /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
2598   /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
2599   mutable const Type *TypeForDecl;
2600   /// LocStart - The start of the source range for this declaration.
2601   SourceLocation LocStart;
2602   friend class ASTContext;
2603
2604 protected:
2605   TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2606            SourceLocation StartL = SourceLocation())
2607     : NamedDecl(DK, DC, L, Id), TypeForDecl(nullptr), LocStart(StartL) {}
2608
2609 public:
2610   // Low-level accessor. If you just want the type defined by this node,
2611   // check out ASTContext::getTypeDeclType or one of
2612   // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
2613   // already know the specific kind of node this is.
2614   const Type *getTypeForDecl() const { return TypeForDecl; }
2615   void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
2616
2617   SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
2618   void setLocStart(SourceLocation L) { LocStart = L; }
2619   SourceRange getSourceRange() const override LLVM_READONLY {
2620     if (LocStart.isValid())
2621       return SourceRange(LocStart, getLocation());
2622     else
2623       return SourceRange(getLocation());
2624   }
2625
2626   // Implement isa/cast/dyncast/etc.
2627   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2628   static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
2629 };
2630
2631
2632 /// Base class for declarations which introduce a typedef-name.
2633 class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
2634   void anchor() override;
2635   typedef std::pair<TypeSourceInfo*, QualType> ModedTInfo;
2636   llvm::PointerUnion<TypeSourceInfo*, ModedTInfo*> MaybeModedTInfo;
2637
2638 protected:
2639   TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC,
2640                   SourceLocation StartLoc, SourceLocation IdLoc,
2641                   IdentifierInfo *Id, TypeSourceInfo *TInfo)
2642       : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
2643         MaybeModedTInfo(TInfo) {}
2644
2645   typedef Redeclarable<TypedefNameDecl> redeclarable_base;
2646   TypedefNameDecl *getNextRedeclarationImpl() override {
2647     return getNextRedeclaration();
2648   }
2649   TypedefNameDecl *getPreviousDeclImpl() override {
2650     return getPreviousDecl();
2651   }
2652   TypedefNameDecl *getMostRecentDeclImpl() override {
2653     return getMostRecentDecl();
2654   }
2655
2656 public:
2657   typedef redeclarable_base::redecl_range redecl_range;
2658   typedef redeclarable_base::redecl_iterator redecl_iterator;
2659   using redeclarable_base::redecls_begin;
2660   using redeclarable_base::redecls_end;
2661   using redeclarable_base::redecls;
2662   using redeclarable_base::getPreviousDecl;
2663   using redeclarable_base::getMostRecentDecl;
2664   using redeclarable_base::isFirstDecl;
2665
2666   bool isModed() const { return MaybeModedTInfo.is<ModedTInfo*>(); }
2667
2668   TypeSourceInfo *getTypeSourceInfo() const {
2669     return isModed()
2670       ? MaybeModedTInfo.get<ModedTInfo*>()->first
2671       : MaybeModedTInfo.get<TypeSourceInfo*>();
2672   }
2673   QualType getUnderlyingType() const {
2674     return isModed()
2675       ? MaybeModedTInfo.get<ModedTInfo*>()->second
2676       : MaybeModedTInfo.get<TypeSourceInfo*>()->getType();
2677   }
2678   void setTypeSourceInfo(TypeSourceInfo *newType) {
2679     MaybeModedTInfo = newType;
2680   }
2681   void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
2682     MaybeModedTInfo = new (getASTContext()) ModedTInfo(unmodedTSI, modedTy);
2683   }
2684
2685   /// Retrieves the canonical declaration of this typedef-name.
2686   TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); }
2687   const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); }
2688
2689   /// Retrieves the tag declaration for which this is the typedef name for
2690   /// linkage purposes, if any.
2691   ///
2692   /// \param AnyRedecl Look for the tag declaration in any redeclaration of
2693   /// this typedef declaration.
2694   TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const;
2695
2696   // Implement isa/cast/dyncast/etc.
2697   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2698   static bool classofKind(Kind K) {
2699     return K >= firstTypedefName && K <= lastTypedefName;
2700   }
2701 };
2702
2703 /// TypedefDecl - Represents the declaration of a typedef-name via the 'typedef'
2704 /// type specifier.
2705 class TypedefDecl : public TypedefNameDecl {
2706   TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2707               SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
2708       : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {}
2709
2710 public:
2711   static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
2712                              SourceLocation StartLoc, SourceLocation IdLoc,
2713                              IdentifierInfo *Id, TypeSourceInfo *TInfo);
2714   static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2715
2716   SourceRange getSourceRange() const override LLVM_READONLY;
2717
2718   // Implement isa/cast/dyncast/etc.
2719   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2720   static bool classofKind(Kind K) { return K == Typedef; }
2721 };
2722
2723 /// TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x
2724 /// alias-declaration.
2725 class TypeAliasDecl : public TypedefNameDecl {
2726   /// The template for which this is the pattern, if any.
2727   TypeAliasTemplateDecl *Template;
2728
2729   TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2730                 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
2731       : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
2732         Template(nullptr) {}
2733
2734 public:
2735   static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
2736                                SourceLocation StartLoc, SourceLocation IdLoc,
2737                                IdentifierInfo *Id, TypeSourceInfo *TInfo);
2738   static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2739
2740   SourceRange getSourceRange() const override LLVM_READONLY;
2741
2742   TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; }
2743   void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; }
2744
2745   // Implement isa/cast/dyncast/etc.
2746   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2747   static bool classofKind(Kind K) { return K == TypeAlias; }
2748 };
2749
2750 /// TagDecl - Represents the declaration of a struct/union/class/enum.
2751 class TagDecl
2752   : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
2753 public:
2754   // This is really ugly.
2755   typedef TagTypeKind TagKind;
2756
2757 private:
2758   // FIXME: This can be packed into the bitfields in Decl.
2759   /// TagDeclKind - The TagKind enum.
2760   unsigned TagDeclKind : 3;
2761
2762   /// IsCompleteDefinition - True if this is a definition ("struct foo
2763   /// {};"), false if it is a declaration ("struct foo;").  It is not
2764   /// a definition until the definition has been fully processed.
2765   unsigned IsCompleteDefinition : 1;
2766
2767 protected:
2768   /// IsBeingDefined - True if this is currently being defined.
2769   unsigned IsBeingDefined : 1;
2770
2771 private:
2772   /// IsEmbeddedInDeclarator - True if this tag declaration is
2773   /// "embedded" (i.e., defined or declared for the very first time)
2774   /// in the syntax of a declarator.
2775   unsigned IsEmbeddedInDeclarator : 1;
2776
2777   /// \brief True if this tag is free standing, e.g. "struct foo;".
2778   unsigned IsFreeStanding : 1;
2779
2780 protected:
2781   // These are used by (and only defined for) EnumDecl.
2782   unsigned NumPositiveBits : 8;
2783   unsigned NumNegativeBits : 8;
2784
2785   /// IsScoped - True if this tag declaration is a scoped enumeration. Only
2786   /// possible in C++11 mode.
2787   unsigned IsScoped : 1;
2788   /// IsScopedUsingClassTag - If this tag declaration is a scoped enum,
2789   /// then this is true if the scoped enum was declared using the class
2790   /// tag, false if it was declared with the struct tag. No meaning is
2791   /// associated if this tag declaration is not a scoped enum.
2792   unsigned IsScopedUsingClassTag : 1;
2793
2794   /// IsFixed - True if this is an enumeration with fixed underlying type. Only
2795   /// possible in C++11, Microsoft extensions, or Objective C mode.
2796   unsigned IsFixed : 1;
2797
2798   /// \brief Indicates whether it is possible for declarations of this kind
2799   /// to have an out-of-date definition.
2800   ///
2801   /// This option is only enabled when modules are enabled.
2802   unsigned MayHaveOutOfDateDef : 1;
2803
2804   /// Has the full definition of this type been required by a use somewhere in
2805   /// the TU.
2806   unsigned IsCompleteDefinitionRequired : 1;
2807 private:
2808   SourceRange BraceRange;
2809
2810   // A struct representing syntactic qualifier info,
2811   // to be used for the (uncommon) case of out-of-line declarations.
2812   typedef QualifierInfo ExtInfo;
2813
2814   /// \brief If the (out-of-line) tag declaration name
2815   /// is qualified, it points to the qualifier info (nns and range);
2816   /// otherwise, if the tag declaration is anonymous and it is part of
2817   /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
2818   /// otherwise, if the tag declaration is anonymous and it is used as a
2819   /// declaration specifier for variables, it points to the first VarDecl (used
2820   /// for mangling);
2821   /// otherwise, it is a null (TypedefNameDecl) pointer.
2822   llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier;
2823
2824   bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); }
2825   ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); }
2826   const ExtInfo *getExtInfo() const {
2827     return TypedefNameDeclOrQualifier.get<ExtInfo *>();
2828   }
2829
2830 protected:
2831   TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
2832           SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
2833           SourceLocation StartL)
2834       : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
2835         TagDeclKind(TK), IsCompleteDefinition(false), IsBeingDefined(false),
2836         IsEmbeddedInDeclarator(false), IsFreeStanding(false),
2837         IsCompleteDefinitionRequired(false),
2838         TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
2839     assert((DK != Enum || TK == TTK_Enum) &&
2840            "EnumDecl not matched with TTK_Enum");
2841     setPreviousDecl(PrevDecl);
2842   }
2843
2844   typedef Redeclarable<TagDecl> redeclarable_base;
2845   TagDecl *getNextRedeclarationImpl() override {
2846     return getNextRedeclaration();
2847   }
2848   TagDecl *getPreviousDeclImpl() override {
2849     return getPreviousDecl();
2850   }
2851   TagDecl *getMostRecentDeclImpl() override {
2852     return getMostRecentDecl();
2853   }
2854
2855   /// @brief Completes the definition of this tag declaration.
2856   ///
2857   /// This is a helper function for derived classes.
2858   void completeDefinition();
2859
2860 public:
2861   typedef redeclarable_base::redecl_range redecl_range;
2862   typedef redeclarable_base::redecl_iterator redecl_iterator;
2863   using redeclarable_base::redecls_begin;
2864   using redeclarable_base::redecls_end;
2865   using redeclarable_base::redecls;
2866   using redeclarable_base::getPreviousDecl;
2867   using redeclarable_base::getMostRecentDecl;
2868   using redeclarable_base::isFirstDecl;
2869
2870   SourceRange getBraceRange() const { return BraceRange; }
2871   void setBraceRange(SourceRange R) { BraceRange = R; }
2872
2873   /// getInnerLocStart - Return SourceLocation representing start of source
2874   /// range ignoring outer template declarations.
2875   SourceLocation getInnerLocStart() const { return getLocStart(); }
2876
2877   /// getOuterLocStart - Return SourceLocation representing start of source
2878   /// range taking into account any outer template declarations.
2879   SourceLocation getOuterLocStart() const;
2880   SourceRange getSourceRange() const override LLVM_READONLY;
2881
2882   TagDecl *getCanonicalDecl() override;
2883   const TagDecl *getCanonicalDecl() const {
2884     return const_cast<TagDecl*>(this)->getCanonicalDecl();
2885   }
2886
2887   /// isThisDeclarationADefinition() - Return true if this declaration
2888   /// is a completion definition of the type.  Provided for consistency.
2889   bool isThisDeclarationADefinition() const {
2890     return isCompleteDefinition();
2891   }
2892
2893   /// isCompleteDefinition - Return true if this decl has its body
2894   /// fully specified.
2895   bool isCompleteDefinition() const {
2896     return IsCompleteDefinition;
2897   }
2898
2899   /// \brief Return true if this complete decl is
2900   /// required to be complete for some existing use.
2901   bool isCompleteDefinitionRequired() const {
2902     return IsCompleteDefinitionRequired;
2903   }
2904
2905   /// isBeingDefined - Return true if this decl is currently being defined.
2906   bool isBeingDefined() const {
2907     return IsBeingDefined;
2908   }
2909
2910   bool isEmbeddedInDeclarator() const {
2911     return IsEmbeddedInDeclarator;
2912   }
2913   void setEmbeddedInDeclarator(bool isInDeclarator) {
2914     IsEmbeddedInDeclarator = isInDeclarator;
2915   }
2916
2917   bool isFreeStanding() const { return IsFreeStanding; }
2918   void setFreeStanding(bool isFreeStanding = true) {
2919     IsFreeStanding = isFreeStanding;
2920   }
2921
2922   /// \brief Whether this declaration declares a type that is
2923   /// dependent, i.e., a type that somehow depends on template
2924   /// parameters.
2925   bool isDependentType() const { return isDependentContext(); }
2926
2927   /// @brief Starts the definition of this tag declaration.
2928   ///
2929   /// This method should be invoked at the beginning of the definition
2930   /// of this tag declaration. It will set the tag type into a state
2931   /// where it is in the process of being defined.
2932   void startDefinition();
2933
2934   /// getDefinition - Returns the TagDecl that actually defines this
2935   ///  struct/union/class/enum.  When determining whether or not a
2936   ///  struct/union/class/enum has a definition, one should use this
2937   ///  method as opposed to 'isDefinition'.  'isDefinition' indicates
2938   ///  whether or not a specific TagDecl is defining declaration, not
2939   ///  whether or not the struct/union/class/enum type is defined.
2940   ///  This method returns NULL if there is no TagDecl that defines
2941   ///  the struct/union/class/enum.
2942   TagDecl *getDefinition() const;
2943
2944   void setCompleteDefinition(bool V) { IsCompleteDefinition = V; }
2945
2946   void setCompleteDefinitionRequired(bool V = true) {
2947     IsCompleteDefinitionRequired = V;
2948   }
2949
2950   StringRef getKindName() const {
2951     return TypeWithKeyword::getTagTypeKindName(getTagKind());
2952   }
2953
2954   TagKind getTagKind() const {
2955     return TagKind(TagDeclKind);
2956   }
2957
2958   void setTagKind(TagKind TK) { TagDeclKind = TK; }
2959
2960   bool isStruct() const { return getTagKind() == TTK_Struct; }
2961   bool isInterface() const { return getTagKind() == TTK_Interface; }
2962   bool isClass()  const { return getTagKind() == TTK_Class; }
2963   bool isUnion()  const { return getTagKind() == TTK_Union; }
2964   bool isEnum()   const { return getTagKind() == TTK_Enum; }
2965
2966   /// Is this tag type named, either directly or via being defined in
2967   /// a typedef of this type?
2968   ///
2969   /// C++11 [basic.link]p8:
2970   ///   A type is said to have linkage if and only if:
2971   ///     - it is a class or enumeration type that is named (or has a
2972   ///       name for linkage purposes) and the name has linkage; ...
2973   /// C++11 [dcl.typedef]p9:
2974   ///   If the typedef declaration defines an unnamed class (or enum),
2975   ///   the first typedef-name declared by the declaration to be that
2976   ///   class type (or enum type) is used to denote the class type (or
2977   ///   enum type) for linkage purposes only.
2978   ///
2979   /// C does not have an analogous rule, but the same concept is
2980   /// nonetheless useful in some places.
2981   bool hasNameForLinkage() const {
2982     return (getDeclName() || getTypedefNameForAnonDecl());
2983   }
2984
2985   TypedefNameDecl *getTypedefNameForAnonDecl() const {
2986     return hasExtInfo() ? nullptr
2987                         : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>();
2988   }
2989
2990   void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
2991
2992   /// \brief Retrieve the nested-name-specifier that qualifies the name of this
2993   /// declaration, if it was present in the source.
2994   NestedNameSpecifier *getQualifier() const {
2995     return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
2996                         : nullptr;
2997   }
2998
2999   /// \brief Retrieve the nested-name-specifier (with source-location
3000   /// information) that qualifies the name of this declaration, if it was
3001   /// present in the source.
3002   NestedNameSpecifierLoc getQualifierLoc() const {
3003     return hasExtInfo() ? getExtInfo()->QualifierLoc
3004                         : NestedNameSpecifierLoc();
3005   }
3006
3007   void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
3008
3009   unsigned getNumTemplateParameterLists() const {
3010     return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
3011   }
3012   TemplateParameterList *getTemplateParameterList(unsigned i) const {
3013     assert(i < getNumTemplateParameterLists());
3014     return getExtInfo()->TemplParamLists[i];
3015   }
3016   void setTemplateParameterListsInfo(ASTContext &Context,
3017                                      ArrayRef<TemplateParameterList *> TPLists);
3018
3019   // Implement isa/cast/dyncast/etc.
3020   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3021   static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
3022
3023   static DeclContext *castToDeclContext(const TagDecl *D) {
3024     return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
3025   }
3026   static TagDecl *castFromDeclContext(const DeclContext *DC) {
3027     return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
3028   }
3029
3030   friend class ASTDeclReader;
3031   friend class ASTDeclWriter;
3032 };
3033
3034 /// EnumDecl - Represents an enum.  In C++11, enums can be forward-declared
3035 /// with a fixed underlying type, and in C we allow them to be forward-declared
3036 /// with no underlying type as an extension.
3037 class EnumDecl : public TagDecl {
3038   void anchor() override;
3039   /// IntegerType - This represent the integer type that the enum corresponds
3040   /// to for code generation purposes.  Note that the enumerator constants may
3041   /// have a different type than this does.
3042   ///
3043   /// If the underlying integer type was explicitly stated in the source
3044   /// code, this is a TypeSourceInfo* for that type. Otherwise this type
3045   /// was automatically deduced somehow, and this is a Type*.
3046   ///
3047   /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
3048   /// some cases it won't.
3049   ///
3050   /// The underlying type of an enumeration never has any qualifiers, so
3051   /// we can get away with just storing a raw Type*, and thus save an
3052   /// extra pointer when TypeSourceInfo is needed.
3053
3054   llvm::PointerUnion<const Type*, TypeSourceInfo*> IntegerType;
3055
3056   /// PromotionType - The integer type that values of this type should
3057   /// promote to.  In C, enumerators are generally of an integer type
3058   /// directly, but gcc-style large enumerators (and all enumerators
3059   /// in C++) are of the enum type instead.
3060   QualType PromotionType;
3061
3062   /// \brief If this enumeration is an instantiation of a member enumeration
3063   /// of a class template specialization, this is the member specialization
3064   /// information.
3065   MemberSpecializationInfo *SpecializationInfo;
3066
3067   EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3068            SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
3069            bool Scoped, bool ScopedUsingClassTag, bool Fixed)
3070       : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc),
3071         SpecializationInfo(nullptr) {
3072     assert(Scoped || !ScopedUsingClassTag);
3073     IntegerType = (const Type *)nullptr;
3074     NumNegativeBits = 0;
3075     NumPositiveBits = 0;
3076     IsScoped = Scoped;
3077     IsScopedUsingClassTag = ScopedUsingClassTag;
3078     IsFixed = Fixed;
3079   }
3080
3081   void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3082                                     TemplateSpecializationKind TSK);
3083 public:
3084   EnumDecl *getCanonicalDecl() override {
3085     return cast<EnumDecl>(TagDecl::getCanonicalDecl());
3086   }
3087   const EnumDecl *getCanonicalDecl() const {
3088     return const_cast<EnumDecl*>(this)->getCanonicalDecl();
3089   }
3090
3091   EnumDecl *getPreviousDecl() {
3092     return cast_or_null<EnumDecl>(
3093             static_cast<TagDecl *>(this)->getPreviousDecl());
3094   }
3095   const EnumDecl *getPreviousDecl() const {
3096     return const_cast<EnumDecl*>(this)->getPreviousDecl();
3097   }
3098
3099   EnumDecl *getMostRecentDecl() {
3100     return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3101   }
3102   const EnumDecl *getMostRecentDecl() const {
3103     return const_cast<EnumDecl*>(this)->getMostRecentDecl();
3104   }
3105
3106   EnumDecl *getDefinition() const {
3107     return cast_or_null<EnumDecl>(TagDecl::getDefinition());
3108   }
3109
3110   static EnumDecl *Create(ASTContext &C, DeclContext *DC,
3111                           SourceLocation StartLoc, SourceLocation IdLoc,
3112                           IdentifierInfo *Id, EnumDecl *PrevDecl,
3113                           bool IsScoped, bool IsScopedUsingClassTag,
3114                           bool IsFixed);
3115   static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3116
3117   /// completeDefinition - When created, the EnumDecl corresponds to a
3118   /// forward-declared enum. This method is used to mark the
3119   /// declaration as being defined; it's enumerators have already been
3120   /// added (via DeclContext::addDecl). NewType is the new underlying
3121   /// type of the enumeration type.
3122   void completeDefinition(QualType NewType,
3123                           QualType PromotionType,
3124                           unsigned NumPositiveBits,
3125                           unsigned NumNegativeBits);
3126
3127   // enumerator_iterator - Iterates through the enumerators of this
3128   // enumeration.
3129   typedef specific_decl_iterator<EnumConstantDecl> enumerator_iterator;
3130   typedef llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>
3131     enumerator_range;
3132
3133   enumerator_range enumerators() const {
3134     return enumerator_range(enumerator_begin(), enumerator_end());
3135   }
3136
3137   enumerator_iterator enumerator_begin() const {
3138     const EnumDecl *E = getDefinition();
3139     if (!E)
3140       E = this;
3141     return enumerator_iterator(E->decls_begin());
3142   }
3143
3144   enumerator_iterator enumerator_end() const {
3145     const EnumDecl *E = getDefinition();
3146     if (!E)
3147       E = this;
3148     return enumerator_iterator(E->decls_end());
3149   }
3150
3151   /// getPromotionType - Return the integer type that enumerators
3152   /// should promote to.
3153   QualType getPromotionType() const { return PromotionType; }
3154
3155   /// \brief Set the promotion type.
3156   void setPromotionType(QualType T) { PromotionType = T; }
3157
3158   /// getIntegerType - Return the integer type this enum decl corresponds to.
3159   /// This returns a null QualType for an enum forward definition with no fixed
3160   /// underlying type.
3161   QualType getIntegerType() const {
3162     if (!IntegerType)
3163       return QualType();
3164     if (const Type *T = IntegerType.dyn_cast<const Type*>())
3165       return QualType(T, 0);
3166     return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType();
3167   }
3168
3169   /// \brief Set the underlying integer type.
3170   void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
3171
3172   /// \brief Set the underlying integer type source info.
3173   void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; }
3174
3175   /// \brief Return the type source info for the underlying integer type,
3176   /// if no type source info exists, return 0.
3177   TypeSourceInfo *getIntegerTypeSourceInfo() const {
3178     return IntegerType.dyn_cast<TypeSourceInfo*>();
3179   }
3180
3181   /// \brief Retrieve the source range that covers the underlying type if
3182   /// specified.
3183   SourceRange getIntegerTypeRange() const LLVM_READONLY;
3184
3185   /// \brief Returns the width in bits required to store all the
3186   /// non-negative enumerators of this enum.
3187   unsigned getNumPositiveBits() const {
3188     return NumPositiveBits;
3189   }
3190   void setNumPositiveBits(unsigned Num) {
3191     NumPositiveBits = Num;
3192     assert(NumPositiveBits == Num && "can't store this bitcount");
3193   }
3194
3195   /// \brief Returns the width in bits required to store all the
3196   /// negative enumerators of this enum.  These widths include
3197   /// the rightmost leading 1;  that is:
3198   ///
3199   /// MOST NEGATIVE ENUMERATOR     PATTERN     NUM NEGATIVE BITS
3200   /// ------------------------     -------     -----------------
3201   ///                       -1     1111111                     1
3202   ///                      -10     1110110                     5
3203   ///                     -101     1001011                     8
3204   unsigned getNumNegativeBits() const {
3205     return NumNegativeBits;
3206   }
3207   void setNumNegativeBits(unsigned Num) {
3208     NumNegativeBits = Num;
3209   }
3210
3211   /// \brief Returns true if this is a C++11 scoped enumeration.
3212   bool isScoped() const {
3213     return IsScoped;
3214   }
3215
3216   /// \brief Returns true if this is a C++11 scoped enumeration.
3217   bool isScopedUsingClassTag() const {
3218     return IsScopedUsingClassTag;
3219   }
3220
3221   /// \brief Returns true if this is an Objective-C, C++11, or
3222   /// Microsoft-style enumeration with a fixed underlying type.
3223   bool isFixed() const {
3224     return IsFixed;
3225   }
3226
3227   /// \brief Returns true if this can be considered a complete type.
3228   bool isComplete() const {
3229     return isCompleteDefinition() || isFixed();
3230   }
3231
3232   /// \brief Retrieve the enum definition from which this enumeration could
3233   /// be instantiated, if it is an instantiation (rather than a non-template).
3234   EnumDecl *getTemplateInstantiationPattern() const;
3235
3236   /// \brief Returns the enumeration (declared within the template)
3237   /// from which this enumeration type was instantiated, or NULL if
3238   /// this enumeration was not instantiated from any template.
3239   EnumDecl *getInstantiatedFromMemberEnum() const;
3240
3241   /// \brief If this enumeration is a member of a specialization of a
3242   /// templated class, determine what kind of template specialization
3243   /// or instantiation this is.
3244   TemplateSpecializationKind getTemplateSpecializationKind() const;
3245
3246   /// \brief For an enumeration member that was instantiated from a member
3247   /// enumeration of a templated class, set the template specialiation kind.
3248   void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3249                         SourceLocation PointOfInstantiation = SourceLocation());
3250
3251   /// \brief If this enumeration is an instantiation of a member enumeration of
3252   /// a class template specialization, retrieves the member specialization
3253   /// information.
3254   MemberSpecializationInfo *getMemberSpecializationInfo() const {
3255     return SpecializationInfo;
3256   }
3257
3258   /// \brief Specify that this enumeration is an instantiation of the
3259   /// member enumeration ED.
3260   void setInstantiationOfMemberEnum(EnumDecl *ED,
3261                                     TemplateSpecializationKind TSK) {
3262     setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
3263   }
3264
3265   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3266   static bool classofKind(Kind K) { return K == Enum; }
3267
3268   friend class ASTDeclReader;
3269 };
3270
3271
3272 /// RecordDecl - Represents a struct/union/class.  For example:
3273 ///   struct X;                  // Forward declaration, no "body".
3274 ///   union Y { int A, B; };     // Has body with members A and B (FieldDecls).
3275 /// This decl will be marked invalid if *any* members are invalid.
3276 ///
3277 class RecordDecl : public TagDecl {
3278   // FIXME: This can be packed into the bitfields in Decl.
3279   /// HasFlexibleArrayMember - This is true if this struct ends with a flexible
3280   /// array member (e.g. int X[]) or if this union contains a struct that does.
3281   /// If so, this cannot be contained in arrays or other structs as a member.
3282   bool HasFlexibleArrayMember : 1;
3283
3284   /// AnonymousStructOrUnion - Whether this is the type of an anonymous struct
3285   /// or union.
3286   bool AnonymousStructOrUnion : 1;
3287
3288   /// HasObjectMember - This is true if this struct has at least one member
3289   /// containing an Objective-C object pointer type.
3290   bool HasObjectMember : 1;
3291   
3292   /// HasVolatileMember - This is true if struct has at least one member of
3293   /// 'volatile' type.
3294   bool HasVolatileMember : 1;
3295
3296   /// \brief Whether the field declarations of this record have been loaded
3297   /// from external storage. To avoid unnecessary deserialization of
3298   /// methods/nested types we allow deserialization of just the fields
3299   /// when needed.
3300   mutable bool LoadedFieldsFromExternalStorage : 1;
3301   friend class DeclContext;
3302
3303 protected:
3304   RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3305              SourceLocation StartLoc, SourceLocation IdLoc,
3306              IdentifierInfo *Id, RecordDecl *PrevDecl);
3307
3308 public:
3309   static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3310                             SourceLocation StartLoc, SourceLocation IdLoc,
3311                             IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr);
3312   static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
3313
3314   RecordDecl *getPreviousDecl() {
3315     return cast_or_null<RecordDecl>(
3316             static_cast<TagDecl *>(this)->getPreviousDecl());
3317   }
3318   const RecordDecl *getPreviousDecl() const {
3319     return const_cast<RecordDecl*>(this)->getPreviousDecl();
3320   }
3321
3322   RecordDecl *getMostRecentDecl() {
3323     return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3324   }
3325   const RecordDecl *getMostRecentDecl() const {
3326     return const_cast<RecordDecl*>(this)->getMostRecentDecl();
3327   }
3328
3329   bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
3330   void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
3331
3332   /// isAnonymousStructOrUnion - Whether this is an anonymous struct
3333   /// or union. To be an anonymous struct or union, it must have been
3334   /// declared without a name and there must be no objects of this
3335   /// type declared, e.g.,
3336   /// @code
3337   ///   union { int i; float f; };
3338   /// @endcode
3339   /// is an anonymous union but neither of the following are:
3340   /// @code
3341   ///  union X { int i; float f; };
3342   ///  union { int i; float f; } obj;
3343   /// @endcode
3344   bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
3345   void setAnonymousStructOrUnion(bool Anon) {
3346     AnonymousStructOrUnion = Anon;
3347   }
3348
3349   bool hasObjectMember() const { return HasObjectMember; }
3350   void setHasObjectMember (bool val) { HasObjectMember = val; }
3351
3352   bool hasVolatileMember() const { return HasVolatileMember; }
3353   void setHasVolatileMember (bool val) { HasVolatileMember = val; }
3354
3355   bool hasLoadedFieldsFromExternalStorage() const {
3356     return LoadedFieldsFromExternalStorage;
3357   }
3358   void setHasLoadedFieldsFromExternalStorage(bool val) {
3359     LoadedFieldsFromExternalStorage = val;
3360   }
3361
3362   /// \brief Determines whether this declaration represents the
3363   /// injected class name.
3364   ///
3365   /// The injected class name in C++ is the name of the class that
3366   /// appears inside the class itself. For example:
3367   ///
3368   /// \code
3369   /// struct C {
3370   ///   // C is implicitly declared here as a synonym for the class name.
3371   /// };
3372   ///
3373   /// C::C c; // same as "C c;"
3374   /// \endcode
3375   bool isInjectedClassName() const;
3376
3377   /// \brief Determine whether this record is a class describing a lambda
3378   /// function object.
3379   bool isLambda() const;
3380
3381   /// \brief Determine whether this record is a record for captured variables in
3382   /// CapturedStmt construct.
3383   bool isCapturedRecord() const;
3384   /// \brief Mark the record as a record for captured variables in CapturedStmt
3385   /// construct.
3386   void setCapturedRecord();
3387
3388   /// getDefinition - Returns the RecordDecl that actually defines
3389   ///  this struct/union/class.  When determining whether or not a
3390   ///  struct/union/class is completely defined, one should use this
3391   ///  method as opposed to 'isCompleteDefinition'.
3392   ///  'isCompleteDefinition' indicates whether or not a specific
3393   ///  RecordDecl is a completed definition, not whether or not the
3394   ///  record type is defined.  This method returns NULL if there is
3395   ///  no RecordDecl that defines the struct/union/tag.
3396   RecordDecl *getDefinition() const {
3397     return cast_or_null<RecordDecl>(TagDecl::getDefinition());
3398   }
3399
3400   // Iterator access to field members. The field iterator only visits
3401   // the non-static data members of this class, ignoring any static
3402   // data members, functions, constructors, destructors, etc.
3403   typedef specific_decl_iterator<FieldDecl> field_iterator;
3404   typedef llvm::iterator_range<specific_decl_iterator<FieldDecl>> field_range;
3405
3406   field_range fields() const { return field_range(field_begin(), field_end()); }
3407   field_iterator field_begin() const;
3408
3409   field_iterator field_end() const {
3410     return field_iterator(decl_iterator());
3411   }
3412
3413   // field_empty - Whether there are any fields (non-static data
3414   // members) in this record.
3415   bool field_empty() const {
3416     return field_begin() == field_end();
3417   }
3418
3419   /// completeDefinition - Notes that the definition of this type is
3420   /// now complete.
3421   virtual void completeDefinition();
3422
3423   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3424   static bool classofKind(Kind K) {
3425     return K >= firstRecord && K <= lastRecord;
3426   }
3427
3428   /// isMsStrust - Get whether or not this is an ms_struct which can
3429   /// be turned on with an attribute, pragma, or -mms-bitfields
3430   /// commandline option.
3431   bool isMsStruct(const ASTContext &C) const;
3432
3433   /// \brief Whether we are allowed to insert extra padding between fields.
3434   /// These padding are added to help AddressSanitizer detect
3435   /// intra-object-overflow bugs.
3436   bool mayInsertExtraPadding(bool EmitRemark = false) const;
3437
3438   /// Finds the first data member which has a name.
3439   /// nullptr is returned if no named data member exists.
3440   const FieldDecl *findFirstNamedDataMember() const;  
3441
3442 private:
3443   /// \brief Deserialize just the fields.
3444   void LoadFieldsFromExternalStorage() const;
3445 };
3446
3447 class FileScopeAsmDecl : public Decl {
3448   virtual void anchor();
3449   StringLiteral *AsmString;
3450   SourceLocation RParenLoc;
3451   FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
3452                    SourceLocation StartL, SourceLocation EndL)
3453     : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
3454 public:
3455   static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
3456                                   StringLiteral *Str, SourceLocation AsmLoc,
3457                                   SourceLocation RParenLoc);
3458
3459   static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3460   
3461   SourceLocation getAsmLoc() const { return getLocation(); }
3462   SourceLocation getRParenLoc() const { return RParenLoc; }
3463   void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3464   SourceRange getSourceRange() const override LLVM_READONLY {
3465     return SourceRange(getAsmLoc(), getRParenLoc());
3466   }
3467
3468   const StringLiteral *getAsmString() const { return AsmString; }
3469   StringLiteral *getAsmString() { return AsmString; }
3470   void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
3471
3472   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3473   static bool classofKind(Kind K) { return K == FileScopeAsm; }
3474 };
3475
3476 /// BlockDecl - This represents a block literal declaration, which is like an
3477 /// unnamed FunctionDecl.  For example:
3478 /// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
3479 ///
3480 class BlockDecl : public Decl, public DeclContext {
3481 public:
3482   /// A class which contains all the information about a particular
3483   /// captured value.
3484   class Capture {
3485     enum {
3486       flag_isByRef = 0x1,
3487       flag_isNested = 0x2
3488     };
3489
3490     /// The variable being captured.
3491     llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
3492
3493     /// The copy expression, expressed in terms of a DeclRef (or
3494     /// BlockDeclRef) to the captured variable.  Only required if the
3495     /// variable has a C++ class type.
3496     Expr *CopyExpr;
3497
3498   public:
3499     Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
3500       : VariableAndFlags(variable,
3501                   (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
3502         CopyExpr(copy) {}
3503
3504     /// The variable being captured.
3505     VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
3506
3507     /// Whether this is a "by ref" capture, i.e. a capture of a __block
3508     /// variable.
3509     bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
3510
3511     /// Whether this is a nested capture, i.e. the variable captured
3512     /// is not from outside the immediately enclosing function/block.
3513     bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
3514
3515     bool hasCopyExpr() const { return CopyExpr != nullptr; }
3516     Expr *getCopyExpr() const { return CopyExpr; }
3517     void setCopyExpr(Expr *e) { CopyExpr = e; }
3518   };
3519
3520 private:
3521   // FIXME: This can be packed into the bitfields in Decl.
3522   bool IsVariadic : 1;
3523   bool CapturesCXXThis : 1;
3524   bool BlockMissingReturnType : 1;
3525   bool IsConversionFromLambda : 1;
3526   /// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal
3527   /// parameters of this function.  This is null if a prototype or if there are
3528   /// no formals.
3529   ParmVarDecl **ParamInfo;
3530   unsigned NumParams;
3531
3532   Stmt *Body;
3533   TypeSourceInfo *SignatureAsWritten;
3534
3535   const Capture *Captures;
3536   unsigned NumCaptures;
3537
3538   unsigned ManglingNumber;
3539   Decl *ManglingContextDecl;
3540
3541 protected:
3542   BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
3543     : Decl(Block, DC, CaretLoc), DeclContext(Block),
3544       IsVariadic(false), CapturesCXXThis(false),
3545       BlockMissingReturnType(true), IsConversionFromLambda(false),
3546       ParamInfo(nullptr), NumParams(0), Body(nullptr),
3547       SignatureAsWritten(nullptr), Captures(nullptr), NumCaptures(0),
3548       ManglingNumber(0), ManglingContextDecl(nullptr) {}
3549
3550 public:
3551   static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L); 
3552   static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3553   
3554   SourceLocation getCaretLocation() const { return getLocation(); }
3555
3556   bool isVariadic() const { return IsVariadic; }
3557   void setIsVariadic(bool value) { IsVariadic = value; }
3558
3559   CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
3560   Stmt *getBody() const override { return (Stmt*) Body; }
3561   void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
3562
3563   void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
3564   TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
3565
3566   // ArrayRef access to formal parameters.
3567   ArrayRef<ParmVarDecl *> parameters() const {
3568     return {ParamInfo, getNumParams()};
3569   }
3570   MutableArrayRef<ParmVarDecl *> parameters() {
3571     return {ParamInfo, getNumParams()};
3572   }
3573
3574   // Iterator access to formal parameters.
3575   typedef MutableArrayRef<ParmVarDecl *>::iterator param_iterator;
3576   typedef ArrayRef<ParmVarDecl *>::const_iterator param_const_iterator;
3577   bool param_empty() const { return parameters().empty(); }
3578   param_iterator param_begin() { return parameters().begin(); }
3579   param_iterator param_end() { return parameters().end(); }
3580   param_const_iterator param_begin() const { return parameters().begin(); }
3581   param_const_iterator param_end() const { return parameters().end(); }
3582   size_t param_size() const { return parameters().size(); }
3583
3584   unsigned getNumParams() const { return NumParams; }
3585   const ParmVarDecl *getParamDecl(unsigned i) const {
3586     assert(i < getNumParams() && "Illegal param #");
3587     return ParamInfo[i];
3588   }
3589   ParmVarDecl *getParamDecl(unsigned i) {
3590     assert(i < getNumParams() && "Illegal param #");
3591     return ParamInfo[i];
3592   }
3593   void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
3594
3595   /// hasCaptures - True if this block (or its nested blocks) captures
3596   /// anything of local storage from its enclosing scopes.
3597   bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; }
3598
3599   /// getNumCaptures - Returns the number of captured variables.
3600   /// Does not include an entry for 'this'.
3601   unsigned getNumCaptures() const { return NumCaptures; }
3602
3603   typedef ArrayRef<Capture>::const_iterator capture_const_iterator;
3604
3605   ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; }
3606
3607   capture_const_iterator capture_begin() const { return captures().begin(); }
3608   capture_const_iterator capture_end() const { return captures().end(); }
3609
3610   bool capturesCXXThis() const { return CapturesCXXThis; }
3611   bool blockMissingReturnType() const { return BlockMissingReturnType; }
3612   void setBlockMissingReturnType(bool val) { BlockMissingReturnType = val; }
3613
3614   bool isConversionFromLambda() const { return IsConversionFromLambda; }
3615   void setIsConversionFromLambda(bool val) { IsConversionFromLambda = val; }
3616
3617   bool capturesVariable(const VarDecl *var) const;
3618
3619   void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
3620                    bool CapturesCXXThis);
3621
3622    unsigned getBlockManglingNumber() const {
3623      return ManglingNumber;
3624    }
3625    Decl *getBlockManglingContextDecl() const {
3626      return ManglingContextDecl;    
3627    }
3628
3629   void setBlockMangling(unsigned Number, Decl *Ctx) {
3630     ManglingNumber = Number;
3631     ManglingContextDecl = Ctx;
3632   }
3633
3634   SourceRange getSourceRange() const override LLVM_READONLY;
3635
3636   // Implement isa/cast/dyncast/etc.
3637   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3638   static bool classofKind(Kind K) { return K == Block; }
3639   static DeclContext *castToDeclContext(const BlockDecl *D) {
3640     return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
3641   }
3642   static BlockDecl *castFromDeclContext(const DeclContext *DC) {
3643     return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
3644   }
3645 };
3646
3647 /// \brief This represents the body of a CapturedStmt, and serves as its
3648 /// DeclContext.
3649 class CapturedDecl final
3650     : public Decl,
3651       public DeclContext,
3652       private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> {
3653 protected:
3654   size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) {
3655     return NumParams;
3656   }
3657
3658 private:
3659   /// \brief The number of parameters to the outlined function.
3660   unsigned NumParams;
3661   /// \brief The position of context parameter in list of parameters.
3662   unsigned ContextParam;
3663   /// \brief The body of the outlined function.
3664   llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow;
3665
3666   explicit CapturedDecl(DeclContext *DC, unsigned NumParams);
3667
3668   ImplicitParamDecl *const *getParams() const {
3669     return getTrailingObjects<ImplicitParamDecl *>();
3670   }
3671
3672   ImplicitParamDecl **getParams() {
3673     return getTrailingObjects<ImplicitParamDecl *>();
3674   }
3675
3676 public:
3677   static CapturedDecl *Create(ASTContext &C, DeclContext *DC,
3678                               unsigned NumParams);
3679   static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3680                                           unsigned NumParams);
3681
3682   Stmt *getBody() const override;
3683   void setBody(Stmt *B);
3684
3685   bool isNothrow() const;
3686   void setNothrow(bool Nothrow = true);
3687
3688   unsigned getNumParams() const { return NumParams; }
3689
3690   ImplicitParamDecl *getParam(unsigned i) const {
3691     assert(i < NumParams);
3692     return getParams()[i];
3693   }
3694   void setParam(unsigned i, ImplicitParamDecl *P) {
3695     assert(i < NumParams);
3696     getParams()[i] = P;
3697   }
3698
3699   // ArrayRef interface to parameters.
3700   ArrayRef<ImplicitParamDecl *> parameters() const {
3701     return {getParams(), getNumParams()};
3702   }
3703   MutableArrayRef<ImplicitParamDecl *> parameters() {
3704     return {getParams(), getNumParams()};
3705   }
3706
3707   /// \brief Retrieve the parameter containing captured variables.
3708   ImplicitParamDecl *getContextParam() const {
3709     assert(ContextParam < NumParams);
3710     return getParam(ContextParam);
3711   }
3712   void setContextParam(unsigned i, ImplicitParamDecl *P) {
3713     assert(i < NumParams);
3714     ContextParam = i;
3715     setParam(i, P);
3716   }
3717   unsigned getContextParamPosition() const { return ContextParam; }
3718
3719   typedef ImplicitParamDecl *const *param_iterator;
3720   typedef llvm::iterator_range<param_iterator> param_range;
3721
3722   /// \brief Retrieve an iterator pointing to the first parameter decl.
3723   param_iterator param_begin() const { return getParams(); }
3724   /// \brief Retrieve an iterator one past the last parameter decl.
3725   param_iterator param_end() const { return getParams() + NumParams; }
3726
3727   // Implement isa/cast/dyncast/etc.
3728   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3729   static bool classofKind(Kind K) { return K == Captured; }
3730   static DeclContext *castToDeclContext(const CapturedDecl *D) {
3731     return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D));
3732   }
3733   static CapturedDecl *castFromDeclContext(const DeclContext *DC) {
3734     return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC));
3735   }
3736
3737   friend class ASTDeclReader;
3738   friend class ASTDeclWriter;
3739   friend TrailingObjects;
3740 };
3741
3742 /// \brief Describes a module import declaration, which makes the contents
3743 /// of the named module visible in the current translation unit.
3744 ///
3745 /// An import declaration imports the named module (or submodule). For example:
3746 /// \code
3747 ///   @import std.vector;
3748 /// \endcode
3749 ///
3750 /// Import declarations can also be implicitly generated from
3751 /// \#include/\#import directives.
3752 class ImportDecl final : public Decl,
3753                          llvm::TrailingObjects<ImportDecl, SourceLocation> {
3754   /// \brief The imported module, along with a bit that indicates whether
3755   /// we have source-location information for each identifier in the module
3756   /// name. 
3757   ///
3758   /// When the bit is false, we only have a single source location for the
3759   /// end of the import declaration.
3760   llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete;
3761   
3762   /// \brief The next import in the list of imports local to the translation
3763   /// unit being parsed (not loaded from an AST file).
3764   ImportDecl *NextLocalImport;
3765   
3766   friend class ASTReader;
3767   friend class ASTDeclReader;
3768   friend class ASTContext;
3769   friend TrailingObjects;
3770
3771   ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3772              ArrayRef<SourceLocation> IdentifierLocs);
3773
3774   ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
3775              SourceLocation EndLoc);
3776
3777   ImportDecl(EmptyShell Empty) : Decl(Import, Empty), NextLocalImport() { }
3778   
3779 public:
3780   /// \brief Create a new module import declaration.
3781   static ImportDecl *Create(ASTContext &C, DeclContext *DC, 
3782                             SourceLocation StartLoc, Module *Imported,
3783                             ArrayRef<SourceLocation> IdentifierLocs);
3784   
3785   /// \brief Create a new module import declaration for an implicitly-generated
3786   /// import.
3787   static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC, 
3788                                     SourceLocation StartLoc, Module *Imported, 
3789                                     SourceLocation EndLoc);
3790   
3791   /// \brief Create a new, deserialized module import declaration.
3792   static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID, 
3793                                         unsigned NumLocations);
3794   
3795   /// \brief Retrieve the module that was imported by the import declaration.
3796   Module *getImportedModule() const { return ImportedAndComplete.getPointer(); }
3797   
3798   /// \brief Retrieves the locations of each of the identifiers that make up
3799   /// the complete module name in the import declaration.
3800   ///
3801   /// This will return an empty array if the locations of the individual
3802   /// identifiers aren't available.
3803   ArrayRef<SourceLocation> getIdentifierLocs() const;
3804
3805   SourceRange getSourceRange() const override LLVM_READONLY;
3806
3807   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3808   static bool classofKind(Kind K) { return K == Import; }
3809 };
3810
3811 /// \brief Represents a C++ Modules TS module export declaration.
3812 ///
3813 /// For example:
3814 /// \code
3815 ///   export void foo();
3816 /// \endcode
3817 class ExportDecl final : public Decl, public DeclContext {
3818   virtual void anchor();
3819 private:
3820   /// \brief The source location for the right brace (if valid).
3821   SourceLocation RBraceLoc;
3822
3823   ExportDecl(DeclContext *DC, SourceLocation ExportLoc)
3824     : Decl(Export, DC, ExportLoc), DeclContext(Export),
3825       RBraceLoc(SourceLocation()) { }
3826
3827   friend class ASTDeclReader;
3828
3829 public:
3830   static ExportDecl *Create(ASTContext &C, DeclContext *DC,
3831                             SourceLocation ExportLoc);
3832   static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3833   
3834   SourceLocation getExportLoc() const { return getLocation(); }
3835   SourceLocation getRBraceLoc() const { return RBraceLoc; }
3836   void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
3837
3838   SourceLocation getLocEnd() const LLVM_READONLY {
3839     if (RBraceLoc.isValid())
3840       return RBraceLoc;
3841     // No braces: get the end location of the (only) declaration in context
3842     // (if present).
3843     return decls_empty() ? getLocation() : decls_begin()->getLocEnd();
3844   }
3845
3846   SourceRange getSourceRange() const override LLVM_READONLY {
3847     return SourceRange(getLocation(), getLocEnd());
3848   }
3849
3850   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3851   static bool classofKind(Kind K) { return K == Export; }
3852   static DeclContext *castToDeclContext(const ExportDecl *D) {
3853     return static_cast<DeclContext *>(const_cast<ExportDecl*>(D));
3854   }
3855   static ExportDecl *castFromDeclContext(const DeclContext *DC) {
3856     return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC));
3857   }
3858 };
3859
3860 /// \brief Represents an empty-declaration.
3861 class EmptyDecl : public Decl {
3862   virtual void anchor();
3863   EmptyDecl(DeclContext *DC, SourceLocation L)
3864     : Decl(Empty, DC, L) { }
3865
3866 public:
3867   static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
3868                            SourceLocation L);
3869   static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3870
3871   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3872   static bool classofKind(Kind K) { return K == Empty; }
3873 };
3874
3875 /// Insertion operator for diagnostics.  This allows sending NamedDecl's
3876 /// into a diagnostic with <<.
3877 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
3878                                            const NamedDecl* ND) {
3879   DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
3880                   DiagnosticsEngine::ak_nameddecl);
3881   return DB;
3882 }
3883 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
3884                                            const NamedDecl* ND) {
3885   PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
3886                   DiagnosticsEngine::ak_nameddecl);
3887   return PD;
3888 }
3889
3890 template<typename decl_type>
3891 void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) {
3892   // Note: This routine is implemented here because we need both NamedDecl
3893   // and Redeclarable to be defined.
3894   assert(RedeclLink.NextIsLatest() &&
3895          "setPreviousDecl on a decl already in a redeclaration chain");
3896
3897   if (PrevDecl) {
3898     // Point to previous. Make sure that this is actually the most recent
3899     // redeclaration, or we can build invalid chains. If the most recent
3900     // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
3901     First = PrevDecl->getFirstDecl();
3902     assert(First->RedeclLink.NextIsLatest() && "Expected first");
3903     decl_type *MostRecent = First->getNextRedeclaration();
3904     RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent));
3905
3906     // If the declaration was previously visible, a redeclaration of it remains
3907     // visible even if it wouldn't be visible by itself.
3908     static_cast<decl_type*>(this)->IdentifierNamespace |=
3909       MostRecent->getIdentifierNamespace() &
3910       (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
3911   } else {
3912     // Make this first.
3913     First = static_cast<decl_type*>(this);
3914   }
3915
3916   // First one will point to this one as latest.
3917   First->RedeclLink.setLatest(static_cast<decl_type*>(this));
3918
3919   assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
3920          cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid());
3921 }
3922
3923 // Inline function definitions.
3924
3925 /// \brief Check if the given decl is complete.
3926 ///
3927 /// We use this function to break a cycle between the inline definitions in
3928 /// Type.h and Decl.h.
3929 inline bool IsEnumDeclComplete(EnumDecl *ED) {
3930   return ED->isComplete();
3931 }
3932
3933 /// \brief Check if the given decl is scoped.
3934 ///
3935 /// We use this function to break a cycle between the inline definitions in
3936 /// Type.h and Decl.h.
3937 inline bool IsEnumDeclScoped(EnumDecl *ED) {
3938   return ED->isScoped();
3939 }
3940
3941 }  // end namespace clang
3942
3943 #endif