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