1 //===- DeclObjC.h - Classes for representing declarations -------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file defines the DeclObjC interface and subclasses.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CLANG_AST_DECLOBJC_H
14 #define LLVM_CLANG_AST_DECLOBJC_H
15 
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclBase.h"
18 #include "clang/AST/ExternalASTSource.h"
19 #include "clang/AST/Redeclarable.h"
20 #include "clang/AST/SelectorLocationsKind.h"
21 #include "clang/AST/Type.h"
22 #include "clang/Basic/IdentifierTable.h"
23 #include "clang/Basic/LLVM.h"
24 #include "clang/Basic/SourceLocation.h"
25 #include "clang/Basic/Specifiers.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/DenseSet.h"
29 #include "llvm/ADT/None.h"
30 #include "llvm/ADT/PointerIntPair.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/StringRef.h"
33 #include "llvm/ADT/iterator_range.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/Support/TrailingObjects.h"
36 #include <cassert>
37 #include <cstddef>
38 #include <cstdint>
39 #include <iterator>
40 #include <string>
41 #include <utility>
42 
43 namespace clang {
44 
45 class ASTContext;
46 class CompoundStmt;
47 class CXXCtorInitializer;
48 class Expr;
49 class ObjCCategoryDecl;
50 class ObjCCategoryImplDecl;
51 class ObjCImplementationDecl;
52 class ObjCInterfaceDecl;
53 class ObjCIvarDecl;
54 class ObjCPropertyDecl;
55 class ObjCPropertyImplDecl;
56 class ObjCProtocolDecl;
57 class Stmt;
58 
59 class ObjCListBase {
60 protected:
61   /// List is an array of pointers to objects that are not owned by this object.
62   void **List = nullptr;
63   unsigned NumElts = 0;
64 
65 public:
66   ObjCListBase() = default;
67   ObjCListBase(const ObjCListBase &) = delete;
68   ObjCListBase &operator=(const ObjCListBase &) = delete;
69 
size()70   unsigned size() const { return NumElts; }
empty()71   bool empty() const { return NumElts == 0; }
72 
73 protected:
74   void set(void *const* InList, unsigned Elts, ASTContext &Ctx);
75 };
76 
77 /// ObjCList - This is a simple template class used to hold various lists of
78 /// decls etc, which is heavily used by the ObjC front-end.  This only use case
79 /// this supports is setting the list all at once and then reading elements out
80 /// of it.
81 template <typename T>
82 class ObjCList : public ObjCListBase {
83 public:
set(T * const * InList,unsigned Elts,ASTContext & Ctx)84   void set(T* const* InList, unsigned Elts, ASTContext &Ctx) {
85     ObjCListBase::set(reinterpret_cast<void*const*>(InList), Elts, Ctx);
86   }
87 
88   using iterator = T* const *;
89 
begin()90   iterator begin() const { return (iterator)List; }
end()91   iterator end() const { return (iterator)List+NumElts; }
92 
93   T* operator[](unsigned Idx) const {
94     assert(Idx < NumElts && "Invalid access");
95     return (T*)List[Idx];
96   }
97 };
98 
99 /// A list of Objective-C protocols, along with the source
100 /// locations at which they were referenced.
101 class ObjCProtocolList : public ObjCList<ObjCProtocolDecl> {
102   SourceLocation *Locations = nullptr;
103 
104   using ObjCList<ObjCProtocolDecl>::set;
105 
106 public:
107   ObjCProtocolList() = default;
108 
109   using loc_iterator = const SourceLocation *;
110 
loc_begin()111   loc_iterator loc_begin() const { return Locations; }
loc_end()112   loc_iterator loc_end() const { return Locations + size(); }
113 
114   void set(ObjCProtocolDecl* const* InList, unsigned Elts,
115            const SourceLocation *Locs, ASTContext &Ctx);
116 };
117 
118 /// ObjCMethodDecl - Represents an instance or class method declaration.
119 /// ObjC methods can be declared within 4 contexts: class interfaces,
120 /// categories, protocols, and class implementations. While C++ member
121 /// functions leverage C syntax, Objective-C method syntax is modeled after
122 /// Smalltalk (using colons to specify argument types/expressions).
123 /// Here are some brief examples:
124 ///
125 /// Setter/getter instance methods:
126 /// - (void)setMenu:(NSMenu *)menu;
127 /// - (NSMenu *)menu;
128 ///
129 /// Instance method that takes 2 NSView arguments:
130 /// - (void)replaceSubview:(NSView *)oldView with:(NSView *)newView;
131 ///
132 /// Getter class method:
133 /// + (NSMenu *)defaultMenu;
134 ///
135 /// A selector represents a unique name for a method. The selector names for
136 /// the above methods are setMenu:, menu, replaceSubview:with:, and defaultMenu.
137 ///
138 class ObjCMethodDecl : public NamedDecl, public DeclContext {
139   // This class stores some data in DeclContext::ObjCMethodDeclBits
140   // to save some space. Use the provided accessors to access it.
141 
142 public:
143   enum ImplementationControl { None, Required, Optional };
144 
145 private:
146   /// Return type of this method.
147   QualType MethodDeclType;
148 
149   /// Type source information for the return type.
150   TypeSourceInfo *ReturnTInfo;
151 
152   /// Array of ParmVarDecls for the formal parameters of this method
153   /// and optionally followed by selector locations.
154   void *ParamsAndSelLocs = nullptr;
155   unsigned NumParams = 0;
156 
157   /// List of attributes for this method declaration.
158   SourceLocation DeclEndLoc; // the location of the ';' or '{'.
159 
160   /// The following are only used for method definitions, null otherwise.
161   LazyDeclStmtPtr Body;
162 
163   /// SelfDecl - Decl for the implicit self parameter. This is lazily
164   /// constructed by createImplicitParams.
165   ImplicitParamDecl *SelfDecl = nullptr;
166 
167   /// CmdDecl - Decl for the implicit _cmd parameter. This is lazily
168   /// constructed by createImplicitParams.
169   ImplicitParamDecl *CmdDecl = nullptr;
170 
171   ObjCMethodDecl(SourceLocation beginLoc, SourceLocation endLoc,
172                  Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo,
173                  DeclContext *contextDecl, bool isInstance = true,
174                  bool isVariadic = false, bool isPropertyAccessor = false,
175                  bool isImplicitlyDeclared = false, bool isDefined = false,
176                  ImplementationControl impControl = None,
177                  bool HasRelatedResultType = false);
178 
getSelLocsKind()179   SelectorLocationsKind getSelLocsKind() const {
180     return static_cast<SelectorLocationsKind>(ObjCMethodDeclBits.SelLocsKind);
181   }
182 
setSelLocsKind(SelectorLocationsKind Kind)183   void setSelLocsKind(SelectorLocationsKind Kind) {
184     ObjCMethodDeclBits.SelLocsKind = Kind;
185   }
186 
hasStandardSelLocs()187   bool hasStandardSelLocs() const {
188     return getSelLocsKind() != SelLoc_NonStandard;
189   }
190 
191   /// Get a pointer to the stored selector identifiers locations array.
192   /// No locations will be stored if HasStandardSelLocs is true.
getStoredSelLocs()193   SourceLocation *getStoredSelLocs() {
194     return reinterpret_cast<SourceLocation *>(getParams() + NumParams);
195   }
getStoredSelLocs()196   const SourceLocation *getStoredSelLocs() const {
197     return reinterpret_cast<const SourceLocation *>(getParams() + NumParams);
198   }
199 
200   /// Get a pointer to the stored selector identifiers locations array.
201   /// No locations will be stored if HasStandardSelLocs is true.
getParams()202   ParmVarDecl **getParams() {
203     return reinterpret_cast<ParmVarDecl **>(ParamsAndSelLocs);
204   }
getParams()205   const ParmVarDecl *const *getParams() const {
206     return reinterpret_cast<const ParmVarDecl *const *>(ParamsAndSelLocs);
207   }
208 
209   /// Get the number of stored selector identifiers locations.
210   /// No locations will be stored if HasStandardSelLocs is true.
getNumStoredSelLocs()211   unsigned getNumStoredSelLocs() const {
212     if (hasStandardSelLocs())
213       return 0;
214     return getNumSelectorLocs();
215   }
216 
217   void setParamsAndSelLocs(ASTContext &C,
218                            ArrayRef<ParmVarDecl*> Params,
219                            ArrayRef<SourceLocation> SelLocs);
220 
221   /// A definition will return its interface declaration.
222   /// An interface declaration will return its definition.
223   /// Otherwise it will return itself.
224   ObjCMethodDecl *getNextRedeclarationImpl() override;
225 
226 public:
227   friend class ASTDeclReader;
228   friend class ASTDeclWriter;
229 
230   static ObjCMethodDecl *
231   Create(ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc,
232          Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo,
233          DeclContext *contextDecl, bool isInstance = true,
234          bool isVariadic = false, bool isPropertyAccessor = false,
235          bool isImplicitlyDeclared = false, bool isDefined = false,
236          ImplementationControl impControl = None,
237          bool HasRelatedResultType = false);
238 
239   static ObjCMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID);
240 
241   ObjCMethodDecl *getCanonicalDecl() override;
getCanonicalDecl()242   const ObjCMethodDecl *getCanonicalDecl() const {
243     return const_cast<ObjCMethodDecl*>(this)->getCanonicalDecl();
244   }
245 
getObjCDeclQualifier()246   ObjCDeclQualifier getObjCDeclQualifier() const {
247     return static_cast<ObjCDeclQualifier>(ObjCMethodDeclBits.objcDeclQualifier);
248   }
249 
setObjCDeclQualifier(ObjCDeclQualifier QV)250   void setObjCDeclQualifier(ObjCDeclQualifier QV) {
251     ObjCMethodDeclBits.objcDeclQualifier = QV;
252   }
253 
254   /// Determine whether this method has a result type that is related
255   /// to the message receiver's type.
hasRelatedResultType()256   bool hasRelatedResultType() const {
257     return ObjCMethodDeclBits.RelatedResultType;
258   }
259 
260   /// Note whether this method has a related result type.
261   void setRelatedResultType(bool RRT = true) {
262     ObjCMethodDeclBits.RelatedResultType = RRT;
263   }
264 
265   /// True if this is a method redeclaration in the same interface.
isRedeclaration()266   bool isRedeclaration() const { return ObjCMethodDeclBits.IsRedeclaration; }
setIsRedeclaration(bool RD)267   void setIsRedeclaration(bool RD) { ObjCMethodDeclBits.IsRedeclaration = RD; }
268   void setAsRedeclaration(const ObjCMethodDecl *PrevMethod);
269 
270   /// True if redeclared in the same interface.
hasRedeclaration()271   bool hasRedeclaration() const { return ObjCMethodDeclBits.HasRedeclaration; }
setHasRedeclaration(bool HRD)272   void setHasRedeclaration(bool HRD) const {
273     ObjCMethodDeclBits.HasRedeclaration = HRD;
274   }
275 
276   /// Returns the location where the declarator ends. It will be
277   /// the location of ';' for a method declaration and the location of '{'
278   /// for a method definition.
getDeclaratorEndLoc()279   SourceLocation getDeclaratorEndLoc() const { return DeclEndLoc; }
280 
281   // Location information, modeled after the Stmt API.
getBeginLoc()282   SourceLocation getBeginLoc() const LLVM_READONLY { return getLocation(); }
283   SourceLocation getEndLoc() const LLVM_READONLY;
getSourceRange()284   SourceRange getSourceRange() const override LLVM_READONLY {
285     return SourceRange(getLocation(), getEndLoc());
286   }
287 
getSelectorStartLoc()288   SourceLocation getSelectorStartLoc() const {
289     if (isImplicit())
290       return getBeginLoc();
291     return getSelectorLoc(0);
292   }
293 
getSelectorLoc(unsigned Index)294   SourceLocation getSelectorLoc(unsigned Index) const {
295     assert(Index < getNumSelectorLocs() && "Index out of range!");
296     if (hasStandardSelLocs())
297       return getStandardSelectorLoc(Index, getSelector(),
298                                    getSelLocsKind() == SelLoc_StandardWithSpace,
299                                     parameters(),
300                                    DeclEndLoc);
301     return getStoredSelLocs()[Index];
302   }
303 
304   void getSelectorLocs(SmallVectorImpl<SourceLocation> &SelLocs) const;
305 
getNumSelectorLocs()306   unsigned getNumSelectorLocs() const {
307     if (isImplicit())
308       return 0;
309     Selector Sel = getSelector();
310     if (Sel.isUnarySelector())
311       return 1;
312     return Sel.getNumArgs();
313   }
314 
315   ObjCInterfaceDecl *getClassInterface();
getClassInterface()316   const ObjCInterfaceDecl *getClassInterface() const {
317     return const_cast<ObjCMethodDecl*>(this)->getClassInterface();
318   }
319 
getSelector()320   Selector getSelector() const { return getDeclName().getObjCSelector(); }
321 
getReturnType()322   QualType getReturnType() const { return MethodDeclType; }
setReturnType(QualType T)323   void setReturnType(QualType T) { MethodDeclType = T; }
324   SourceRange getReturnTypeSourceRange() const;
325 
326   /// Determine the type of an expression that sends a message to this
327   /// function. This replaces the type parameters with the types they would
328   /// get if the receiver was parameterless (e.g. it may replace the type
329   /// parameter with 'id').
330   QualType getSendResultType() const;
331 
332   /// Determine the type of an expression that sends a message to this
333   /// function with the given receiver type.
334   QualType getSendResultType(QualType receiverType) const;
335 
getReturnTypeSourceInfo()336   TypeSourceInfo *getReturnTypeSourceInfo() const { return ReturnTInfo; }
setReturnTypeSourceInfo(TypeSourceInfo * TInfo)337   void setReturnTypeSourceInfo(TypeSourceInfo *TInfo) { ReturnTInfo = TInfo; }
338 
339   // Iterator access to formal parameters.
param_size()340   unsigned param_size() const { return NumParams; }
341 
342   using param_const_iterator = const ParmVarDecl *const *;
343   using param_iterator = ParmVarDecl *const *;
344   using param_range = llvm::iterator_range<param_iterator>;
345   using param_const_range = llvm::iterator_range<param_const_iterator>;
346 
param_begin()347   param_const_iterator param_begin() const {
348     return param_const_iterator(getParams());
349   }
350 
param_end()351   param_const_iterator param_end() const {
352     return param_const_iterator(getParams() + NumParams);
353   }
354 
param_begin()355   param_iterator param_begin() { return param_iterator(getParams()); }
param_end()356   param_iterator param_end() { return param_iterator(getParams() + NumParams); }
357 
358   // This method returns and of the parameters which are part of the selector
359   // name mangling requirements.
sel_param_end()360   param_const_iterator sel_param_end() const {
361     return param_begin() + getSelector().getNumArgs();
362   }
363 
364   // ArrayRef access to formal parameters.  This should eventually
365   // replace the iterator interface above.
parameters()366   ArrayRef<ParmVarDecl*> parameters() const {
367     return llvm::makeArrayRef(const_cast<ParmVarDecl**>(getParams()),
368                               NumParams);
369   }
370 
getParamDecl(unsigned Idx)371   ParmVarDecl *getParamDecl(unsigned Idx) {
372     assert(Idx < NumParams && "Index out of bounds!");
373     return getParams()[Idx];
374   }
getParamDecl(unsigned Idx)375   const ParmVarDecl *getParamDecl(unsigned Idx) const {
376     return const_cast<ObjCMethodDecl *>(this)->getParamDecl(Idx);
377   }
378 
379   /// Sets the method's parameters and selector source locations.
380   /// If the method is implicit (not coming from source) \p SelLocs is
381   /// ignored.
382   void setMethodParams(ASTContext &C,
383                        ArrayRef<ParmVarDecl*> Params,
384                        ArrayRef<SourceLocation> SelLocs = llvm::None);
385 
386   // Iterator access to parameter types.
387   struct GetTypeFn {
operatorGetTypeFn388     QualType operator()(const ParmVarDecl *PD) const { return PD->getType(); }
389   };
390 
391   using param_type_iterator =
392       llvm::mapped_iterator<param_const_iterator, GetTypeFn>;
393 
param_type_begin()394   param_type_iterator param_type_begin() const {
395     return llvm::map_iterator(param_begin(), GetTypeFn());
396   }
397 
param_type_end()398   param_type_iterator param_type_end() const {
399     return llvm::map_iterator(param_end(), GetTypeFn());
400   }
401 
402   /// createImplicitParams - Used to lazily create the self and cmd
403   /// implict parameters. This must be called prior to using getSelfDecl()
404   /// or getCmdDecl(). The call is ignored if the implicit parameters
405   /// have already been created.
406   void createImplicitParams(ASTContext &Context, const ObjCInterfaceDecl *ID);
407 
408   /// \return the type for \c self and set \arg selfIsPseudoStrong and
409   /// \arg selfIsConsumed accordingly.
410   QualType getSelfType(ASTContext &Context, const ObjCInterfaceDecl *OID,
411                        bool &selfIsPseudoStrong, bool &selfIsConsumed);
412 
getSelfDecl()413   ImplicitParamDecl * getSelfDecl() const { return SelfDecl; }
setSelfDecl(ImplicitParamDecl * SD)414   void setSelfDecl(ImplicitParamDecl *SD) { SelfDecl = SD; }
getCmdDecl()415   ImplicitParamDecl * getCmdDecl() const { return CmdDecl; }
setCmdDecl(ImplicitParamDecl * CD)416   void setCmdDecl(ImplicitParamDecl *CD) { CmdDecl = CD; }
417 
418   /// Determines the family of this method.
419   ObjCMethodFamily getMethodFamily() const;
420 
isInstanceMethod()421   bool isInstanceMethod() const { return ObjCMethodDeclBits.IsInstance; }
setInstanceMethod(bool isInst)422   void setInstanceMethod(bool isInst) {
423     ObjCMethodDeclBits.IsInstance = isInst;
424   }
425 
isVariadic()426   bool isVariadic() const { return ObjCMethodDeclBits.IsVariadic; }
setVariadic(bool isVar)427   void setVariadic(bool isVar) { ObjCMethodDeclBits.IsVariadic = isVar; }
428 
isClassMethod()429   bool isClassMethod() const { return !isInstanceMethod(); }
430 
isPropertyAccessor()431   bool isPropertyAccessor() const {
432     return ObjCMethodDeclBits.IsPropertyAccessor;
433   }
434 
setPropertyAccessor(bool isAccessor)435   void setPropertyAccessor(bool isAccessor) {
436     ObjCMethodDeclBits.IsPropertyAccessor = isAccessor;
437   }
438 
isDefined()439   bool isDefined() const { return ObjCMethodDeclBits.IsDefined; }
setDefined(bool isDefined)440   void setDefined(bool isDefined) { ObjCMethodDeclBits.IsDefined = isDefined; }
441 
442   /// Whether this method overrides any other in the class hierarchy.
443   ///
444   /// A method is said to override any method in the class's
445   /// base classes, its protocols, or its categories' protocols, that has
446   /// the same selector and is of the same kind (class or instance).
447   /// A method in an implementation is not considered as overriding the same
448   /// method in the interface or its categories.
isOverriding()449   bool isOverriding() const { return ObjCMethodDeclBits.IsOverriding; }
setOverriding(bool IsOver)450   void setOverriding(bool IsOver) { ObjCMethodDeclBits.IsOverriding = IsOver; }
451 
452   /// Return overridden methods for the given \p Method.
453   ///
454   /// An ObjC method is considered to override any method in the class's
455   /// base classes (and base's categories), its protocols, or its categories'
456   /// protocols, that has
457   /// the same selector and is of the same kind (class or instance).
458   /// A method in an implementation is not considered as overriding the same
459   /// method in the interface or its categories.
460   void getOverriddenMethods(
461                      SmallVectorImpl<const ObjCMethodDecl *> &Overridden) const;
462 
463   /// True if the method was a definition but its body was skipped.
hasSkippedBody()464   bool hasSkippedBody() const { return ObjCMethodDeclBits.HasSkippedBody; }
465   void setHasSkippedBody(bool Skipped = true) {
466     ObjCMethodDeclBits.HasSkippedBody = Skipped;
467   }
468 
469   /// Returns the property associated with this method's selector.
470   ///
471   /// Note that even if this particular method is not marked as a property
472   /// accessor, it is still possible for it to match a property declared in a
473   /// superclass. Pass \c false if you only want to check the current class.
474   const ObjCPropertyDecl *findPropertyDecl(bool CheckOverrides = true) const;
475 
476   // Related to protocols declared in  \@protocol
setDeclImplementation(ImplementationControl ic)477   void setDeclImplementation(ImplementationControl ic) {
478     ObjCMethodDeclBits.DeclImplementation = ic;
479   }
480 
getImplementationControl()481   ImplementationControl getImplementationControl() const {
482     return ImplementationControl(ObjCMethodDeclBits.DeclImplementation);
483   }
484 
isOptional()485   bool isOptional() const {
486     return getImplementationControl() == Optional;
487   }
488 
489   /// Returns true if this specific method declaration is marked with the
490   /// designated initializer attribute.
491   bool isThisDeclarationADesignatedInitializer() const;
492 
493   /// Returns true if the method selector resolves to a designated initializer
494   /// in the class's interface.
495   ///
496   /// \param InitMethod if non-null and the function returns true, it receives
497   /// the method declaration that was marked with the designated initializer
498   /// attribute.
499   bool isDesignatedInitializerForTheInterface(
500       const ObjCMethodDecl **InitMethod = nullptr) const;
501 
502   /// Determine whether this method has a body.
hasBody()503   bool hasBody() const override { return Body.isValid(); }
504 
505   /// Retrieve the body of this method, if it has one.
506   Stmt *getBody() const override;
507 
setLazyBody(uint64_t Offset)508   void setLazyBody(uint64_t Offset) { Body = Offset; }
509 
getCompoundBody()510   CompoundStmt *getCompoundBody() { return (CompoundStmt*)getBody(); }
setBody(Stmt * B)511   void setBody(Stmt *B) { Body = B; }
512 
513   /// Returns whether this specific method is a definition.
isThisDeclarationADefinition()514   bool isThisDeclarationADefinition() const { return hasBody(); }
515 
516   /// Is this method defined in the NSObject base class?
517   bool definedInNSObject(const ASTContext &) const;
518 
519   // Implement isa/cast/dyncast/etc.
classof(const Decl * D)520   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classofKind(Kind K)521   static bool classofKind(Kind K) { return K == ObjCMethod; }
522 
castToDeclContext(const ObjCMethodDecl * D)523   static DeclContext *castToDeclContext(const ObjCMethodDecl *D) {
524     return static_cast<DeclContext *>(const_cast<ObjCMethodDecl*>(D));
525   }
526 
castFromDeclContext(const DeclContext * DC)527   static ObjCMethodDecl *castFromDeclContext(const DeclContext *DC) {
528     return static_cast<ObjCMethodDecl *>(const_cast<DeclContext*>(DC));
529   }
530 };
531 
532 /// Describes the variance of a given generic parameter.
533 enum class ObjCTypeParamVariance : uint8_t {
534   /// The parameter is invariant: must match exactly.
535   Invariant,
536 
537   /// The parameter is covariant, e.g., X<T> is a subtype of X<U> when
538   /// the type parameter is covariant and T is a subtype of U.
539   Covariant,
540 
541   /// The parameter is contravariant, e.g., X<T> is a subtype of X<U>
542   /// when the type parameter is covariant and U is a subtype of T.
543   Contravariant,
544 };
545 
546 /// Represents the declaration of an Objective-C type parameter.
547 ///
548 /// \code
549 /// @interface NSDictionary<Key : id<NSCopying>, Value>
550 /// @end
551 /// \endcode
552 ///
553 /// In the example above, both \c Key and \c Value are represented by
554 /// \c ObjCTypeParamDecl. \c Key has an explicit bound of \c id<NSCopying>,
555 /// while \c Value gets an implicit bound of \c id.
556 ///
557 /// Objective-C type parameters are typedef-names in the grammar,
558 class ObjCTypeParamDecl : public TypedefNameDecl {
559   /// Index of this type parameter in the type parameter list.
560   unsigned Index : 14;
561 
562   /// The variance of the type parameter.
563   unsigned Variance : 2;
564 
565   /// The location of the variance, if any.
566   SourceLocation VarianceLoc;
567 
568   /// The location of the ':', which will be valid when the bound was
569   /// explicitly specified.
570   SourceLocation ColonLoc;
571 
ObjCTypeParamDecl(ASTContext & ctx,DeclContext * dc,ObjCTypeParamVariance variance,SourceLocation varianceLoc,unsigned index,SourceLocation nameLoc,IdentifierInfo * name,SourceLocation colonLoc,TypeSourceInfo * boundInfo)572   ObjCTypeParamDecl(ASTContext &ctx, DeclContext *dc,
573                     ObjCTypeParamVariance variance, SourceLocation varianceLoc,
574                     unsigned index,
575                     SourceLocation nameLoc, IdentifierInfo *name,
576                     SourceLocation colonLoc, TypeSourceInfo *boundInfo)
577       : TypedefNameDecl(ObjCTypeParam, ctx, dc, nameLoc, nameLoc, name,
578                         boundInfo),
579         Index(index), Variance(static_cast<unsigned>(variance)),
580         VarianceLoc(varianceLoc), ColonLoc(colonLoc) {}
581 
582   void anchor() override;
583 
584 public:
585   friend class ASTDeclReader;
586   friend class ASTDeclWriter;
587 
588   static ObjCTypeParamDecl *Create(ASTContext &ctx, DeclContext *dc,
589                                    ObjCTypeParamVariance variance,
590                                    SourceLocation varianceLoc,
591                                    unsigned index,
592                                    SourceLocation nameLoc,
593                                    IdentifierInfo *name,
594                                    SourceLocation colonLoc,
595                                    TypeSourceInfo *boundInfo);
596   static ObjCTypeParamDecl *CreateDeserialized(ASTContext &ctx, unsigned ID);
597 
598   SourceRange getSourceRange() const override LLVM_READONLY;
599 
600   /// Determine the variance of this type parameter.
getVariance()601   ObjCTypeParamVariance getVariance() const {
602     return static_cast<ObjCTypeParamVariance>(Variance);
603   }
604 
605   /// Set the variance of this type parameter.
setVariance(ObjCTypeParamVariance variance)606   void setVariance(ObjCTypeParamVariance variance) {
607     Variance = static_cast<unsigned>(variance);
608   }
609 
610   /// Retrieve the location of the variance keyword.
getVarianceLoc()611   SourceLocation getVarianceLoc() const { return VarianceLoc; }
612 
613   /// Retrieve the index into its type parameter list.
getIndex()614   unsigned getIndex() const { return Index; }
615 
616   /// Whether this type parameter has an explicitly-written type bound, e.g.,
617   /// "T : NSView".
hasExplicitBound()618   bool hasExplicitBound() const { return ColonLoc.isValid(); }
619 
620   /// Retrieve the location of the ':' separating the type parameter name
621   /// from the explicitly-specified bound.
getColonLoc()622   SourceLocation getColonLoc() const { return ColonLoc; }
623 
624   // Implement isa/cast/dyncast/etc.
classof(const Decl * D)625   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classofKind(Kind K)626   static bool classofKind(Kind K) { return K == ObjCTypeParam; }
627 };
628 
629 /// Stores a list of Objective-C type parameters for a parameterized class
630 /// or a category/extension thereof.
631 ///
632 /// \code
633 /// @interface NSArray<T> // stores the <T>
634 /// @end
635 /// \endcode
636 class ObjCTypeParamList final
637     : private llvm::TrailingObjects<ObjCTypeParamList, ObjCTypeParamDecl *> {
638   /// Stores the components of a SourceRange as a POD.
639   struct PODSourceRange {
640     unsigned Begin;
641     unsigned End;
642   };
643 
644   union {
645     /// Location of the left and right angle brackets.
646     PODSourceRange Brackets;
647 
648     // Used only for alignment.
649     ObjCTypeParamDecl *AlignmentHack;
650   };
651 
652   /// The number of parameters in the list, which are tail-allocated.
653   unsigned NumParams;
654 
655   ObjCTypeParamList(SourceLocation lAngleLoc,
656                     ArrayRef<ObjCTypeParamDecl *> typeParams,
657                     SourceLocation rAngleLoc);
658 
659 public:
660   friend TrailingObjects;
661 
662   /// Create a new Objective-C type parameter list.
663   static ObjCTypeParamList *create(ASTContext &ctx,
664                                    SourceLocation lAngleLoc,
665                                    ArrayRef<ObjCTypeParamDecl *> typeParams,
666                                    SourceLocation rAngleLoc);
667 
668   /// Iterate through the type parameters in the list.
669   using iterator = ObjCTypeParamDecl **;
670 
begin()671   iterator begin() { return getTrailingObjects<ObjCTypeParamDecl *>(); }
672 
end()673   iterator end() { return begin() + size(); }
674 
675   /// Determine the number of type parameters in this list.
size()676   unsigned size() const { return NumParams; }
677 
678   // Iterate through the type parameters in the list.
679   using const_iterator = ObjCTypeParamDecl * const *;
680 
begin()681   const_iterator begin() const {
682     return getTrailingObjects<ObjCTypeParamDecl *>();
683   }
684 
end()685   const_iterator end() const {
686     return begin() + size();
687   }
688 
front()689   ObjCTypeParamDecl *front() const {
690     assert(size() > 0 && "empty Objective-C type parameter list");
691     return *begin();
692   }
693 
back()694   ObjCTypeParamDecl *back() const {
695     assert(size() > 0 && "empty Objective-C type parameter list");
696     return *(end() - 1);
697   }
698 
getLAngleLoc()699   SourceLocation getLAngleLoc() const {
700     return SourceLocation::getFromRawEncoding(Brackets.Begin);
701   }
702 
getRAngleLoc()703   SourceLocation getRAngleLoc() const {
704     return SourceLocation::getFromRawEncoding(Brackets.End);
705   }
706 
getSourceRange()707   SourceRange getSourceRange() const {
708     return SourceRange(getLAngleLoc(), getRAngleLoc());
709   }
710 
711   /// Gather the default set of type arguments to be substituted for
712   /// these type parameters when dealing with an unspecialized type.
713   void gatherDefaultTypeArgs(SmallVectorImpl<QualType> &typeArgs) const;
714 };
715 
716 enum class ObjCPropertyQueryKind : uint8_t {
717   OBJC_PR_query_unknown = 0x00,
718   OBJC_PR_query_instance,
719   OBJC_PR_query_class
720 };
721 
722 /// Represents one property declaration in an Objective-C interface.
723 ///
724 /// For example:
725 /// \code{.mm}
726 /// \@property (assign, readwrite) int MyProperty;
727 /// \endcode
728 class ObjCPropertyDecl : public NamedDecl {
729   void anchor() override;
730 
731 public:
732   enum PropertyAttributeKind {
733     OBJC_PR_noattr    = 0x00,
734     OBJC_PR_readonly  = 0x01,
735     OBJC_PR_getter    = 0x02,
736     OBJC_PR_assign    = 0x04,
737     OBJC_PR_readwrite = 0x08,
738     OBJC_PR_retain    = 0x10,
739     OBJC_PR_copy      = 0x20,
740     OBJC_PR_nonatomic = 0x40,
741     OBJC_PR_setter    = 0x80,
742     OBJC_PR_atomic    = 0x100,
743     OBJC_PR_weak      = 0x200,
744     OBJC_PR_strong    = 0x400,
745     OBJC_PR_unsafe_unretained = 0x800,
746     /// Indicates that the nullability of the type was spelled with a
747     /// property attribute rather than a type qualifier.
748     OBJC_PR_nullability = 0x1000,
749     OBJC_PR_null_resettable = 0x2000,
750     OBJC_PR_class = 0x4000
751     // Adding a property should change NumPropertyAttrsBits
752   };
753 
754   enum {
755     /// Number of bits fitting all the property attributes.
756     NumPropertyAttrsBits = 15
757   };
758 
759   enum SetterKind { Assign, Retain, Copy, Weak };
760   enum PropertyControl { None, Required, Optional };
761 
762 private:
763   // location of \@property
764   SourceLocation AtLoc;
765 
766   // location of '(' starting attribute list or null.
767   SourceLocation LParenLoc;
768 
769   QualType DeclType;
770   TypeSourceInfo *DeclTypeSourceInfo;
771   unsigned PropertyAttributes : NumPropertyAttrsBits;
772   unsigned PropertyAttributesAsWritten : NumPropertyAttrsBits;
773 
774   // \@required/\@optional
775   unsigned PropertyImplementation : 2;
776 
777   // getter name of NULL if no getter
778   Selector GetterName;
779 
780   // setter name of NULL if no setter
781   Selector SetterName;
782 
783   // location of the getter attribute's value
784   SourceLocation GetterNameLoc;
785 
786   // location of the setter attribute's value
787   SourceLocation SetterNameLoc;
788 
789   // Declaration of getter instance method
790   ObjCMethodDecl *GetterMethodDecl = nullptr;
791 
792   // Declaration of setter instance method
793   ObjCMethodDecl *SetterMethodDecl = nullptr;
794 
795   // Synthesize ivar for this property
796   ObjCIvarDecl *PropertyIvarDecl = nullptr;
797 
ObjCPropertyDecl(DeclContext * DC,SourceLocation L,IdentifierInfo * Id,SourceLocation AtLocation,SourceLocation LParenLocation,QualType T,TypeSourceInfo * TSI,PropertyControl propControl)798   ObjCPropertyDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
799                    SourceLocation AtLocation,  SourceLocation LParenLocation,
800                    QualType T, TypeSourceInfo *TSI,
801                    PropertyControl propControl)
802     : NamedDecl(ObjCProperty, DC, L, Id), AtLoc(AtLocation),
803       LParenLoc(LParenLocation), DeclType(T), DeclTypeSourceInfo(TSI),
804       PropertyAttributes(OBJC_PR_noattr),
805       PropertyAttributesAsWritten(OBJC_PR_noattr),
806       PropertyImplementation(propControl), GetterName(Selector()),
807       SetterName(Selector()) {}
808 
809 public:
810   static ObjCPropertyDecl *Create(ASTContext &C, DeclContext *DC,
811                                   SourceLocation L,
812                                   IdentifierInfo *Id, SourceLocation AtLocation,
813                                   SourceLocation LParenLocation,
814                                   QualType T,
815                                   TypeSourceInfo *TSI,
816                                   PropertyControl propControl = None);
817 
818   static ObjCPropertyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
819 
getAtLoc()820   SourceLocation getAtLoc() const { return AtLoc; }
setAtLoc(SourceLocation L)821   void setAtLoc(SourceLocation L) { AtLoc = L; }
822 
getLParenLoc()823   SourceLocation getLParenLoc() const { return LParenLoc; }
setLParenLoc(SourceLocation L)824   void setLParenLoc(SourceLocation L) { LParenLoc = L; }
825 
getTypeSourceInfo()826   TypeSourceInfo *getTypeSourceInfo() const { return DeclTypeSourceInfo; }
827 
getType()828   QualType getType() const { return DeclType; }
829 
setType(QualType T,TypeSourceInfo * TSI)830   void setType(QualType T, TypeSourceInfo *TSI) {
831     DeclType = T;
832     DeclTypeSourceInfo = TSI;
833   }
834 
835   /// Retrieve the type when this property is used with a specific base object
836   /// type.
837   QualType getUsageType(QualType objectType) const;
838 
getPropertyAttributes()839   PropertyAttributeKind getPropertyAttributes() const {
840     return PropertyAttributeKind(PropertyAttributes);
841   }
842 
setPropertyAttributes(PropertyAttributeKind PRVal)843   void setPropertyAttributes(PropertyAttributeKind PRVal) {
844     PropertyAttributes |= PRVal;
845   }
846 
overwritePropertyAttributes(unsigned PRVal)847   void overwritePropertyAttributes(unsigned PRVal) {
848     PropertyAttributes = PRVal;
849   }
850 
getPropertyAttributesAsWritten()851   PropertyAttributeKind getPropertyAttributesAsWritten() const {
852     return PropertyAttributeKind(PropertyAttributesAsWritten);
853   }
854 
setPropertyAttributesAsWritten(PropertyAttributeKind PRVal)855   void setPropertyAttributesAsWritten(PropertyAttributeKind PRVal) {
856     PropertyAttributesAsWritten = PRVal;
857   }
858 
859   // Helper methods for accessing attributes.
860 
861   /// isReadOnly - Return true iff the property has a setter.
isReadOnly()862   bool isReadOnly() const {
863     return (PropertyAttributes & OBJC_PR_readonly);
864   }
865 
866   /// isAtomic - Return true if the property is atomic.
isAtomic()867   bool isAtomic() const {
868     return (PropertyAttributes & OBJC_PR_atomic);
869   }
870 
871   /// isRetaining - Return true if the property retains its value.
isRetaining()872   bool isRetaining() const {
873     return (PropertyAttributes &
874             (OBJC_PR_retain | OBJC_PR_strong | OBJC_PR_copy));
875   }
876 
isInstanceProperty()877   bool isInstanceProperty() const { return !isClassProperty(); }
isClassProperty()878   bool isClassProperty() const { return PropertyAttributes & OBJC_PR_class; }
879 
getQueryKind()880   ObjCPropertyQueryKind getQueryKind() const {
881     return isClassProperty() ? ObjCPropertyQueryKind::OBJC_PR_query_class :
882                                ObjCPropertyQueryKind::OBJC_PR_query_instance;
883   }
884 
getQueryKind(bool isClassProperty)885   static ObjCPropertyQueryKind getQueryKind(bool isClassProperty) {
886     return isClassProperty ? ObjCPropertyQueryKind::OBJC_PR_query_class :
887                              ObjCPropertyQueryKind::OBJC_PR_query_instance;
888   }
889 
890   /// getSetterKind - Return the method used for doing assignment in
891   /// the property setter. This is only valid if the property has been
892   /// defined to have a setter.
getSetterKind()893   SetterKind getSetterKind() const {
894     if (PropertyAttributes & OBJC_PR_strong)
895       return getType()->isBlockPointerType() ? Copy : Retain;
896     if (PropertyAttributes & OBJC_PR_retain)
897       return Retain;
898     if (PropertyAttributes & OBJC_PR_copy)
899       return Copy;
900     if (PropertyAttributes & OBJC_PR_weak)
901       return Weak;
902     return Assign;
903   }
904 
getGetterName()905   Selector getGetterName() const { return GetterName; }
getGetterNameLoc()906   SourceLocation getGetterNameLoc() const { return GetterNameLoc; }
907 
908   void setGetterName(Selector Sel, SourceLocation Loc = SourceLocation()) {
909     GetterName = Sel;
910     GetterNameLoc = Loc;
911   }
912 
getSetterName()913   Selector getSetterName() const { return SetterName; }
getSetterNameLoc()914   SourceLocation getSetterNameLoc() const { return SetterNameLoc; }
915 
916   void setSetterName(Selector Sel, SourceLocation Loc = SourceLocation()) {
917     SetterName = Sel;
918     SetterNameLoc = Loc;
919   }
920 
getGetterMethodDecl()921   ObjCMethodDecl *getGetterMethodDecl() const { return GetterMethodDecl; }
setGetterMethodDecl(ObjCMethodDecl * gDecl)922   void setGetterMethodDecl(ObjCMethodDecl *gDecl) { GetterMethodDecl = gDecl; }
923 
getSetterMethodDecl()924   ObjCMethodDecl *getSetterMethodDecl() const { return SetterMethodDecl; }
setSetterMethodDecl(ObjCMethodDecl * gDecl)925   void setSetterMethodDecl(ObjCMethodDecl *gDecl) { SetterMethodDecl = gDecl; }
926 
927   // Related to \@optional/\@required declared in \@protocol
setPropertyImplementation(PropertyControl pc)928   void setPropertyImplementation(PropertyControl pc) {
929     PropertyImplementation = pc;
930   }
931 
getPropertyImplementation()932   PropertyControl getPropertyImplementation() const {
933     return PropertyControl(PropertyImplementation);
934   }
935 
isOptional()936   bool isOptional() const {
937     return getPropertyImplementation() == PropertyControl::Optional;
938   }
939 
setPropertyIvarDecl(ObjCIvarDecl * Ivar)940   void setPropertyIvarDecl(ObjCIvarDecl *Ivar) {
941     PropertyIvarDecl = Ivar;
942   }
943 
getPropertyIvarDecl()944   ObjCIvarDecl *getPropertyIvarDecl() const {
945     return PropertyIvarDecl;
946   }
947 
getSourceRange()948   SourceRange getSourceRange() const override LLVM_READONLY {
949     return SourceRange(AtLoc, getLocation());
950   }
951 
952   /// Get the default name of the synthesized ivar.
953   IdentifierInfo *getDefaultSynthIvarName(ASTContext &Ctx) const;
954 
955   /// Lookup a property by name in the specified DeclContext.
956   static ObjCPropertyDecl *findPropertyDecl(const DeclContext *DC,
957                                             const IdentifierInfo *propertyID,
958                                             ObjCPropertyQueryKind queryKind);
959 
classof(const Decl * D)960   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classofKind(Kind K)961   static bool classofKind(Kind K) { return K == ObjCProperty; }
962 };
963 
964 /// ObjCContainerDecl - Represents a container for method declarations.
965 /// Current sub-classes are ObjCInterfaceDecl, ObjCCategoryDecl,
966 /// ObjCProtocolDecl, and ObjCImplDecl.
967 ///
968 class ObjCContainerDecl : public NamedDecl, public DeclContext {
969   // This class stores some data in DeclContext::ObjCContainerDeclBits
970   // to save some space. Use the provided accessors to access it.
971 
972   // These two locations in the range mark the end of the method container.
973   // The first points to the '@' token, and the second to the 'end' token.
974   SourceRange AtEnd;
975 
976   void anchor() override;
977 
978 public:
979   ObjCContainerDecl(Kind DK, DeclContext *DC, IdentifierInfo *Id,
980                     SourceLocation nameLoc, SourceLocation atStartLoc);
981 
982   // Iterator access to instance/class properties.
983   using prop_iterator = specific_decl_iterator<ObjCPropertyDecl>;
984   using prop_range =
985       llvm::iterator_range<specific_decl_iterator<ObjCPropertyDecl>>;
986 
properties()987   prop_range properties() const { return prop_range(prop_begin(), prop_end()); }
988 
prop_begin()989   prop_iterator prop_begin() const {
990     return prop_iterator(decls_begin());
991   }
992 
prop_end()993   prop_iterator prop_end() const {
994     return prop_iterator(decls_end());
995   }
996 
997   using instprop_iterator =
998       filtered_decl_iterator<ObjCPropertyDecl,
999                              &ObjCPropertyDecl::isInstanceProperty>;
1000   using instprop_range = llvm::iterator_range<instprop_iterator>;
1001 
instance_properties()1002   instprop_range instance_properties() const {
1003     return instprop_range(instprop_begin(), instprop_end());
1004   }
1005 
instprop_begin()1006   instprop_iterator instprop_begin() const {
1007     return instprop_iterator(decls_begin());
1008   }
1009 
instprop_end()1010   instprop_iterator instprop_end() const {
1011     return instprop_iterator(decls_end());
1012   }
1013 
1014   using classprop_iterator =
1015       filtered_decl_iterator<ObjCPropertyDecl,
1016                              &ObjCPropertyDecl::isClassProperty>;
1017   using classprop_range = llvm::iterator_range<classprop_iterator>;
1018 
class_properties()1019   classprop_range class_properties() const {
1020     return classprop_range(classprop_begin(), classprop_end());
1021   }
1022 
classprop_begin()1023   classprop_iterator classprop_begin() const {
1024     return classprop_iterator(decls_begin());
1025   }
1026 
classprop_end()1027   classprop_iterator classprop_end() const {
1028     return classprop_iterator(decls_end());
1029   }
1030 
1031   // Iterator access to instance/class methods.
1032   using method_iterator = specific_decl_iterator<ObjCMethodDecl>;
1033   using method_range =
1034       llvm::iterator_range<specific_decl_iterator<ObjCMethodDecl>>;
1035 
methods()1036   method_range methods() const {
1037     return method_range(meth_begin(), meth_end());
1038   }
1039 
meth_begin()1040   method_iterator meth_begin() const {
1041     return method_iterator(decls_begin());
1042   }
1043 
meth_end()1044   method_iterator meth_end() const {
1045     return method_iterator(decls_end());
1046   }
1047 
1048   using instmeth_iterator =
1049       filtered_decl_iterator<ObjCMethodDecl,
1050                              &ObjCMethodDecl::isInstanceMethod>;
1051   using instmeth_range = llvm::iterator_range<instmeth_iterator>;
1052 
instance_methods()1053   instmeth_range instance_methods() const {
1054     return instmeth_range(instmeth_begin(), instmeth_end());
1055   }
1056 
instmeth_begin()1057   instmeth_iterator instmeth_begin() const {
1058     return instmeth_iterator(decls_begin());
1059   }
1060 
instmeth_end()1061   instmeth_iterator instmeth_end() const {
1062     return instmeth_iterator(decls_end());
1063   }
1064 
1065   using classmeth_iterator =
1066       filtered_decl_iterator<ObjCMethodDecl,
1067                              &ObjCMethodDecl::isClassMethod>;
1068   using classmeth_range = llvm::iterator_range<classmeth_iterator>;
1069 
class_methods()1070   classmeth_range class_methods() const {
1071     return classmeth_range(classmeth_begin(), classmeth_end());
1072   }
1073 
classmeth_begin()1074   classmeth_iterator classmeth_begin() const {
1075     return classmeth_iterator(decls_begin());
1076   }
1077 
classmeth_end()1078   classmeth_iterator classmeth_end() const {
1079     return classmeth_iterator(decls_end());
1080   }
1081 
1082   // Get the local instance/class method declared in this interface.
1083   ObjCMethodDecl *getMethod(Selector Sel, bool isInstance,
1084                             bool AllowHidden = false) const;
1085 
1086   ObjCMethodDecl *getInstanceMethod(Selector Sel,
1087                                     bool AllowHidden = false) const {
1088     return getMethod(Sel, true/*isInstance*/, AllowHidden);
1089   }
1090 
1091   ObjCMethodDecl *getClassMethod(Selector Sel, bool AllowHidden = false) const {
1092     return getMethod(Sel, false/*isInstance*/, AllowHidden);
1093   }
1094 
1095   bool HasUserDeclaredSetterMethod(const ObjCPropertyDecl *P) const;
1096   ObjCIvarDecl *getIvarDecl(IdentifierInfo *Id) const;
1097 
1098   ObjCPropertyDecl *
1099   FindPropertyDeclaration(const IdentifierInfo *PropertyId,
1100                           ObjCPropertyQueryKind QueryKind) const;
1101 
1102   using PropertyMap =
1103       llvm::DenseMap<std::pair<IdentifierInfo *, unsigned/*isClassProperty*/>,
1104                      ObjCPropertyDecl *>;
1105   using ProtocolPropertySet = llvm::SmallDenseSet<const ObjCProtocolDecl *, 8>;
1106   using PropertyDeclOrder = llvm::SmallVector<ObjCPropertyDecl *, 8>;
1107 
1108   /// This routine collects list of properties to be implemented in the class.
1109   /// This includes, class's and its conforming protocols' properties.
1110   /// Note, the superclass's properties are not included in the list.
collectPropertiesToImplement(PropertyMap & PM,PropertyDeclOrder & PO)1111   virtual void collectPropertiesToImplement(PropertyMap &PM,
1112                                             PropertyDeclOrder &PO) const {}
1113 
getAtStartLoc()1114   SourceLocation getAtStartLoc() const { return ObjCContainerDeclBits.AtStart; }
1115 
setAtStartLoc(SourceLocation Loc)1116   void setAtStartLoc(SourceLocation Loc) {
1117     ObjCContainerDeclBits.AtStart = Loc;
1118   }
1119 
1120   // Marks the end of the container.
getAtEndRange()1121   SourceRange getAtEndRange() const { return AtEnd; }
1122 
setAtEndRange(SourceRange atEnd)1123   void setAtEndRange(SourceRange atEnd) { AtEnd = atEnd; }
1124 
getSourceRange()1125   SourceRange getSourceRange() const override LLVM_READONLY {
1126     return SourceRange(getAtStartLoc(), getAtEndRange().getEnd());
1127   }
1128 
1129   // Implement isa/cast/dyncast/etc.
classof(const Decl * D)1130   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1131 
classofKind(Kind K)1132   static bool classofKind(Kind K) {
1133     return K >= firstObjCContainer &&
1134            K <= lastObjCContainer;
1135   }
1136 
castToDeclContext(const ObjCContainerDecl * D)1137   static DeclContext *castToDeclContext(const ObjCContainerDecl *D) {
1138     return static_cast<DeclContext *>(const_cast<ObjCContainerDecl*>(D));
1139   }
1140 
castFromDeclContext(const DeclContext * DC)1141   static ObjCContainerDecl *castFromDeclContext(const DeclContext *DC) {
1142     return static_cast<ObjCContainerDecl *>(const_cast<DeclContext*>(DC));
1143   }
1144 };
1145 
1146 /// Represents an ObjC class declaration.
1147 ///
1148 /// For example:
1149 ///
1150 /// \code
1151 ///   // MostPrimitive declares no super class (not particularly useful).
1152 ///   \@interface MostPrimitive
1153 ///     // no instance variables or methods.
1154 ///   \@end
1155 ///
1156 ///   // NSResponder inherits from NSObject & implements NSCoding (a protocol).
1157 ///   \@interface NSResponder : NSObject \<NSCoding>
1158 ///   { // instance variables are represented by ObjCIvarDecl.
1159 ///     id nextResponder; // nextResponder instance variable.
1160 ///   }
1161 ///   - (NSResponder *)nextResponder; // return a pointer to NSResponder.
1162 ///   - (void)mouseMoved:(NSEvent *)theEvent; // return void, takes a pointer
1163 ///   \@end                                    // to an NSEvent.
1164 /// \endcode
1165 ///
1166 ///   Unlike C/C++, forward class declarations are accomplished with \@class.
1167 ///   Unlike C/C++, \@class allows for a list of classes to be forward declared.
1168 ///   Unlike C++, ObjC is a single-rooted class model. In Cocoa, classes
1169 ///   typically inherit from NSObject (an exception is NSProxy).
1170 ///
1171 class ObjCInterfaceDecl : public ObjCContainerDecl
1172                         , public Redeclarable<ObjCInterfaceDecl> {
1173   friend class ASTContext;
1174 
1175   /// TypeForDecl - This indicates the Type object that represents this
1176   /// TypeDecl.  It is a cache maintained by ASTContext::getObjCInterfaceType
1177   mutable const Type *TypeForDecl = nullptr;
1178 
1179   struct DefinitionData {
1180     /// The definition of this class, for quick access from any
1181     /// declaration.
1182     ObjCInterfaceDecl *Definition = nullptr;
1183 
1184     /// When non-null, this is always an ObjCObjectType.
1185     TypeSourceInfo *SuperClassTInfo = nullptr;
1186 
1187     /// Protocols referenced in the \@interface  declaration
1188     ObjCProtocolList ReferencedProtocols;
1189 
1190     /// Protocols reference in both the \@interface and class extensions.
1191     ObjCList<ObjCProtocolDecl> AllReferencedProtocols;
1192 
1193     /// List of categories and class extensions defined for this class.
1194     ///
1195     /// Categories are stored as a linked list in the AST, since the categories
1196     /// and class extensions come long after the initial interface declaration,
1197     /// and we avoid dynamically-resized arrays in the AST wherever possible.
1198     ObjCCategoryDecl *CategoryList = nullptr;
1199 
1200     /// IvarList - List of all ivars defined by this class; including class
1201     /// extensions and implementation. This list is built lazily.
1202     ObjCIvarDecl *IvarList = nullptr;
1203 
1204     /// Indicates that the contents of this Objective-C class will be
1205     /// completed by the external AST source when required.
1206     mutable unsigned ExternallyCompleted : 1;
1207 
1208     /// Indicates that the ivar cache does not yet include ivars
1209     /// declared in the implementation.
1210     mutable unsigned IvarListMissingImplementation : 1;
1211 
1212     /// Indicates that this interface decl contains at least one initializer
1213     /// marked with the 'objc_designated_initializer' attribute.
1214     unsigned HasDesignatedInitializers : 1;
1215 
1216     enum InheritedDesignatedInitializersState {
1217       /// We didn't calculate whether the designated initializers should be
1218       /// inherited or not.
1219       IDI_Unknown = 0,
1220 
1221       /// Designated initializers are inherited for the super class.
1222       IDI_Inherited = 1,
1223 
1224       /// The class does not inherit designated initializers.
1225       IDI_NotInherited = 2
1226     };
1227 
1228     /// One of the \c InheritedDesignatedInitializersState enumeratos.
1229     mutable unsigned InheritedDesignatedInitializers : 2;
1230 
1231     /// The location of the last location in this declaration, before
1232     /// the properties/methods. For example, this will be the '>', '}', or
1233     /// identifier,
1234     SourceLocation EndLoc;
1235 
DefinitionDataDefinitionData1236     DefinitionData()
1237         : ExternallyCompleted(false), IvarListMissingImplementation(true),
1238           HasDesignatedInitializers(false),
1239           InheritedDesignatedInitializers(IDI_Unknown) {}
1240   };
1241 
1242   /// The type parameters associated with this class, if any.
1243   ObjCTypeParamList *TypeParamList = nullptr;
1244 
1245   /// Contains a pointer to the data associated with this class,
1246   /// which will be NULL if this class has not yet been defined.
1247   ///
1248   /// The bit indicates when we don't need to check for out-of-date
1249   /// declarations. It will be set unless modules are enabled.
1250   llvm::PointerIntPair<DefinitionData *, 1, bool> Data;
1251 
1252   ObjCInterfaceDecl(const ASTContext &C, DeclContext *DC, SourceLocation AtLoc,
1253                     IdentifierInfo *Id, ObjCTypeParamList *typeParamList,
1254                     SourceLocation CLoc, ObjCInterfaceDecl *PrevDecl,
1255                     bool IsInternal);
1256 
1257   void anchor() override;
1258 
1259   void LoadExternalDefinition() const;
1260 
data()1261   DefinitionData &data() const {
1262     assert(Data.getPointer() && "Declaration has no definition!");
1263     return *Data.getPointer();
1264   }
1265 
1266   /// Allocate the definition data for this class.
1267   void allocateDefinitionData();
1268 
1269   using redeclarable_base = Redeclarable<ObjCInterfaceDecl>;
1270 
getNextRedeclarationImpl()1271   ObjCInterfaceDecl *getNextRedeclarationImpl() override {
1272     return getNextRedeclaration();
1273   }
1274 
getPreviousDeclImpl()1275   ObjCInterfaceDecl *getPreviousDeclImpl() override {
1276     return getPreviousDecl();
1277   }
1278 
getMostRecentDeclImpl()1279   ObjCInterfaceDecl *getMostRecentDeclImpl() override {
1280     return getMostRecentDecl();
1281   }
1282 
1283 public:
1284   static ObjCInterfaceDecl *Create(const ASTContext &C, DeclContext *DC,
1285                                    SourceLocation atLoc,
1286                                    IdentifierInfo *Id,
1287                                    ObjCTypeParamList *typeParamList,
1288                                    ObjCInterfaceDecl *PrevDecl,
1289                                    SourceLocation ClassLoc = SourceLocation(),
1290                                    bool isInternal = false);
1291 
1292   static ObjCInterfaceDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
1293 
1294   /// Retrieve the type parameters of this class.
1295   ///
1296   /// This function looks for a type parameter list for the given
1297   /// class; if the class has been declared (with \c \@class) but not
1298   /// defined (with \c \@interface), it will search for a declaration that
1299   /// has type parameters, skipping any declarations that do not.
1300   ObjCTypeParamList *getTypeParamList() const;
1301 
1302   /// Set the type parameters of this class.
1303   ///
1304   /// This function is used by the AST importer, which must import the type
1305   /// parameters after creating their DeclContext to avoid loops.
1306   void setTypeParamList(ObjCTypeParamList *TPL);
1307 
1308   /// Retrieve the type parameters written on this particular declaration of
1309   /// the class.
getTypeParamListAsWritten()1310   ObjCTypeParamList *getTypeParamListAsWritten() const {
1311     return TypeParamList;
1312   }
1313 
getSourceRange()1314   SourceRange getSourceRange() const override LLVM_READONLY {
1315     if (isThisDeclarationADefinition())
1316       return ObjCContainerDecl::getSourceRange();
1317 
1318     return SourceRange(getAtStartLoc(), getLocation());
1319   }
1320 
1321   /// Indicate that this Objective-C class is complete, but that
1322   /// the external AST source will be responsible for filling in its contents
1323   /// when a complete class is required.
1324   void setExternallyCompleted();
1325 
1326   /// Indicate that this interface decl contains at least one initializer
1327   /// marked with the 'objc_designated_initializer' attribute.
1328   void setHasDesignatedInitializers();
1329 
1330   /// Returns true if this interface decl contains at least one initializer
1331   /// marked with the 'objc_designated_initializer' attribute.
1332   bool hasDesignatedInitializers() const;
1333 
1334   /// Returns true if this interface decl declares a designated initializer
1335   /// or it inherites one from its super class.
declaresOrInheritsDesignatedInitializers()1336   bool declaresOrInheritsDesignatedInitializers() const {
1337     return hasDesignatedInitializers() || inheritsDesignatedInitializers();
1338   }
1339 
getReferencedProtocols()1340   const ObjCProtocolList &getReferencedProtocols() const {
1341     assert(hasDefinition() && "Caller did not check for forward reference!");
1342     if (data().ExternallyCompleted)
1343       LoadExternalDefinition();
1344 
1345     return data().ReferencedProtocols;
1346   }
1347 
1348   ObjCImplementationDecl *getImplementation() const;
1349   void setImplementation(ObjCImplementationDecl *ImplD);
1350 
1351   ObjCCategoryDecl *FindCategoryDeclaration(IdentifierInfo *CategoryId) const;
1352 
1353   // Get the local instance/class method declared in a category.
1354   ObjCMethodDecl *getCategoryInstanceMethod(Selector Sel) const;
1355   ObjCMethodDecl *getCategoryClassMethod(Selector Sel) const;
1356 
getCategoryMethod(Selector Sel,bool isInstance)1357   ObjCMethodDecl *getCategoryMethod(Selector Sel, bool isInstance) const {
1358     return isInstance ? getCategoryInstanceMethod(Sel)
1359                       : getCategoryClassMethod(Sel);
1360   }
1361 
1362   using protocol_iterator = ObjCProtocolList::iterator;
1363   using protocol_range = llvm::iterator_range<protocol_iterator>;
1364 
protocols()1365   protocol_range protocols() const {
1366     return protocol_range(protocol_begin(), protocol_end());
1367   }
1368 
protocol_begin()1369   protocol_iterator protocol_begin() const {
1370     // FIXME: Should make sure no callers ever do this.
1371     if (!hasDefinition())
1372       return protocol_iterator();
1373 
1374     if (data().ExternallyCompleted)
1375       LoadExternalDefinition();
1376 
1377     return data().ReferencedProtocols.begin();
1378   }
1379 
protocol_end()1380   protocol_iterator protocol_end() const {
1381     // FIXME: Should make sure no callers ever do this.
1382     if (!hasDefinition())
1383       return protocol_iterator();
1384 
1385     if (data().ExternallyCompleted)
1386       LoadExternalDefinition();
1387 
1388     return data().ReferencedProtocols.end();
1389   }
1390 
1391   using protocol_loc_iterator = ObjCProtocolList::loc_iterator;
1392   using protocol_loc_range = llvm::iterator_range<protocol_loc_iterator>;
1393 
protocol_locs()1394   protocol_loc_range protocol_locs() const {
1395     return protocol_loc_range(protocol_loc_begin(), protocol_loc_end());
1396   }
1397 
protocol_loc_begin()1398   protocol_loc_iterator protocol_loc_begin() const {
1399     // FIXME: Should make sure no callers ever do this.
1400     if (!hasDefinition())
1401       return protocol_loc_iterator();
1402 
1403     if (data().ExternallyCompleted)
1404       LoadExternalDefinition();
1405 
1406     return data().ReferencedProtocols.loc_begin();
1407   }
1408 
protocol_loc_end()1409   protocol_loc_iterator protocol_loc_end() const {
1410     // FIXME: Should make sure no callers ever do this.
1411     if (!hasDefinition())
1412       return protocol_loc_iterator();
1413 
1414     if (data().ExternallyCompleted)
1415       LoadExternalDefinition();
1416 
1417     return data().ReferencedProtocols.loc_end();
1418   }
1419 
1420   using all_protocol_iterator = ObjCList<ObjCProtocolDecl>::iterator;
1421   using all_protocol_range = llvm::iterator_range<all_protocol_iterator>;
1422 
all_referenced_protocols()1423   all_protocol_range all_referenced_protocols() const {
1424     return all_protocol_range(all_referenced_protocol_begin(),
1425                               all_referenced_protocol_end());
1426   }
1427 
all_referenced_protocol_begin()1428   all_protocol_iterator all_referenced_protocol_begin() const {
1429     // FIXME: Should make sure no callers ever do this.
1430     if (!hasDefinition())
1431       return all_protocol_iterator();
1432 
1433     if (data().ExternallyCompleted)
1434       LoadExternalDefinition();
1435 
1436     return data().AllReferencedProtocols.empty()
1437              ? protocol_begin()
1438              : data().AllReferencedProtocols.begin();
1439   }
1440 
all_referenced_protocol_end()1441   all_protocol_iterator all_referenced_protocol_end() const {
1442     // FIXME: Should make sure no callers ever do this.
1443     if (!hasDefinition())
1444       return all_protocol_iterator();
1445 
1446     if (data().ExternallyCompleted)
1447       LoadExternalDefinition();
1448 
1449     return data().AllReferencedProtocols.empty()
1450              ? protocol_end()
1451              : data().AllReferencedProtocols.end();
1452   }
1453 
1454   using ivar_iterator = specific_decl_iterator<ObjCIvarDecl>;
1455   using ivar_range = llvm::iterator_range<specific_decl_iterator<ObjCIvarDecl>>;
1456 
ivars()1457   ivar_range ivars() const { return ivar_range(ivar_begin(), ivar_end()); }
1458 
ivar_begin()1459   ivar_iterator ivar_begin() const {
1460     if (const ObjCInterfaceDecl *Def = getDefinition())
1461       return ivar_iterator(Def->decls_begin());
1462 
1463     // FIXME: Should make sure no callers ever do this.
1464     return ivar_iterator();
1465   }
1466 
ivar_end()1467   ivar_iterator ivar_end() const {
1468     if (const ObjCInterfaceDecl *Def = getDefinition())
1469       return ivar_iterator(Def->decls_end());
1470 
1471     // FIXME: Should make sure no callers ever do this.
1472     return ivar_iterator();
1473   }
1474 
ivar_size()1475   unsigned ivar_size() const {
1476     return std::distance(ivar_begin(), ivar_end());
1477   }
1478 
ivar_empty()1479   bool ivar_empty() const { return ivar_begin() == ivar_end(); }
1480 
1481   ObjCIvarDecl *all_declared_ivar_begin();
all_declared_ivar_begin()1482   const ObjCIvarDecl *all_declared_ivar_begin() const {
1483     // Even though this modifies IvarList, it's conceptually const:
1484     // the ivar chain is essentially a cached property of ObjCInterfaceDecl.
1485     return const_cast<ObjCInterfaceDecl *>(this)->all_declared_ivar_begin();
1486   }
setIvarList(ObjCIvarDecl * ivar)1487   void setIvarList(ObjCIvarDecl *ivar) { data().IvarList = ivar; }
1488 
1489   /// setProtocolList - Set the list of protocols that this interface
1490   /// implements.
setProtocolList(ObjCProtocolDecl * const * List,unsigned Num,const SourceLocation * Locs,ASTContext & C)1491   void setProtocolList(ObjCProtocolDecl *const* List, unsigned Num,
1492                        const SourceLocation *Locs, ASTContext &C) {
1493     data().ReferencedProtocols.set(List, Num, Locs, C);
1494   }
1495 
1496   /// mergeClassExtensionProtocolList - Merge class extension's protocol list
1497   /// into the protocol list for this class.
1498   void mergeClassExtensionProtocolList(ObjCProtocolDecl *const* List,
1499                                        unsigned Num,
1500                                        ASTContext &C);
1501 
1502   /// Produce a name to be used for class's metadata. It comes either via
1503   /// objc_runtime_name attribute or class name.
1504   StringRef getObjCRuntimeNameAsString() const;
1505 
1506   /// Returns the designated initializers for the interface.
1507   ///
1508   /// If this declaration does not have methods marked as designated
1509   /// initializers then the interface inherits the designated initializers of
1510   /// its super class.
1511   void getDesignatedInitializers(
1512                   llvm::SmallVectorImpl<const ObjCMethodDecl *> &Methods) const;
1513 
1514   /// Returns true if the given selector is a designated initializer for the
1515   /// interface.
1516   ///
1517   /// If this declaration does not have methods marked as designated
1518   /// initializers then the interface inherits the designated initializers of
1519   /// its super class.
1520   ///
1521   /// \param InitMethod if non-null and the function returns true, it receives
1522   /// the method that was marked as a designated initializer.
1523   bool
1524   isDesignatedInitializer(Selector Sel,
1525                           const ObjCMethodDecl **InitMethod = nullptr) const;
1526 
1527   /// Determine whether this particular declaration of this class is
1528   /// actually also a definition.
isThisDeclarationADefinition()1529   bool isThisDeclarationADefinition() const {
1530     return getDefinition() == this;
1531   }
1532 
1533   /// Determine whether this class has been defined.
hasDefinition()1534   bool hasDefinition() const {
1535     // If the name of this class is out-of-date, bring it up-to-date, which
1536     // might bring in a definition.
1537     // Note: a null value indicates that we don't have a definition and that
1538     // modules are enabled.
1539     if (!Data.getOpaqueValue())
1540       getMostRecentDecl();
1541 
1542     return Data.getPointer();
1543   }
1544 
1545   /// Retrieve the definition of this class, or NULL if this class
1546   /// has been forward-declared (with \@class) but not yet defined (with
1547   /// \@interface).
getDefinition()1548   ObjCInterfaceDecl *getDefinition() {
1549     return hasDefinition()? Data.getPointer()->Definition : nullptr;
1550   }
1551 
1552   /// Retrieve the definition of this class, or NULL if this class
1553   /// has been forward-declared (with \@class) but not yet defined (with
1554   /// \@interface).
getDefinition()1555   const ObjCInterfaceDecl *getDefinition() const {
1556     return hasDefinition()? Data.getPointer()->Definition : nullptr;
1557   }
1558 
1559   /// Starts the definition of this Objective-C class, taking it from
1560   /// a forward declaration (\@class) to a definition (\@interface).
1561   void startDefinition();
1562 
1563   /// Retrieve the superclass type.
getSuperClassType()1564   const ObjCObjectType *getSuperClassType() const {
1565     if (TypeSourceInfo *TInfo = getSuperClassTInfo())
1566       return TInfo->getType()->castAs<ObjCObjectType>();
1567 
1568     return nullptr;
1569   }
1570 
1571   // Retrieve the type source information for the superclass.
getSuperClassTInfo()1572   TypeSourceInfo *getSuperClassTInfo() const {
1573     // FIXME: Should make sure no callers ever do this.
1574     if (!hasDefinition())
1575       return nullptr;
1576 
1577     if (data().ExternallyCompleted)
1578       LoadExternalDefinition();
1579 
1580     return data().SuperClassTInfo;
1581   }
1582 
1583   // Retrieve the declaration for the superclass of this class, which
1584   // does not include any type arguments that apply to the superclass.
1585   ObjCInterfaceDecl *getSuperClass() const;
1586 
setSuperClass(TypeSourceInfo * superClass)1587   void setSuperClass(TypeSourceInfo *superClass) {
1588     data().SuperClassTInfo = superClass;
1589   }
1590 
1591   /// Iterator that walks over the list of categories, filtering out
1592   /// those that do not meet specific criteria.
1593   ///
1594   /// This class template is used for the various permutations of category
1595   /// and extension iterators.
1596   template<bool (*Filter)(ObjCCategoryDecl *)>
1597   class filtered_category_iterator {
1598     ObjCCategoryDecl *Current = nullptr;
1599 
1600     void findAcceptableCategory();
1601 
1602   public:
1603     using value_type = ObjCCategoryDecl *;
1604     using reference = value_type;
1605     using pointer = value_type;
1606     using difference_type = std::ptrdiff_t;
1607     using iterator_category = std::input_iterator_tag;
1608 
1609     filtered_category_iterator() = default;
filtered_category_iterator(ObjCCategoryDecl * Current)1610     explicit filtered_category_iterator(ObjCCategoryDecl *Current)
1611         : Current(Current) {
1612       findAcceptableCategory();
1613     }
1614 
1615     reference operator*() const { return Current; }
1616     pointer operator->() const { return Current; }
1617 
1618     filtered_category_iterator &operator++();
1619 
1620     filtered_category_iterator operator++(int) {
1621       filtered_category_iterator Tmp = *this;
1622       ++(*this);
1623       return Tmp;
1624     }
1625 
1626     friend bool operator==(filtered_category_iterator X,
1627                            filtered_category_iterator Y) {
1628       return X.Current == Y.Current;
1629     }
1630 
1631     friend bool operator!=(filtered_category_iterator X,
1632                            filtered_category_iterator Y) {
1633       return X.Current != Y.Current;
1634     }
1635   };
1636 
1637 private:
1638   /// Test whether the given category is visible.
1639   ///
1640   /// Used in the \c visible_categories_iterator.
1641   static bool isVisibleCategory(ObjCCategoryDecl *Cat);
1642 
1643 public:
1644   /// Iterator that walks over the list of categories and extensions
1645   /// that are visible, i.e., not hidden in a non-imported submodule.
1646   using visible_categories_iterator =
1647       filtered_category_iterator<isVisibleCategory>;
1648 
1649   using visible_categories_range =
1650       llvm::iterator_range<visible_categories_iterator>;
1651 
visible_categories()1652   visible_categories_range visible_categories() const {
1653     return visible_categories_range(visible_categories_begin(),
1654                                     visible_categories_end());
1655   }
1656 
1657   /// Retrieve an iterator to the beginning of the visible-categories
1658   /// list.
visible_categories_begin()1659   visible_categories_iterator visible_categories_begin() const {
1660     return visible_categories_iterator(getCategoryListRaw());
1661   }
1662 
1663   /// Retrieve an iterator to the end of the visible-categories list.
visible_categories_end()1664   visible_categories_iterator visible_categories_end() const {
1665     return visible_categories_iterator();
1666   }
1667 
1668   /// Determine whether the visible-categories list is empty.
visible_categories_empty()1669   bool visible_categories_empty() const {
1670     return visible_categories_begin() == visible_categories_end();
1671   }
1672 
1673 private:
1674   /// Test whether the given category... is a category.
1675   ///
1676   /// Used in the \c known_categories_iterator.
isKnownCategory(ObjCCategoryDecl *)1677   static bool isKnownCategory(ObjCCategoryDecl *) { return true; }
1678 
1679 public:
1680   /// Iterator that walks over all of the known categories and
1681   /// extensions, including those that are hidden.
1682   using known_categories_iterator = filtered_category_iterator<isKnownCategory>;
1683   using known_categories_range =
1684      llvm::iterator_range<known_categories_iterator>;
1685 
known_categories()1686   known_categories_range known_categories() const {
1687     return known_categories_range(known_categories_begin(),
1688                                   known_categories_end());
1689   }
1690 
1691   /// Retrieve an iterator to the beginning of the known-categories
1692   /// list.
known_categories_begin()1693   known_categories_iterator known_categories_begin() const {
1694     return known_categories_iterator(getCategoryListRaw());
1695   }
1696 
1697   /// Retrieve an iterator to the end of the known-categories list.
known_categories_end()1698   known_categories_iterator known_categories_end() const {
1699     return known_categories_iterator();
1700   }
1701 
1702   /// Determine whether the known-categories list is empty.
known_categories_empty()1703   bool known_categories_empty() const {
1704     return known_categories_begin() == known_categories_end();
1705   }
1706 
1707 private:
1708   /// Test whether the given category is a visible extension.
1709   ///
1710   /// Used in the \c visible_extensions_iterator.
1711   static bool isVisibleExtension(ObjCCategoryDecl *Cat);
1712 
1713 public:
1714   /// Iterator that walks over all of the visible extensions, skipping
1715   /// any that are known but hidden.
1716   using visible_extensions_iterator =
1717       filtered_category_iterator<isVisibleExtension>;
1718 
1719   using visible_extensions_range =
1720       llvm::iterator_range<visible_extensions_iterator>;
1721 
visible_extensions()1722   visible_extensions_range visible_extensions() const {
1723     return visible_extensions_range(visible_extensions_begin(),
1724                                     visible_extensions_end());
1725   }
1726 
1727   /// Retrieve an iterator to the beginning of the visible-extensions
1728   /// list.
visible_extensions_begin()1729   visible_extensions_iterator visible_extensions_begin() const {
1730     return visible_extensions_iterator(getCategoryListRaw());
1731   }
1732 
1733   /// Retrieve an iterator to the end of the visible-extensions list.
visible_extensions_end()1734   visible_extensions_iterator visible_extensions_end() const {
1735     return visible_extensions_iterator();
1736   }
1737 
1738   /// Determine whether the visible-extensions list is empty.
visible_extensions_empty()1739   bool visible_extensions_empty() const {
1740     return visible_extensions_begin() == visible_extensions_end();
1741   }
1742 
1743 private:
1744   /// Test whether the given category is an extension.
1745   ///
1746   /// Used in the \c known_extensions_iterator.
1747   static bool isKnownExtension(ObjCCategoryDecl *Cat);
1748 
1749 public:
1750   friend class ASTDeclReader;
1751   friend class ASTDeclWriter;
1752   friend class ASTReader;
1753 
1754   /// Iterator that walks over all of the known extensions.
1755   using known_extensions_iterator =
1756       filtered_category_iterator<isKnownExtension>;
1757   using known_extensions_range =
1758       llvm::iterator_range<known_extensions_iterator>;
1759 
known_extensions()1760   known_extensions_range known_extensions() const {
1761     return known_extensions_range(known_extensions_begin(),
1762                                   known_extensions_end());
1763   }
1764 
1765   /// Retrieve an iterator to the beginning of the known-extensions
1766   /// list.
known_extensions_begin()1767   known_extensions_iterator known_extensions_begin() const {
1768     return known_extensions_iterator(getCategoryListRaw());
1769   }
1770 
1771   /// Retrieve an iterator to the end of the known-extensions list.
known_extensions_end()1772   known_extensions_iterator known_extensions_end() const {
1773     return known_extensions_iterator();
1774   }
1775 
1776   /// Determine whether the known-extensions list is empty.
known_extensions_empty()1777   bool known_extensions_empty() const {
1778     return known_extensions_begin() == known_extensions_end();
1779   }
1780 
1781   /// Retrieve the raw pointer to the start of the category/extension
1782   /// list.
getCategoryListRaw()1783   ObjCCategoryDecl* getCategoryListRaw() const {
1784     // FIXME: Should make sure no callers ever do this.
1785     if (!hasDefinition())
1786       return nullptr;
1787 
1788     if (data().ExternallyCompleted)
1789       LoadExternalDefinition();
1790 
1791     return data().CategoryList;
1792   }
1793 
1794   /// Set the raw pointer to the start of the category/extension
1795   /// list.
setCategoryListRaw(ObjCCategoryDecl * category)1796   void setCategoryListRaw(ObjCCategoryDecl *category) {
1797     data().CategoryList = category;
1798   }
1799 
1800   ObjCPropertyDecl
1801     *FindPropertyVisibleInPrimaryClass(IdentifierInfo *PropertyId,
1802                                        ObjCPropertyQueryKind QueryKind) const;
1803 
1804   void collectPropertiesToImplement(PropertyMap &PM,
1805                                     PropertyDeclOrder &PO) const override;
1806 
1807   /// isSuperClassOf - Return true if this class is the specified class or is a
1808   /// super class of the specified interface class.
isSuperClassOf(const ObjCInterfaceDecl * I)1809   bool isSuperClassOf(const ObjCInterfaceDecl *I) const {
1810     // If RHS is derived from LHS it is OK; else it is not OK.
1811     while (I != nullptr) {
1812       if (declaresSameEntity(this, I))
1813         return true;
1814 
1815       I = I->getSuperClass();
1816     }
1817     return false;
1818   }
1819 
1820   /// isArcWeakrefUnavailable - Checks for a class or one of its super classes
1821   /// to be incompatible with __weak references. Returns true if it is.
1822   bool isArcWeakrefUnavailable() const;
1823 
1824   /// isObjCRequiresPropertyDefs - Checks that a class or one of its super
1825   /// classes must not be auto-synthesized. Returns class decl. if it must not
1826   /// be; 0, otherwise.
1827   const ObjCInterfaceDecl *isObjCRequiresPropertyDefs() const;
1828 
1829   ObjCIvarDecl *lookupInstanceVariable(IdentifierInfo *IVarName,
1830                                        ObjCInterfaceDecl *&ClassDeclared);
lookupInstanceVariable(IdentifierInfo * IVarName)1831   ObjCIvarDecl *lookupInstanceVariable(IdentifierInfo *IVarName) {
1832     ObjCInterfaceDecl *ClassDeclared;
1833     return lookupInstanceVariable(IVarName, ClassDeclared);
1834   }
1835 
1836   ObjCProtocolDecl *lookupNestedProtocol(IdentifierInfo *Name);
1837 
1838   // Lookup a method. First, we search locally. If a method isn't
1839   // found, we search referenced protocols and class categories.
1840   ObjCMethodDecl *lookupMethod(Selector Sel, bool isInstance,
1841                                bool shallowCategoryLookup = false,
1842                                bool followSuper = true,
1843                                const ObjCCategoryDecl *C = nullptr) const;
1844 
1845   /// Lookup an instance method for a given selector.
lookupInstanceMethod(Selector Sel)1846   ObjCMethodDecl *lookupInstanceMethod(Selector Sel) const {
1847     return lookupMethod(Sel, true/*isInstance*/);
1848   }
1849 
1850   /// Lookup a class method for a given selector.
lookupClassMethod(Selector Sel)1851   ObjCMethodDecl *lookupClassMethod(Selector Sel) const {
1852     return lookupMethod(Sel, false/*isInstance*/);
1853   }
1854 
1855   ObjCInterfaceDecl *lookupInheritedClass(const IdentifierInfo *ICName);
1856 
1857   /// Lookup a method in the classes implementation hierarchy.
1858   ObjCMethodDecl *lookupPrivateMethod(const Selector &Sel,
1859                                       bool Instance=true) const;
1860 
lookupPrivateClassMethod(const Selector & Sel)1861   ObjCMethodDecl *lookupPrivateClassMethod(const Selector &Sel) {
1862     return lookupPrivateMethod(Sel, false);
1863   }
1864 
1865   /// Lookup a setter or getter in the class hierarchy,
1866   /// including in all categories except for category passed
1867   /// as argument.
lookupPropertyAccessor(const Selector Sel,const ObjCCategoryDecl * Cat,bool IsClassProperty)1868   ObjCMethodDecl *lookupPropertyAccessor(const Selector Sel,
1869                                          const ObjCCategoryDecl *Cat,
1870                                          bool IsClassProperty) const {
1871     return lookupMethod(Sel, !IsClassProperty/*isInstance*/,
1872                         false/*shallowCategoryLookup*/,
1873                         true /* followsSuper */,
1874                         Cat);
1875   }
1876 
getEndOfDefinitionLoc()1877   SourceLocation getEndOfDefinitionLoc() const {
1878     if (!hasDefinition())
1879       return getLocation();
1880 
1881     return data().EndLoc;
1882   }
1883 
setEndOfDefinitionLoc(SourceLocation LE)1884   void setEndOfDefinitionLoc(SourceLocation LE) { data().EndLoc = LE; }
1885 
1886   /// Retrieve the starting location of the superclass.
1887   SourceLocation getSuperClassLoc() const;
1888 
1889   /// isImplicitInterfaceDecl - check that this is an implicitly declared
1890   /// ObjCInterfaceDecl node. This is for legacy objective-c \@implementation
1891   /// declaration without an \@interface declaration.
isImplicitInterfaceDecl()1892   bool isImplicitInterfaceDecl() const {
1893     return hasDefinition() ? data().Definition->isImplicit() : isImplicit();
1894   }
1895 
1896   /// ClassImplementsProtocol - Checks that 'lProto' protocol
1897   /// has been implemented in IDecl class, its super class or categories (if
1898   /// lookupCategory is true).
1899   bool ClassImplementsProtocol(ObjCProtocolDecl *lProto,
1900                                bool lookupCategory,
1901                                bool RHSIsQualifiedID = false);
1902 
1903   using redecl_range = redeclarable_base::redecl_range;
1904   using redecl_iterator = redeclarable_base::redecl_iterator;
1905 
1906   using redeclarable_base::redecls_begin;
1907   using redeclarable_base::redecls_end;
1908   using redeclarable_base::redecls;
1909   using redeclarable_base::getPreviousDecl;
1910   using redeclarable_base::getMostRecentDecl;
1911   using redeclarable_base::isFirstDecl;
1912 
1913   /// Retrieves the canonical declaration of this Objective-C class.
getCanonicalDecl()1914   ObjCInterfaceDecl *getCanonicalDecl() override { return getFirstDecl(); }
getCanonicalDecl()1915   const ObjCInterfaceDecl *getCanonicalDecl() const { return getFirstDecl(); }
1916 
1917   // Low-level accessor
getTypeForDecl()1918   const Type *getTypeForDecl() const { return TypeForDecl; }
setTypeForDecl(const Type * TD)1919   void setTypeForDecl(const Type *TD) const { TypeForDecl = TD; }
1920 
classof(const Decl * D)1921   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classofKind(Kind K)1922   static bool classofKind(Kind K) { return K == ObjCInterface; }
1923 
1924 private:
1925   const ObjCInterfaceDecl *findInterfaceWithDesignatedInitializers() const;
1926   bool inheritsDesignatedInitializers() const;
1927 };
1928 
1929 /// ObjCIvarDecl - Represents an ObjC instance variable. In general, ObjC
1930 /// instance variables are identical to C. The only exception is Objective-C
1931 /// supports C++ style access control. For example:
1932 ///
1933 ///   \@interface IvarExample : NSObject
1934 ///   {
1935 ///     id defaultToProtected;
1936 ///   \@public:
1937 ///     id canBePublic; // same as C++.
1938 ///   \@protected:
1939 ///     id canBeProtected; // same as C++.
1940 ///   \@package:
1941 ///     id canBePackage; // framework visibility (not available in C++).
1942 ///   }
1943 ///
1944 class ObjCIvarDecl : public FieldDecl {
1945   void anchor() override;
1946 
1947 public:
1948   enum AccessControl {
1949     None, Private, Protected, Public, Package
1950   };
1951 
1952 private:
ObjCIvarDecl(ObjCContainerDecl * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,QualType T,TypeSourceInfo * TInfo,AccessControl ac,Expr * BW,bool synthesized)1953   ObjCIvarDecl(ObjCContainerDecl *DC, SourceLocation StartLoc,
1954                SourceLocation IdLoc, IdentifierInfo *Id,
1955                QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW,
1956                bool synthesized)
1957       : FieldDecl(ObjCIvar, DC, StartLoc, IdLoc, Id, T, TInfo, BW,
1958                   /*Mutable=*/false, /*HasInit=*/ICIS_NoInit),
1959         DeclAccess(ac), Synthesized(synthesized) {}
1960 
1961 public:
1962   static ObjCIvarDecl *Create(ASTContext &C, ObjCContainerDecl *DC,
1963                               SourceLocation StartLoc, SourceLocation IdLoc,
1964                               IdentifierInfo *Id, QualType T,
1965                               TypeSourceInfo *TInfo,
1966                               AccessControl ac, Expr *BW = nullptr,
1967                               bool synthesized=false);
1968 
1969   static ObjCIvarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1970 
1971   /// Return the class interface that this ivar is logically contained
1972   /// in; this is either the interface where the ivar was declared, or the
1973   /// interface the ivar is conceptually a part of in the case of synthesized
1974   /// ivars.
1975   const ObjCInterfaceDecl *getContainingInterface() const;
1976 
getNextIvar()1977   ObjCIvarDecl *getNextIvar() { return NextIvar; }
getNextIvar()1978   const ObjCIvarDecl *getNextIvar() const { return NextIvar; }
setNextIvar(ObjCIvarDecl * ivar)1979   void setNextIvar(ObjCIvarDecl *ivar) { NextIvar = ivar; }
1980 
setAccessControl(AccessControl ac)1981   void setAccessControl(AccessControl ac) { DeclAccess = ac; }
1982 
getAccessControl()1983   AccessControl getAccessControl() const { return AccessControl(DeclAccess); }
1984 
getCanonicalAccessControl()1985   AccessControl getCanonicalAccessControl() const {
1986     return DeclAccess == None ? Protected : AccessControl(DeclAccess);
1987   }
1988 
setSynthesize(bool synth)1989   void setSynthesize(bool synth) { Synthesized = synth; }
getSynthesize()1990   bool getSynthesize() const { return Synthesized; }
1991 
1992   /// Retrieve the type of this instance variable when viewed as a member of a
1993   /// specific object type.
1994   QualType getUsageType(QualType objectType) const;
1995 
1996   // Implement isa/cast/dyncast/etc.
classof(const Decl * D)1997   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classofKind(Kind K)1998   static bool classofKind(Kind K) { return K == ObjCIvar; }
1999 
2000 private:
2001   /// NextIvar - Next Ivar in the list of ivars declared in class; class's
2002   /// extensions and class's implementation
2003   ObjCIvarDecl *NextIvar = nullptr;
2004 
2005   // NOTE: VC++ treats enums as signed, avoid using the AccessControl enum
2006   unsigned DeclAccess : 3;
2007   unsigned Synthesized : 1;
2008 };
2009 
2010 /// Represents a field declaration created by an \@defs(...).
2011 class ObjCAtDefsFieldDecl : public FieldDecl {
ObjCAtDefsFieldDecl(DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,QualType T,Expr * BW)2012   ObjCAtDefsFieldDecl(DeclContext *DC, SourceLocation StartLoc,
2013                       SourceLocation IdLoc, IdentifierInfo *Id,
2014                       QualType T, Expr *BW)
2015       : FieldDecl(ObjCAtDefsField, DC, StartLoc, IdLoc, Id, T,
2016                   /*TInfo=*/nullptr, // FIXME: Do ObjCAtDefs have declarators ?
2017                   BW, /*Mutable=*/false, /*HasInit=*/ICIS_NoInit) {}
2018 
2019   void anchor() override;
2020 
2021 public:
2022   static ObjCAtDefsFieldDecl *Create(ASTContext &C, DeclContext *DC,
2023                                      SourceLocation StartLoc,
2024                                      SourceLocation IdLoc, IdentifierInfo *Id,
2025                                      QualType T, Expr *BW);
2026 
2027   static ObjCAtDefsFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2028 
2029   // Implement isa/cast/dyncast/etc.
classof(const Decl * D)2030   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classofKind(Kind K)2031   static bool classofKind(Kind K) { return K == ObjCAtDefsField; }
2032 };
2033 
2034 /// Represents an Objective-C protocol declaration.
2035 ///
2036 /// Objective-C protocols declare a pure abstract type (i.e., no instance
2037 /// variables are permitted).  Protocols originally drew inspiration from
2038 /// C++ pure virtual functions (a C++ feature with nice semantics and lousy
2039 /// syntax:-). Here is an example:
2040 ///
2041 /// \code
2042 /// \@protocol NSDraggingInfo <refproto1, refproto2>
2043 /// - (NSWindow *)draggingDestinationWindow;
2044 /// - (NSImage *)draggedImage;
2045 /// \@end
2046 /// \endcode
2047 ///
2048 /// This says that NSDraggingInfo requires two methods and requires everything
2049 /// that the two "referenced protocols" 'refproto1' and 'refproto2' require as
2050 /// well.
2051 ///
2052 /// \code
2053 /// \@interface ImplementsNSDraggingInfo : NSObject \<NSDraggingInfo>
2054 /// \@end
2055 /// \endcode
2056 ///
2057 /// ObjC protocols inspired Java interfaces. Unlike Java, ObjC classes and
2058 /// protocols are in distinct namespaces. For example, Cocoa defines both
2059 /// an NSObject protocol and class (which isn't allowed in Java). As a result,
2060 /// protocols are referenced using angle brackets as follows:
2061 ///
2062 /// id \<NSDraggingInfo> anyObjectThatImplementsNSDraggingInfo;
2063 class ObjCProtocolDecl : public ObjCContainerDecl,
2064                          public Redeclarable<ObjCProtocolDecl> {
2065   struct DefinitionData {
2066     // The declaration that defines this protocol.
2067     ObjCProtocolDecl *Definition;
2068 
2069     /// Referenced protocols
2070     ObjCProtocolList ReferencedProtocols;
2071   };
2072 
2073   /// Contains a pointer to the data associated with this class,
2074   /// which will be NULL if this class has not yet been defined.
2075   ///
2076   /// The bit indicates when we don't need to check for out-of-date
2077   /// declarations. It will be set unless modules are enabled.
2078   llvm::PointerIntPair<DefinitionData *, 1, bool> Data;
2079 
2080   ObjCProtocolDecl(ASTContext &C, DeclContext *DC, IdentifierInfo *Id,
2081                    SourceLocation nameLoc, SourceLocation atStartLoc,
2082                    ObjCProtocolDecl *PrevDecl);
2083 
2084   void anchor() override;
2085 
data()2086   DefinitionData &data() const {
2087     assert(Data.getPointer() && "Objective-C protocol has no definition!");
2088     return *Data.getPointer();
2089   }
2090 
2091   void allocateDefinitionData();
2092 
2093   using redeclarable_base = Redeclarable<ObjCProtocolDecl>;
2094 
getNextRedeclarationImpl()2095   ObjCProtocolDecl *getNextRedeclarationImpl() override {
2096     return getNextRedeclaration();
2097   }
2098 
getPreviousDeclImpl()2099   ObjCProtocolDecl *getPreviousDeclImpl() override {
2100     return getPreviousDecl();
2101   }
2102 
getMostRecentDeclImpl()2103   ObjCProtocolDecl *getMostRecentDeclImpl() override {
2104     return getMostRecentDecl();
2105   }
2106 
2107 public:
2108   friend class ASTDeclReader;
2109   friend class ASTDeclWriter;
2110   friend class ASTReader;
2111 
2112   static ObjCProtocolDecl *Create(ASTContext &C, DeclContext *DC,
2113                                   IdentifierInfo *Id,
2114                                   SourceLocation nameLoc,
2115                                   SourceLocation atStartLoc,
2116                                   ObjCProtocolDecl *PrevDecl);
2117 
2118   static ObjCProtocolDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2119 
getReferencedProtocols()2120   const ObjCProtocolList &getReferencedProtocols() const {
2121     assert(hasDefinition() && "No definition available!");
2122     return data().ReferencedProtocols;
2123   }
2124 
2125   using protocol_iterator = ObjCProtocolList::iterator;
2126   using protocol_range = llvm::iterator_range<protocol_iterator>;
2127 
protocols()2128   protocol_range protocols() const {
2129     return protocol_range(protocol_begin(), protocol_end());
2130   }
2131 
protocol_begin()2132   protocol_iterator protocol_begin() const {
2133     if (!hasDefinition())
2134       return protocol_iterator();
2135 
2136     return data().ReferencedProtocols.begin();
2137   }
2138 
protocol_end()2139   protocol_iterator protocol_end() const {
2140     if (!hasDefinition())
2141       return protocol_iterator();
2142 
2143     return data().ReferencedProtocols.end();
2144   }
2145 
2146   using protocol_loc_iterator = ObjCProtocolList::loc_iterator;
2147   using protocol_loc_range = llvm::iterator_range<protocol_loc_iterator>;
2148 
protocol_locs()2149   protocol_loc_range protocol_locs() const {
2150     return protocol_loc_range(protocol_loc_begin(), protocol_loc_end());
2151   }
2152 
protocol_loc_begin()2153   protocol_loc_iterator protocol_loc_begin() const {
2154     if (!hasDefinition())
2155       return protocol_loc_iterator();
2156 
2157     return data().ReferencedProtocols.loc_begin();
2158   }
2159 
protocol_loc_end()2160   protocol_loc_iterator protocol_loc_end() const {
2161     if (!hasDefinition())
2162       return protocol_loc_iterator();
2163 
2164     return data().ReferencedProtocols.loc_end();
2165   }
2166 
protocol_size()2167   unsigned protocol_size() const {
2168     if (!hasDefinition())
2169       return 0;
2170 
2171     return data().ReferencedProtocols.size();
2172   }
2173 
2174   /// setProtocolList - Set the list of protocols that this interface
2175   /// implements.
setProtocolList(ObjCProtocolDecl * const * List,unsigned Num,const SourceLocation * Locs,ASTContext & C)2176   void setProtocolList(ObjCProtocolDecl *const*List, unsigned Num,
2177                        const SourceLocation *Locs, ASTContext &C) {
2178     assert(hasDefinition() && "Protocol is not defined");
2179     data().ReferencedProtocols.set(List, Num, Locs, C);
2180   }
2181 
2182   ObjCProtocolDecl *lookupProtocolNamed(IdentifierInfo *PName);
2183 
2184   // Lookup a method. First, we search locally. If a method isn't
2185   // found, we search referenced protocols and class categories.
2186   ObjCMethodDecl *lookupMethod(Selector Sel, bool isInstance) const;
2187 
lookupInstanceMethod(Selector Sel)2188   ObjCMethodDecl *lookupInstanceMethod(Selector Sel) const {
2189     return lookupMethod(Sel, true/*isInstance*/);
2190   }
2191 
lookupClassMethod(Selector Sel)2192   ObjCMethodDecl *lookupClassMethod(Selector Sel) const {
2193     return lookupMethod(Sel, false/*isInstance*/);
2194   }
2195 
2196   /// Determine whether this protocol has a definition.
hasDefinition()2197   bool hasDefinition() const {
2198     // If the name of this protocol is out-of-date, bring it up-to-date, which
2199     // might bring in a definition.
2200     // Note: a null value indicates that we don't have a definition and that
2201     // modules are enabled.
2202     if (!Data.getOpaqueValue())
2203       getMostRecentDecl();
2204 
2205     return Data.getPointer();
2206   }
2207 
2208   /// Retrieve the definition of this protocol, if any.
getDefinition()2209   ObjCProtocolDecl *getDefinition() {
2210     return hasDefinition()? Data.getPointer()->Definition : nullptr;
2211   }
2212 
2213   /// Retrieve the definition of this protocol, if any.
getDefinition()2214   const ObjCProtocolDecl *getDefinition() const {
2215     return hasDefinition()? Data.getPointer()->Definition : nullptr;
2216   }
2217 
2218   /// Determine whether this particular declaration is also the
2219   /// definition.
isThisDeclarationADefinition()2220   bool isThisDeclarationADefinition() const {
2221     return getDefinition() == this;
2222   }
2223 
2224   /// Starts the definition of this Objective-C protocol.
2225   void startDefinition();
2226 
2227   /// Produce a name to be used for protocol's metadata. It comes either via
2228   /// objc_runtime_name attribute or protocol name.
2229   StringRef getObjCRuntimeNameAsString() const;
2230 
getSourceRange()2231   SourceRange getSourceRange() const override LLVM_READONLY {
2232     if (isThisDeclarationADefinition())
2233       return ObjCContainerDecl::getSourceRange();
2234 
2235     return SourceRange(getAtStartLoc(), getLocation());
2236   }
2237 
2238   using redecl_range = redeclarable_base::redecl_range;
2239   using redecl_iterator = redeclarable_base::redecl_iterator;
2240 
2241   using redeclarable_base::redecls_begin;
2242   using redeclarable_base::redecls_end;
2243   using redeclarable_base::redecls;
2244   using redeclarable_base::getPreviousDecl;
2245   using redeclarable_base::getMostRecentDecl;
2246   using redeclarable_base::isFirstDecl;
2247 
2248   /// Retrieves the canonical declaration of this Objective-C protocol.
getCanonicalDecl()2249   ObjCProtocolDecl *getCanonicalDecl() override { return getFirstDecl(); }
getCanonicalDecl()2250   const ObjCProtocolDecl *getCanonicalDecl() const { return getFirstDecl(); }
2251 
2252   void collectPropertiesToImplement(PropertyMap &PM,
2253                                     PropertyDeclOrder &PO) const override;
2254 
2255   void collectInheritedProtocolProperties(const ObjCPropertyDecl *Property,
2256                                           ProtocolPropertySet &PS,
2257                                           PropertyDeclOrder &PO) const;
2258 
classof(const Decl * D)2259   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classofKind(Kind K)2260   static bool classofKind(Kind K) { return K == ObjCProtocol; }
2261 };
2262 
2263 /// ObjCCategoryDecl - Represents a category declaration. A category allows
2264 /// you to add methods to an existing class (without subclassing or modifying
2265 /// the original class interface or implementation:-). Categories don't allow
2266 /// you to add instance data. The following example adds "myMethod" to all
2267 /// NSView's within a process:
2268 ///
2269 /// \@interface NSView (MyViewMethods)
2270 /// - myMethod;
2271 /// \@end
2272 ///
2273 /// Categories also allow you to split the implementation of a class across
2274 /// several files (a feature more naturally supported in C++).
2275 ///
2276 /// Categories were originally inspired by dynamic languages such as Common
2277 /// Lisp and Smalltalk.  More traditional class-based languages (C++, Java)
2278 /// don't support this level of dynamism, which is both powerful and dangerous.
2279 class ObjCCategoryDecl : public ObjCContainerDecl {
2280   /// Interface belonging to this category
2281   ObjCInterfaceDecl *ClassInterface;
2282 
2283   /// The type parameters associated with this category, if any.
2284   ObjCTypeParamList *TypeParamList = nullptr;
2285 
2286   /// referenced protocols in this category.
2287   ObjCProtocolList ReferencedProtocols;
2288 
2289   /// Next category belonging to this class.
2290   /// FIXME: this should not be a singly-linked list.  Move storage elsewhere.
2291   ObjCCategoryDecl *NextClassCategory = nullptr;
2292 
2293   /// The location of the category name in this declaration.
2294   SourceLocation CategoryNameLoc;
2295 
2296   /// class extension may have private ivars.
2297   SourceLocation IvarLBraceLoc;
2298   SourceLocation IvarRBraceLoc;
2299 
2300   ObjCCategoryDecl(DeclContext *DC, SourceLocation AtLoc,
2301                    SourceLocation ClassNameLoc, SourceLocation CategoryNameLoc,
2302                    IdentifierInfo *Id, ObjCInterfaceDecl *IDecl,
2303                    ObjCTypeParamList *typeParamList,
2304                    SourceLocation IvarLBraceLoc = SourceLocation(),
2305                    SourceLocation IvarRBraceLoc = SourceLocation());
2306 
2307   void anchor() override;
2308 
2309 public:
2310   friend class ASTDeclReader;
2311   friend class ASTDeclWriter;
2312 
2313   static ObjCCategoryDecl *Create(ASTContext &C, DeclContext *DC,
2314                                   SourceLocation AtLoc,
2315                                   SourceLocation ClassNameLoc,
2316                                   SourceLocation CategoryNameLoc,
2317                                   IdentifierInfo *Id,
2318                                   ObjCInterfaceDecl *IDecl,
2319                                   ObjCTypeParamList *typeParamList,
2320                                   SourceLocation IvarLBraceLoc=SourceLocation(),
2321                                   SourceLocation IvarRBraceLoc=SourceLocation());
2322   static ObjCCategoryDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2323 
getClassInterface()2324   ObjCInterfaceDecl *getClassInterface() { return ClassInterface; }
getClassInterface()2325   const ObjCInterfaceDecl *getClassInterface() const { return ClassInterface; }
2326 
2327   /// Retrieve the type parameter list associated with this category or
2328   /// extension.
getTypeParamList()2329   ObjCTypeParamList *getTypeParamList() const { return TypeParamList; }
2330 
2331   /// Set the type parameters of this category.
2332   ///
2333   /// This function is used by the AST importer, which must import the type
2334   /// parameters after creating their DeclContext to avoid loops.
2335   void setTypeParamList(ObjCTypeParamList *TPL);
2336 
2337 
2338   ObjCCategoryImplDecl *getImplementation() const;
2339   void setImplementation(ObjCCategoryImplDecl *ImplD);
2340 
2341   /// setProtocolList - Set the list of protocols that this interface
2342   /// implements.
setProtocolList(ObjCProtocolDecl * const * List,unsigned Num,const SourceLocation * Locs,ASTContext & C)2343   void setProtocolList(ObjCProtocolDecl *const*List, unsigned Num,
2344                        const SourceLocation *Locs, ASTContext &C) {
2345     ReferencedProtocols.set(List, Num, Locs, C);
2346   }
2347 
getReferencedProtocols()2348   const ObjCProtocolList &getReferencedProtocols() const {
2349     return ReferencedProtocols;
2350   }
2351 
2352   using protocol_iterator = ObjCProtocolList::iterator;
2353   using protocol_range = llvm::iterator_range<protocol_iterator>;
2354 
protocols()2355   protocol_range protocols() const {
2356     return protocol_range(protocol_begin(), protocol_end());
2357   }
2358 
protocol_begin()2359   protocol_iterator protocol_begin() const {
2360     return ReferencedProtocols.begin();
2361   }
2362 
protocol_end()2363   protocol_iterator protocol_end() const { return ReferencedProtocols.end(); }
protocol_size()2364   unsigned protocol_size() const { return ReferencedProtocols.size(); }
2365 
2366   using protocol_loc_iterator = ObjCProtocolList::loc_iterator;
2367   using protocol_loc_range = llvm::iterator_range<protocol_loc_iterator>;
2368 
protocol_locs()2369   protocol_loc_range protocol_locs() const {
2370     return protocol_loc_range(protocol_loc_begin(), protocol_loc_end());
2371   }
2372 
protocol_loc_begin()2373   protocol_loc_iterator protocol_loc_begin() const {
2374     return ReferencedProtocols.loc_begin();
2375   }
2376 
protocol_loc_end()2377   protocol_loc_iterator protocol_loc_end() const {
2378     return ReferencedProtocols.loc_end();
2379   }
2380 
getNextClassCategory()2381   ObjCCategoryDecl *getNextClassCategory() const { return NextClassCategory; }
2382 
2383   /// Retrieve the pointer to the next stored category (or extension),
2384   /// which may be hidden.
getNextClassCategoryRaw()2385   ObjCCategoryDecl *getNextClassCategoryRaw() const {
2386     return NextClassCategory;
2387   }
2388 
IsClassExtension()2389   bool IsClassExtension() const { return getIdentifier() == nullptr; }
2390 
2391   using ivar_iterator = specific_decl_iterator<ObjCIvarDecl>;
2392   using ivar_range = llvm::iterator_range<specific_decl_iterator<ObjCIvarDecl>>;
2393 
ivars()2394   ivar_range ivars() const { return ivar_range(ivar_begin(), ivar_end()); }
2395 
ivar_begin()2396   ivar_iterator ivar_begin() const {
2397     return ivar_iterator(decls_begin());
2398   }
2399 
ivar_end()2400   ivar_iterator ivar_end() const {
2401     return ivar_iterator(decls_end());
2402   }
2403 
ivar_size()2404   unsigned ivar_size() const {
2405     return std::distance(ivar_begin(), ivar_end());
2406   }
2407 
ivar_empty()2408   bool ivar_empty() const {
2409     return ivar_begin() == ivar_end();
2410   }
2411 
getCategoryNameLoc()2412   SourceLocation getCategoryNameLoc() const { return CategoryNameLoc; }
setCategoryNameLoc(SourceLocation Loc)2413   void setCategoryNameLoc(SourceLocation Loc) { CategoryNameLoc = Loc; }
2414 
setIvarLBraceLoc(SourceLocation Loc)2415   void setIvarLBraceLoc(SourceLocation Loc) { IvarLBraceLoc = Loc; }
getIvarLBraceLoc()2416   SourceLocation getIvarLBraceLoc() const { return IvarLBraceLoc; }
setIvarRBraceLoc(SourceLocation Loc)2417   void setIvarRBraceLoc(SourceLocation Loc) { IvarRBraceLoc = Loc; }
getIvarRBraceLoc()2418   SourceLocation getIvarRBraceLoc() const { return IvarRBraceLoc; }
2419 
classof(const Decl * D)2420   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classofKind(Kind K)2421   static bool classofKind(Kind K) { return K == ObjCCategory; }
2422 };
2423 
2424 class ObjCImplDecl : public ObjCContainerDecl {
2425   /// Class interface for this class/category implementation
2426   ObjCInterfaceDecl *ClassInterface;
2427 
2428   void anchor() override;
2429 
2430 protected:
ObjCImplDecl(Kind DK,DeclContext * DC,ObjCInterfaceDecl * classInterface,IdentifierInfo * Id,SourceLocation nameLoc,SourceLocation atStartLoc)2431   ObjCImplDecl(Kind DK, DeclContext *DC,
2432                ObjCInterfaceDecl *classInterface,
2433                IdentifierInfo *Id,
2434                SourceLocation nameLoc, SourceLocation atStartLoc)
2435       : ObjCContainerDecl(DK, DC, Id, nameLoc, atStartLoc),
2436         ClassInterface(classInterface) {}
2437 
2438 public:
getClassInterface()2439   const ObjCInterfaceDecl *getClassInterface() const { return ClassInterface; }
getClassInterface()2440   ObjCInterfaceDecl *getClassInterface() { return ClassInterface; }
2441   void setClassInterface(ObjCInterfaceDecl *IFace);
2442 
addInstanceMethod(ObjCMethodDecl * method)2443   void addInstanceMethod(ObjCMethodDecl *method) {
2444     // FIXME: Context should be set correctly before we get here.
2445     method->setLexicalDeclContext(this);
2446     addDecl(method);
2447   }
2448 
addClassMethod(ObjCMethodDecl * method)2449   void addClassMethod(ObjCMethodDecl *method) {
2450     // FIXME: Context should be set correctly before we get here.
2451     method->setLexicalDeclContext(this);
2452     addDecl(method);
2453   }
2454 
2455   void addPropertyImplementation(ObjCPropertyImplDecl *property);
2456 
2457   ObjCPropertyImplDecl *FindPropertyImplDecl(IdentifierInfo *propertyId,
2458                             ObjCPropertyQueryKind queryKind) const;
2459   ObjCPropertyImplDecl *FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const;
2460 
2461   // Iterator access to properties.
2462   using propimpl_iterator = specific_decl_iterator<ObjCPropertyImplDecl>;
2463   using propimpl_range =
2464       llvm::iterator_range<specific_decl_iterator<ObjCPropertyImplDecl>>;
2465 
property_impls()2466   propimpl_range property_impls() const {
2467     return propimpl_range(propimpl_begin(), propimpl_end());
2468   }
2469 
propimpl_begin()2470   propimpl_iterator propimpl_begin() const {
2471     return propimpl_iterator(decls_begin());
2472   }
2473 
propimpl_end()2474   propimpl_iterator propimpl_end() const {
2475     return propimpl_iterator(decls_end());
2476   }
2477 
classof(const Decl * D)2478   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2479 
classofKind(Kind K)2480   static bool classofKind(Kind K) {
2481     return K >= firstObjCImpl && K <= lastObjCImpl;
2482   }
2483 };
2484 
2485 /// ObjCCategoryImplDecl - An object of this class encapsulates a category
2486 /// \@implementation declaration. If a category class has declaration of a
2487 /// property, its implementation must be specified in the category's
2488 /// \@implementation declaration. Example:
2489 /// \@interface I \@end
2490 /// \@interface I(CATEGORY)
2491 ///    \@property int p1, d1;
2492 /// \@end
2493 /// \@implementation I(CATEGORY)
2494 ///  \@dynamic p1,d1;
2495 /// \@end
2496 ///
2497 /// ObjCCategoryImplDecl
2498 class ObjCCategoryImplDecl : public ObjCImplDecl {
2499   // Category name location
2500   SourceLocation CategoryNameLoc;
2501 
ObjCCategoryImplDecl(DeclContext * DC,IdentifierInfo * Id,ObjCInterfaceDecl * classInterface,SourceLocation nameLoc,SourceLocation atStartLoc,SourceLocation CategoryNameLoc)2502   ObjCCategoryImplDecl(DeclContext *DC, IdentifierInfo *Id,
2503                        ObjCInterfaceDecl *classInterface,
2504                        SourceLocation nameLoc, SourceLocation atStartLoc,
2505                        SourceLocation CategoryNameLoc)
2506       : ObjCImplDecl(ObjCCategoryImpl, DC, classInterface, Id,
2507                      nameLoc, atStartLoc),
2508         CategoryNameLoc(CategoryNameLoc) {}
2509 
2510   void anchor() override;
2511 
2512 public:
2513   friend class ASTDeclReader;
2514   friend class ASTDeclWriter;
2515 
2516   static ObjCCategoryImplDecl *Create(ASTContext &C, DeclContext *DC,
2517                                       IdentifierInfo *Id,
2518                                       ObjCInterfaceDecl *classInterface,
2519                                       SourceLocation nameLoc,
2520                                       SourceLocation atStartLoc,
2521                                       SourceLocation CategoryNameLoc);
2522   static ObjCCategoryImplDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2523 
2524   ObjCCategoryDecl *getCategoryDecl() const;
2525 
getCategoryNameLoc()2526   SourceLocation getCategoryNameLoc() const { return CategoryNameLoc; }
2527 
classof(const Decl * D)2528   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classofKind(Kind K)2529   static bool classofKind(Kind K) { return K == ObjCCategoryImpl;}
2530 };
2531 
2532 raw_ostream &operator<<(raw_ostream &OS, const ObjCCategoryImplDecl &CID);
2533 
2534 /// ObjCImplementationDecl - Represents a class definition - this is where
2535 /// method definitions are specified. For example:
2536 ///
2537 /// @code
2538 /// \@implementation MyClass
2539 /// - (void)myMethod { /* do something */ }
2540 /// \@end
2541 /// @endcode
2542 ///
2543 /// In a non-fragile runtime, instance variables can appear in the class
2544 /// interface, class extensions (nameless categories), and in the implementation
2545 /// itself, as well as being synthesized as backing storage for properties.
2546 ///
2547 /// In a fragile runtime, instance variables are specified in the class
2548 /// interface, \em not in the implementation. Nevertheless (for legacy reasons),
2549 /// we allow instance variables to be specified in the implementation. When
2550 /// specified, they need to be \em identical to the interface.
2551 class ObjCImplementationDecl : public ObjCImplDecl {
2552   /// Implementation Class's super class.
2553   ObjCInterfaceDecl *SuperClass;
2554   SourceLocation SuperLoc;
2555 
2556   /// \@implementation may have private ivars.
2557   SourceLocation IvarLBraceLoc;
2558   SourceLocation IvarRBraceLoc;
2559 
2560   /// Support for ivar initialization.
2561   /// The arguments used to initialize the ivars
2562   LazyCXXCtorInitializersPtr IvarInitializers;
2563   unsigned NumIvarInitializers = 0;
2564 
2565   /// Do the ivars of this class require initialization other than
2566   /// zero-initialization?
2567   bool HasNonZeroConstructors : 1;
2568 
2569   /// Do the ivars of this class require non-trivial destruction?
2570   bool HasDestructors : 1;
2571 
2572   ObjCImplementationDecl(DeclContext *DC,
2573                          ObjCInterfaceDecl *classInterface,
2574                          ObjCInterfaceDecl *superDecl,
2575                          SourceLocation nameLoc, SourceLocation atStartLoc,
2576                          SourceLocation superLoc = SourceLocation(),
2577                          SourceLocation IvarLBraceLoc=SourceLocation(),
2578                          SourceLocation IvarRBraceLoc=SourceLocation())
2579       : ObjCImplDecl(ObjCImplementation, DC, classInterface,
2580                      classInterface ? classInterface->getIdentifier()
2581                                     : nullptr,
2582                      nameLoc, atStartLoc),
2583          SuperClass(superDecl), SuperLoc(superLoc),
2584          IvarLBraceLoc(IvarLBraceLoc), IvarRBraceLoc(IvarRBraceLoc),
2585          HasNonZeroConstructors(false), HasDestructors(false) {}
2586 
2587   void anchor() override;
2588 
2589 public:
2590   friend class ASTDeclReader;
2591   friend class ASTDeclWriter;
2592 
2593   static ObjCImplementationDecl *Create(ASTContext &C, DeclContext *DC,
2594                                         ObjCInterfaceDecl *classInterface,
2595                                         ObjCInterfaceDecl *superDecl,
2596                                         SourceLocation nameLoc,
2597                                         SourceLocation atStartLoc,
2598                                      SourceLocation superLoc = SourceLocation(),
2599                                         SourceLocation IvarLBraceLoc=SourceLocation(),
2600                                         SourceLocation IvarRBraceLoc=SourceLocation());
2601 
2602   static ObjCImplementationDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2603 
2604   /// init_iterator - Iterates through the ivar initializer list.
2605   using init_iterator = CXXCtorInitializer **;
2606 
2607   /// init_const_iterator - Iterates through the ivar initializer list.
2608   using init_const_iterator = CXXCtorInitializer * const *;
2609 
2610   using init_range = llvm::iterator_range<init_iterator>;
2611   using init_const_range = llvm::iterator_range<init_const_iterator>;
2612 
inits()2613   init_range inits() { return init_range(init_begin(), init_end()); }
2614 
inits()2615   init_const_range inits() const {
2616     return init_const_range(init_begin(), init_end());
2617   }
2618 
2619   /// init_begin() - Retrieve an iterator to the first initializer.
init_begin()2620   init_iterator init_begin() {
2621     const auto *ConstThis = this;
2622     return const_cast<init_iterator>(ConstThis->init_begin());
2623   }
2624 
2625   /// begin() - Retrieve an iterator to the first initializer.
2626   init_const_iterator init_begin() const;
2627 
2628   /// init_end() - Retrieve an iterator past the last initializer.
init_end()2629   init_iterator       init_end()       {
2630     return init_begin() + NumIvarInitializers;
2631   }
2632 
2633   /// end() - Retrieve an iterator past the last initializer.
init_end()2634   init_const_iterator init_end() const {
2635     return init_begin() + NumIvarInitializers;
2636   }
2637 
2638   /// getNumArgs - Number of ivars which must be initialized.
getNumIvarInitializers()2639   unsigned getNumIvarInitializers() const {
2640     return NumIvarInitializers;
2641   }
2642 
setNumIvarInitializers(unsigned numNumIvarInitializers)2643   void setNumIvarInitializers(unsigned numNumIvarInitializers) {
2644     NumIvarInitializers = numNumIvarInitializers;
2645   }
2646 
2647   void setIvarInitializers(ASTContext &C,
2648                            CXXCtorInitializer ** initializers,
2649                            unsigned numInitializers);
2650 
2651   /// Do any of the ivars of this class (not counting its base classes)
2652   /// require construction other than zero-initialization?
hasNonZeroConstructors()2653   bool hasNonZeroConstructors() const { return HasNonZeroConstructors; }
setHasNonZeroConstructors(bool val)2654   void setHasNonZeroConstructors(bool val) { HasNonZeroConstructors = val; }
2655 
2656   /// Do any of the ivars of this class (not counting its base classes)
2657   /// require non-trivial destruction?
hasDestructors()2658   bool hasDestructors() const { return HasDestructors; }
setHasDestructors(bool val)2659   void setHasDestructors(bool val) { HasDestructors = val; }
2660 
2661   /// getIdentifier - Get the identifier that names the class
2662   /// interface associated with this implementation.
getIdentifier()2663   IdentifierInfo *getIdentifier() const {
2664     return getClassInterface()->getIdentifier();
2665   }
2666 
2667   /// getName - Get the name of identifier for the class interface associated
2668   /// with this implementation as a StringRef.
2669   //
2670   // FIXME: This is a bad API, we are hiding NamedDecl::getName with a different
2671   // meaning.
getName()2672   StringRef getName() const {
2673     assert(getIdentifier() && "Name is not a simple identifier");
2674     return getIdentifier()->getName();
2675   }
2676 
2677   /// Get the name of the class associated with this interface.
2678   //
2679   // FIXME: Move to StringRef API.
getNameAsString()2680   std::string getNameAsString() const {
2681     return getName();
2682   }
2683 
2684   /// Produce a name to be used for class's metadata. It comes either via
2685   /// class's objc_runtime_name attribute or class name.
2686   StringRef getObjCRuntimeNameAsString() const;
2687 
getSuperClass()2688   const ObjCInterfaceDecl *getSuperClass() const { return SuperClass; }
getSuperClass()2689   ObjCInterfaceDecl *getSuperClass() { return SuperClass; }
getSuperClassLoc()2690   SourceLocation getSuperClassLoc() const { return SuperLoc; }
2691 
setSuperClass(ObjCInterfaceDecl * superCls)2692   void setSuperClass(ObjCInterfaceDecl * superCls) { SuperClass = superCls; }
2693 
setIvarLBraceLoc(SourceLocation Loc)2694   void setIvarLBraceLoc(SourceLocation Loc) { IvarLBraceLoc = Loc; }
getIvarLBraceLoc()2695   SourceLocation getIvarLBraceLoc() const { return IvarLBraceLoc; }
setIvarRBraceLoc(SourceLocation Loc)2696   void setIvarRBraceLoc(SourceLocation Loc) { IvarRBraceLoc = Loc; }
getIvarRBraceLoc()2697   SourceLocation getIvarRBraceLoc() const { return IvarRBraceLoc; }
2698 
2699   using ivar_iterator = specific_decl_iterator<ObjCIvarDecl>;
2700   using ivar_range = llvm::iterator_range<specific_decl_iterator<ObjCIvarDecl>>;
2701 
ivars()2702   ivar_range ivars() const { return ivar_range(ivar_begin(), ivar_end()); }
2703 
ivar_begin()2704   ivar_iterator ivar_begin() const {
2705     return ivar_iterator(decls_begin());
2706   }
2707 
ivar_end()2708   ivar_iterator ivar_end() const {
2709     return ivar_iterator(decls_end());
2710   }
2711 
ivar_size()2712   unsigned ivar_size() const {
2713     return std::distance(ivar_begin(), ivar_end());
2714   }
2715 
ivar_empty()2716   bool ivar_empty() const {
2717     return ivar_begin() == ivar_end();
2718   }
2719 
classof(const Decl * D)2720   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classofKind(Kind K)2721   static bool classofKind(Kind K) { return K == ObjCImplementation; }
2722 };
2723 
2724 raw_ostream &operator<<(raw_ostream &OS, const ObjCImplementationDecl &ID);
2725 
2726 /// ObjCCompatibleAliasDecl - Represents alias of a class. This alias is
2727 /// declared as \@compatibility_alias alias class.
2728 class ObjCCompatibleAliasDecl : public NamedDecl {
2729   /// Class that this is an alias of.
2730   ObjCInterfaceDecl *AliasedClass;
2731 
ObjCCompatibleAliasDecl(DeclContext * DC,SourceLocation L,IdentifierInfo * Id,ObjCInterfaceDecl * aliasedClass)2732   ObjCCompatibleAliasDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
2733                           ObjCInterfaceDecl* aliasedClass)
2734       : NamedDecl(ObjCCompatibleAlias, DC, L, Id), AliasedClass(aliasedClass) {}
2735 
2736   void anchor() override;
2737 
2738 public:
2739   static ObjCCompatibleAliasDecl *Create(ASTContext &C, DeclContext *DC,
2740                                          SourceLocation L, IdentifierInfo *Id,
2741                                          ObjCInterfaceDecl* aliasedClass);
2742 
2743   static ObjCCompatibleAliasDecl *CreateDeserialized(ASTContext &C,
2744                                                      unsigned ID);
2745 
getClassInterface()2746   const ObjCInterfaceDecl *getClassInterface() const { return AliasedClass; }
getClassInterface()2747   ObjCInterfaceDecl *getClassInterface() { return AliasedClass; }
setClassInterface(ObjCInterfaceDecl * D)2748   void setClassInterface(ObjCInterfaceDecl *D) { AliasedClass = D; }
2749 
classof(const Decl * D)2750   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classofKind(Kind K)2751   static bool classofKind(Kind K) { return K == ObjCCompatibleAlias; }
2752 };
2753 
2754 /// ObjCPropertyImplDecl - Represents implementation declaration of a property
2755 /// in a class or category implementation block. For example:
2756 /// \@synthesize prop1 = ivar1;
2757 ///
2758 class ObjCPropertyImplDecl : public Decl {
2759 public:
2760   enum Kind {
2761     Synthesize,
2762     Dynamic
2763   };
2764 
2765 private:
2766   SourceLocation AtLoc;   // location of \@synthesize or \@dynamic
2767 
2768   /// For \@synthesize, the location of the ivar, if it was written in
2769   /// the source code.
2770   ///
2771   /// \code
2772   /// \@synthesize int a = b
2773   /// \endcode
2774   SourceLocation IvarLoc;
2775 
2776   /// Property declaration being implemented
2777   ObjCPropertyDecl *PropertyDecl;
2778 
2779   /// Null for \@dynamic. Required for \@synthesize.
2780   ObjCIvarDecl *PropertyIvarDecl;
2781 
2782   /// Null for \@dynamic. Non-null if property must be copy-constructed in
2783   /// getter.
2784   Expr *GetterCXXConstructor = nullptr;
2785 
2786   /// Null for \@dynamic. Non-null if property has assignment operator to call
2787   /// in Setter synthesis.
2788   Expr *SetterCXXAssignment = nullptr;
2789 
ObjCPropertyImplDecl(DeclContext * DC,SourceLocation atLoc,SourceLocation L,ObjCPropertyDecl * property,Kind PK,ObjCIvarDecl * ivarDecl,SourceLocation ivarLoc)2790   ObjCPropertyImplDecl(DeclContext *DC, SourceLocation atLoc, SourceLocation L,
2791                        ObjCPropertyDecl *property,
2792                        Kind PK,
2793                        ObjCIvarDecl *ivarDecl,
2794                        SourceLocation ivarLoc)
2795       : Decl(ObjCPropertyImpl, DC, L), AtLoc(atLoc),
2796         IvarLoc(ivarLoc), PropertyDecl(property), PropertyIvarDecl(ivarDecl) {
2797     assert(PK == Dynamic || PropertyIvarDecl);
2798   }
2799 
2800 public:
2801   friend class ASTDeclReader;
2802 
2803   static ObjCPropertyImplDecl *Create(ASTContext &C, DeclContext *DC,
2804                                       SourceLocation atLoc, SourceLocation L,
2805                                       ObjCPropertyDecl *property,
2806                                       Kind PK,
2807                                       ObjCIvarDecl *ivarDecl,
2808                                       SourceLocation ivarLoc);
2809 
2810   static ObjCPropertyImplDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2811 
2812   SourceRange getSourceRange() const override LLVM_READONLY;
2813 
getBeginLoc()2814   SourceLocation getBeginLoc() const LLVM_READONLY { return AtLoc; }
setAtLoc(SourceLocation Loc)2815   void setAtLoc(SourceLocation Loc) { AtLoc = Loc; }
2816 
getPropertyDecl()2817   ObjCPropertyDecl *getPropertyDecl() const {
2818     return PropertyDecl;
2819   }
setPropertyDecl(ObjCPropertyDecl * Prop)2820   void setPropertyDecl(ObjCPropertyDecl *Prop) { PropertyDecl = Prop; }
2821 
getPropertyImplementation()2822   Kind getPropertyImplementation() const {
2823     return PropertyIvarDecl ? Synthesize : Dynamic;
2824   }
2825 
getPropertyIvarDecl()2826   ObjCIvarDecl *getPropertyIvarDecl() const {
2827     return PropertyIvarDecl;
2828   }
getPropertyIvarDeclLoc()2829   SourceLocation getPropertyIvarDeclLoc() const { return IvarLoc; }
2830 
setPropertyIvarDecl(ObjCIvarDecl * Ivar,SourceLocation IvarLoc)2831   void setPropertyIvarDecl(ObjCIvarDecl *Ivar,
2832                            SourceLocation IvarLoc) {
2833     PropertyIvarDecl = Ivar;
2834     this->IvarLoc = IvarLoc;
2835   }
2836 
2837   /// For \@synthesize, returns true if an ivar name was explicitly
2838   /// specified.
2839   ///
2840   /// \code
2841   /// \@synthesize int a = b; // true
2842   /// \@synthesize int a; // false
2843   /// \endcode
isIvarNameSpecified()2844   bool isIvarNameSpecified() const {
2845     return IvarLoc.isValid() && IvarLoc != getLocation();
2846   }
2847 
getGetterCXXConstructor()2848   Expr *getGetterCXXConstructor() const {
2849     return GetterCXXConstructor;
2850   }
2851 
setGetterCXXConstructor(Expr * getterCXXConstructor)2852   void setGetterCXXConstructor(Expr *getterCXXConstructor) {
2853     GetterCXXConstructor = getterCXXConstructor;
2854   }
2855 
getSetterCXXAssignment()2856   Expr *getSetterCXXAssignment() const {
2857     return SetterCXXAssignment;
2858   }
2859 
setSetterCXXAssignment(Expr * setterCXXAssignment)2860   void setSetterCXXAssignment(Expr *setterCXXAssignment) {
2861     SetterCXXAssignment = setterCXXAssignment;
2862   }
2863 
classof(const Decl * D)2864   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
classofKind(Decl::Kind K)2865   static bool classofKind(Decl::Kind K) { return K == ObjCPropertyImpl; }
2866 };
2867 
2868 template<bool (*Filter)(ObjCCategoryDecl *)>
2869 void
2870 ObjCInterfaceDecl::filtered_category_iterator<Filter>::
findAcceptableCategory()2871 findAcceptableCategory() {
2872   while (Current && !Filter(Current))
2873     Current = Current->getNextClassCategoryRaw();
2874 }
2875 
2876 template<bool (*Filter)(ObjCCategoryDecl *)>
2877 inline ObjCInterfaceDecl::filtered_category_iterator<Filter> &
2878 ObjCInterfaceDecl::filtered_category_iterator<Filter>::operator++() {
2879   Current = Current->getNextClassCategoryRaw();
2880   findAcceptableCategory();
2881   return *this;
2882 }
2883 
isVisibleCategory(ObjCCategoryDecl * Cat)2884 inline bool ObjCInterfaceDecl::isVisibleCategory(ObjCCategoryDecl *Cat) {
2885   return !Cat->isHidden();
2886 }
2887 
isVisibleExtension(ObjCCategoryDecl * Cat)2888 inline bool ObjCInterfaceDecl::isVisibleExtension(ObjCCategoryDecl *Cat) {
2889   return Cat->IsClassExtension() && !Cat->isHidden();
2890 }
2891 
isKnownExtension(ObjCCategoryDecl * Cat)2892 inline bool ObjCInterfaceDecl::isKnownExtension(ObjCCategoryDecl *Cat) {
2893   return Cat->IsClassExtension();
2894 }
2895 
2896 } // namespace clang
2897 
2898 #endif // LLVM_CLANG_AST_DECLOBJC_H
2899