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