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