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