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