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