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