xref: /freebsd/contrib/llvm-project/clang/lib/CodeGen/CGObjCGNU.cpp (revision c8e7f78a3d28ff6e6223ed136ada8e1e2f34965e)
1 //===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This provides Objective-C code generation targeting the GNU runtime.  The
10 // class in this file generates structures used by the GNU Objective-C runtime
11 // library.  These structures are defined in objc/objc.h and objc/objc-api.h in
12 // the GNU runtime distribution.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "CGCXXABI.h"
17 #include "CGCleanup.h"
18 #include "CGObjCRuntime.h"
19 #include "CodeGenFunction.h"
20 #include "CodeGenModule.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/Attr.h"
23 #include "clang/AST/Decl.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/RecordLayout.h"
26 #include "clang/AST/StmtObjC.h"
27 #include "clang/Basic/FileManager.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "clang/CodeGen/ConstantInitBuilder.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/StringMap.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/ConvertUTF.h"
38 #include <cctype>
39 
40 using namespace clang;
41 using namespace CodeGen;
42 
43 namespace {
44 
45 /// Class that lazily initialises the runtime function.  Avoids inserting the
46 /// types and the function declaration into a module if they're not used, and
47 /// avoids constructing the type more than once if it's used more than once.
48 class LazyRuntimeFunction {
49   CodeGenModule *CGM = nullptr;
50   llvm::FunctionType *FTy = nullptr;
51   const char *FunctionName = nullptr;
52   llvm::FunctionCallee Function = nullptr;
53 
54 public:
55   LazyRuntimeFunction() = default;
56 
57   /// Initialises the lazy function with the name, return type, and the types
58   /// of the arguments.
59   template <typename... Tys>
60   void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy,
61             Tys *... Types) {
62     CGM = Mod;
63     FunctionName = name;
64     Function = nullptr;
65     if(sizeof...(Tys)) {
66       SmallVector<llvm::Type *, 8> ArgTys({Types...});
67       FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
68     }
69     else {
70       FTy = llvm::FunctionType::get(RetTy, std::nullopt, false);
71     }
72   }
73 
74   llvm::FunctionType *getType() { return FTy; }
75 
76   /// Overloaded cast operator, allows the class to be implicitly cast to an
77   /// LLVM constant.
78   operator llvm::FunctionCallee() {
79     if (!Function) {
80       if (!FunctionName)
81         return nullptr;
82       Function = CGM->CreateRuntimeFunction(FTy, FunctionName);
83     }
84     return Function;
85   }
86 };
87 
88 
89 /// GNU Objective-C runtime code generation.  This class implements the parts of
90 /// Objective-C support that are specific to the GNU family of runtimes (GCC,
91 /// GNUstep and ObjFW).
92 class CGObjCGNU : public CGObjCRuntime {
93 protected:
94   /// The LLVM module into which output is inserted
95   llvm::Module &TheModule;
96   /// strut objc_super.  Used for sending messages to super.  This structure
97   /// contains the receiver (object) and the expected class.
98   llvm::StructType *ObjCSuperTy;
99   /// struct objc_super*.  The type of the argument to the superclass message
100   /// lookup functions.
101   llvm::PointerType *PtrToObjCSuperTy;
102   /// LLVM type for selectors.  Opaque pointer (i8*) unless a header declaring
103   /// SEL is included in a header somewhere, in which case it will be whatever
104   /// type is declared in that header, most likely {i8*, i8*}.
105   llvm::PointerType *SelectorTy;
106   /// Element type of SelectorTy.
107   llvm::Type *SelectorElemTy;
108   /// LLVM i8 type.  Cached here to avoid repeatedly getting it in all of the
109   /// places where it's used
110   llvm::IntegerType *Int8Ty;
111   /// Pointer to i8 - LLVM type of char*, for all of the places where the
112   /// runtime needs to deal with C strings.
113   llvm::PointerType *PtrToInt8Ty;
114   /// struct objc_protocol type
115   llvm::StructType *ProtocolTy;
116   /// Protocol * type.
117   llvm::PointerType *ProtocolPtrTy;
118   /// Instance Method Pointer type.  This is a pointer to a function that takes,
119   /// at a minimum, an object and a selector, and is the generic type for
120   /// Objective-C methods.  Due to differences between variadic / non-variadic
121   /// calling conventions, it must always be cast to the correct type before
122   /// actually being used.
123   llvm::PointerType *IMPTy;
124   /// Type of an untyped Objective-C object.  Clang treats id as a built-in type
125   /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
126   /// but if the runtime header declaring it is included then it may be a
127   /// pointer to a structure.
128   llvm::PointerType *IdTy;
129   /// Element type of IdTy.
130   llvm::Type *IdElemTy;
131   /// Pointer to a pointer to an Objective-C object.  Used in the new ABI
132   /// message lookup function and some GC-related functions.
133   llvm::PointerType *PtrToIdTy;
134   /// The clang type of id.  Used when using the clang CGCall infrastructure to
135   /// call Objective-C methods.
136   CanQualType ASTIdTy;
137   /// LLVM type for C int type.
138   llvm::IntegerType *IntTy;
139   /// LLVM type for an opaque pointer.  This is identical to PtrToInt8Ty, but is
140   /// used in the code to document the difference between i8* meaning a pointer
141   /// to a C string and i8* meaning a pointer to some opaque type.
142   llvm::PointerType *PtrTy;
143   /// LLVM type for C long type.  The runtime uses this in a lot of places where
144   /// it should be using intptr_t, but we can't fix this without breaking
145   /// compatibility with GCC...
146   llvm::IntegerType *LongTy;
147   /// LLVM type for C size_t.  Used in various runtime data structures.
148   llvm::IntegerType *SizeTy;
149   /// LLVM type for C intptr_t.
150   llvm::IntegerType *IntPtrTy;
151   /// LLVM type for C ptrdiff_t.  Mainly used in property accessor functions.
152   llvm::IntegerType *PtrDiffTy;
153   /// LLVM type for C int*.  Used for GCC-ABI-compatible non-fragile instance
154   /// variables.
155   llvm::PointerType *PtrToIntTy;
156   /// LLVM type for Objective-C BOOL type.
157   llvm::Type *BoolTy;
158   /// 32-bit integer type, to save us needing to look it up every time it's used.
159   llvm::IntegerType *Int32Ty;
160   /// 64-bit integer type, to save us needing to look it up every time it's used.
161   llvm::IntegerType *Int64Ty;
162   /// The type of struct objc_property.
163   llvm::StructType *PropertyMetadataTy;
164   /// Metadata kind used to tie method lookups to message sends.  The GNUstep
165   /// runtime provides some LLVM passes that can use this to do things like
166   /// automatic IMP caching and speculative inlining.
167   unsigned msgSendMDKind;
168   /// Does the current target use SEH-based exceptions? False implies
169   /// Itanium-style DWARF unwinding.
170   bool usesSEHExceptions;
171 
172   /// Helper to check if we are targeting a specific runtime version or later.
173   bool isRuntime(ObjCRuntime::Kind kind, unsigned major, unsigned minor=0) {
174     const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
175     return (R.getKind() == kind) &&
176       (R.getVersion() >= VersionTuple(major, minor));
177   }
178 
179   std::string ManglePublicSymbol(StringRef Name) {
180     return (StringRef(CGM.getTriple().isOSBinFormatCOFF() ? "$_" : "._") + Name).str();
181   }
182 
183   std::string SymbolForProtocol(Twine Name) {
184     return (ManglePublicSymbol("OBJC_PROTOCOL_") + Name).str();
185   }
186 
187   std::string SymbolForProtocolRef(StringRef Name) {
188     return (ManglePublicSymbol("OBJC_REF_PROTOCOL_") + Name).str();
189   }
190 
191 
192   /// Helper function that generates a constant string and returns a pointer to
193   /// the start of the string.  The result of this function can be used anywhere
194   /// where the C code specifies const char*.
195   llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") {
196     ConstantAddress Array =
197         CGM.GetAddrOfConstantCString(std::string(Str), Name);
198     return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
199                                                 Array.getPointer(), Zeros);
200   }
201 
202   /// Emits a linkonce_odr string, whose name is the prefix followed by the
203   /// string value.  This allows the linker to combine the strings between
204   /// different modules.  Used for EH typeinfo names, selector strings, and a
205   /// few other things.
206   llvm::Constant *ExportUniqueString(const std::string &Str,
207                                      const std::string &prefix,
208                                      bool Private=false) {
209     std::string name = prefix + Str;
210     auto *ConstStr = TheModule.getGlobalVariable(name);
211     if (!ConstStr) {
212       llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
213       auto *GV = new llvm::GlobalVariable(TheModule, value->getType(), true,
214               llvm::GlobalValue::LinkOnceODRLinkage, value, name);
215       GV->setComdat(TheModule.getOrInsertComdat(name));
216       if (Private)
217         GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
218       ConstStr = GV;
219     }
220     return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
221                                                 ConstStr, Zeros);
222   }
223 
224   /// Returns a property name and encoding string.
225   llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
226                                              const Decl *Container) {
227     assert(!isRuntime(ObjCRuntime::GNUstep, 2));
228     if (isRuntime(ObjCRuntime::GNUstep, 1, 6)) {
229       std::string NameAndAttributes;
230       std::string TypeStr =
231         CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);
232       NameAndAttributes += '\0';
233       NameAndAttributes += TypeStr.length() + 3;
234       NameAndAttributes += TypeStr;
235       NameAndAttributes += '\0';
236       NameAndAttributes += PD->getNameAsString();
237       return MakeConstantString(NameAndAttributes);
238     }
239     return MakeConstantString(PD->getNameAsString());
240   }
241 
242   /// Push the property attributes into two structure fields.
243   void PushPropertyAttributes(ConstantStructBuilder &Fields,
244       const ObjCPropertyDecl *property, bool isSynthesized=true, bool
245       isDynamic=true) {
246     int attrs = property->getPropertyAttributes();
247     // For read-only properties, clear the copy and retain flags
248     if (attrs & ObjCPropertyAttribute::kind_readonly) {
249       attrs &= ~ObjCPropertyAttribute::kind_copy;
250       attrs &= ~ObjCPropertyAttribute::kind_retain;
251       attrs &= ~ObjCPropertyAttribute::kind_weak;
252       attrs &= ~ObjCPropertyAttribute::kind_strong;
253     }
254     // The first flags field has the same attribute values as clang uses internally
255     Fields.addInt(Int8Ty, attrs & 0xff);
256     attrs >>= 8;
257     attrs <<= 2;
258     // For protocol properties, synthesized and dynamic have no meaning, so we
259     // reuse these flags to indicate that this is a protocol property (both set
260     // has no meaning, as a property can't be both synthesized and dynamic)
261     attrs |= isSynthesized ? (1<<0) : 0;
262     attrs |= isDynamic ? (1<<1) : 0;
263     // The second field is the next four fields left shifted by two, with the
264     // low bit set to indicate whether the field is synthesized or dynamic.
265     Fields.addInt(Int8Ty, attrs & 0xff);
266     // Two padding fields
267     Fields.addInt(Int8Ty, 0);
268     Fields.addInt(Int8Ty, 0);
269   }
270 
271   virtual llvm::Constant *GenerateCategoryProtocolList(const
272       ObjCCategoryDecl *OCD);
273   virtual ConstantArrayBuilder PushPropertyListHeader(ConstantStructBuilder &Fields,
274       int count) {
275       // int count;
276       Fields.addInt(IntTy, count);
277       // int size; (only in GNUstep v2 ABI.
278       if (isRuntime(ObjCRuntime::GNUstep, 2)) {
279         llvm::DataLayout td(&TheModule);
280         Fields.addInt(IntTy, td.getTypeSizeInBits(PropertyMetadataTy) /
281             CGM.getContext().getCharWidth());
282       }
283       // struct objc_property_list *next;
284       Fields.add(NULLPtr);
285       // struct objc_property properties[]
286       return Fields.beginArray(PropertyMetadataTy);
287   }
288   virtual void PushProperty(ConstantArrayBuilder &PropertiesArray,
289             const ObjCPropertyDecl *property,
290             const Decl *OCD,
291             bool isSynthesized=true, bool
292             isDynamic=true) {
293     auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
294     ASTContext &Context = CGM.getContext();
295     Fields.add(MakePropertyEncodingString(property, OCD));
296     PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
297     auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
298       if (accessor) {
299         std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
300         llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
301         Fields.add(MakeConstantString(accessor->getSelector().getAsString()));
302         Fields.add(TypeEncoding);
303       } else {
304         Fields.add(NULLPtr);
305         Fields.add(NULLPtr);
306       }
307     };
308     addPropertyMethod(property->getGetterMethodDecl());
309     addPropertyMethod(property->getSetterMethodDecl());
310     Fields.finishAndAddTo(PropertiesArray);
311   }
312 
313   /// Ensures that the value has the required type, by inserting a bitcast if
314   /// required.  This function lets us avoid inserting bitcasts that are
315   /// redundant.
316   llvm::Value *EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
317     if (V->getType() == Ty)
318       return V;
319     return B.CreateBitCast(V, Ty);
320   }
321 
322   // Some zeros used for GEPs in lots of places.
323   llvm::Constant *Zeros[2];
324   /// Null pointer value.  Mainly used as a terminator in various arrays.
325   llvm::Constant *NULLPtr;
326   /// LLVM context.
327   llvm::LLVMContext &VMContext;
328 
329 protected:
330 
331   /// Placeholder for the class.  Lots of things refer to the class before we've
332   /// actually emitted it.  We use this alias as a placeholder, and then replace
333   /// it with a pointer to the class structure before finally emitting the
334   /// module.
335   llvm::GlobalAlias *ClassPtrAlias;
336   /// Placeholder for the metaclass.  Lots of things refer to the class before
337   /// we've / actually emitted it.  We use this alias as a placeholder, and then
338   /// replace / it with a pointer to the metaclass structure before finally
339   /// emitting the / module.
340   llvm::GlobalAlias *MetaClassPtrAlias;
341   /// All of the classes that have been generated for this compilation units.
342   std::vector<llvm::Constant*> Classes;
343   /// All of the categories that have been generated for this compilation units.
344   std::vector<llvm::Constant*> Categories;
345   /// All of the Objective-C constant strings that have been generated for this
346   /// compilation units.
347   std::vector<llvm::Constant*> ConstantStrings;
348   /// Map from string values to Objective-C constant strings in the output.
349   /// Used to prevent emitting Objective-C strings more than once.  This should
350   /// not be required at all - CodeGenModule should manage this list.
351   llvm::StringMap<llvm::Constant*> ObjCStrings;
352   /// All of the protocols that have been declared.
353   llvm::StringMap<llvm::Constant*> ExistingProtocols;
354   /// For each variant of a selector, we store the type encoding and a
355   /// placeholder value.  For an untyped selector, the type will be the empty
356   /// string.  Selector references are all done via the module's selector table,
357   /// so we create an alias as a placeholder and then replace it with the real
358   /// value later.
359   typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
360   /// Type of the selector map.  This is roughly equivalent to the structure
361   /// used in the GNUstep runtime, which maintains a list of all of the valid
362   /// types for a selector in a table.
363   typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
364     SelectorMap;
365   /// A map from selectors to selector types.  This allows us to emit all
366   /// selectors of the same name and type together.
367   SelectorMap SelectorTable;
368 
369   /// Selectors related to memory management.  When compiling in GC mode, we
370   /// omit these.
371   Selector RetainSel, ReleaseSel, AutoreleaseSel;
372   /// Runtime functions used for memory management in GC mode.  Note that clang
373   /// supports code generation for calling these functions, but neither GNU
374   /// runtime actually supports this API properly yet.
375   LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
376     WeakAssignFn, GlobalAssignFn;
377 
378   typedef std::pair<std::string, std::string> ClassAliasPair;
379   /// All classes that have aliases set for them.
380   std::vector<ClassAliasPair> ClassAliases;
381 
382 protected:
383   /// Function used for throwing Objective-C exceptions.
384   LazyRuntimeFunction ExceptionThrowFn;
385   /// Function used for rethrowing exceptions, used at the end of \@finally or
386   /// \@synchronize blocks.
387   LazyRuntimeFunction ExceptionReThrowFn;
388   /// Function called when entering a catch function.  This is required for
389   /// differentiating Objective-C exceptions and foreign exceptions.
390   LazyRuntimeFunction EnterCatchFn;
391   /// Function called when exiting from a catch block.  Used to do exception
392   /// cleanup.
393   LazyRuntimeFunction ExitCatchFn;
394   /// Function called when entering an \@synchronize block.  Acquires the lock.
395   LazyRuntimeFunction SyncEnterFn;
396   /// Function called when exiting an \@synchronize block.  Releases the lock.
397   LazyRuntimeFunction SyncExitFn;
398 
399 private:
400   /// Function called if fast enumeration detects that the collection is
401   /// modified during the update.
402   LazyRuntimeFunction EnumerationMutationFn;
403   /// Function for implementing synthesized property getters that return an
404   /// object.
405   LazyRuntimeFunction GetPropertyFn;
406   /// Function for implementing synthesized property setters that return an
407   /// object.
408   LazyRuntimeFunction SetPropertyFn;
409   /// Function used for non-object declared property getters.
410   LazyRuntimeFunction GetStructPropertyFn;
411   /// Function used for non-object declared property setters.
412   LazyRuntimeFunction SetStructPropertyFn;
413 
414 protected:
415   /// The version of the runtime that this class targets.  Must match the
416   /// version in the runtime.
417   int RuntimeVersion;
418   /// The version of the protocol class.  Used to differentiate between ObjC1
419   /// and ObjC2 protocols.  Objective-C 1 protocols can not contain optional
420   /// components and can not contain declared properties.  We always emit
421   /// Objective-C 2 property structures, but we have to pretend that they're
422   /// Objective-C 1 property structures when targeting the GCC runtime or it
423   /// will abort.
424   const int ProtocolVersion;
425   /// The version of the class ABI.  This value is used in the class structure
426   /// and indicates how various fields should be interpreted.
427   const int ClassABIVersion;
428   /// Generates an instance variable list structure.  This is a structure
429   /// containing a size and an array of structures containing instance variable
430   /// metadata.  This is used purely for introspection in the fragile ABI.  In
431   /// the non-fragile ABI, it's used for instance variable fixup.
432   virtual llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
433                              ArrayRef<llvm::Constant *> IvarTypes,
434                              ArrayRef<llvm::Constant *> IvarOffsets,
435                              ArrayRef<llvm::Constant *> IvarAlign,
436                              ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership);
437 
438   /// Generates a method list structure.  This is a structure containing a size
439   /// and an array of structures containing method metadata.
440   ///
441   /// This structure is used by both classes and categories, and contains a next
442   /// pointer allowing them to be chained together in a linked list.
443   llvm::Constant *GenerateMethodList(StringRef ClassName,
444       StringRef CategoryName,
445       ArrayRef<const ObjCMethodDecl*> Methods,
446       bool isClassMethodList);
447 
448   /// Emits an empty protocol.  This is used for \@protocol() where no protocol
449   /// is found.  The runtime will (hopefully) fix up the pointer to refer to the
450   /// real protocol.
451   virtual llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName);
452 
453   /// Generates a list of property metadata structures.  This follows the same
454   /// pattern as method and instance variable metadata lists.
455   llvm::Constant *GeneratePropertyList(const Decl *Container,
456       const ObjCContainerDecl *OCD,
457       bool isClassProperty=false,
458       bool protocolOptionalProperties=false);
459 
460   /// Generates a list of referenced protocols.  Classes, categories, and
461   /// protocols all use this structure.
462   llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
463 
464   /// To ensure that all protocols are seen by the runtime, we add a category on
465   /// a class defined in the runtime, declaring no methods, but adopting the
466   /// protocols.  This is a horribly ugly hack, but it allows us to collect all
467   /// of the protocols without changing the ABI.
468   void GenerateProtocolHolderCategory();
469 
470   /// Generates a class structure.
471   llvm::Constant *GenerateClassStructure(
472       llvm::Constant *MetaClass,
473       llvm::Constant *SuperClass,
474       unsigned info,
475       const char *Name,
476       llvm::Constant *Version,
477       llvm::Constant *InstanceSize,
478       llvm::Constant *IVars,
479       llvm::Constant *Methods,
480       llvm::Constant *Protocols,
481       llvm::Constant *IvarOffsets,
482       llvm::Constant *Properties,
483       llvm::Constant *StrongIvarBitmap,
484       llvm::Constant *WeakIvarBitmap,
485       bool isMeta=false);
486 
487   /// Generates a method list.  This is used by protocols to define the required
488   /// and optional methods.
489   virtual llvm::Constant *GenerateProtocolMethodList(
490       ArrayRef<const ObjCMethodDecl*> Methods);
491   /// Emits optional and required method lists.
492   template<class T>
493   void EmitProtocolMethodList(T &&Methods, llvm::Constant *&Required,
494       llvm::Constant *&Optional) {
495     SmallVector<const ObjCMethodDecl*, 16> RequiredMethods;
496     SmallVector<const ObjCMethodDecl*, 16> OptionalMethods;
497     for (const auto *I : Methods)
498       if (I->isOptional())
499         OptionalMethods.push_back(I);
500       else
501         RequiredMethods.push_back(I);
502     Required = GenerateProtocolMethodList(RequiredMethods);
503     Optional = GenerateProtocolMethodList(OptionalMethods);
504   }
505 
506   /// Returns a selector with the specified type encoding.  An empty string is
507   /// used to return an untyped selector (with the types field set to NULL).
508   virtual llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
509                                         const std::string &TypeEncoding);
510 
511   /// Returns the name of ivar offset variables.  In the GNUstep v1 ABI, this
512   /// contains the class and ivar names, in the v2 ABI this contains the type
513   /// encoding as well.
514   virtual std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
515                                                 const ObjCIvarDecl *Ivar) {
516     const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
517       + '.' + Ivar->getNameAsString();
518     return Name;
519   }
520   /// Returns the variable used to store the offset of an instance variable.
521   llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
522       const ObjCIvarDecl *Ivar);
523   /// Emits a reference to a class.  This allows the linker to object if there
524   /// is no class of the matching name.
525   void EmitClassRef(const std::string &className);
526 
527   /// Emits a pointer to the named class
528   virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
529                                      const std::string &Name, bool isWeak);
530 
531   /// Looks up the method for sending a message to the specified object.  This
532   /// mechanism differs between the GCC and GNU runtimes, so this method must be
533   /// overridden in subclasses.
534   virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
535                                  llvm::Value *&Receiver,
536                                  llvm::Value *cmd,
537                                  llvm::MDNode *node,
538                                  MessageSendInfo &MSI) = 0;
539 
540   /// Looks up the method for sending a message to a superclass.  This
541   /// mechanism differs between the GCC and GNU runtimes, so this method must
542   /// be overridden in subclasses.
543   virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
544                                       Address ObjCSuper,
545                                       llvm::Value *cmd,
546                                       MessageSendInfo &MSI) = 0;
547 
548   /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
549   /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
550   /// bits set to their values, LSB first, while larger ones are stored in a
551   /// structure of this / form:
552   ///
553   /// struct { int32_t length; int32_t values[length]; };
554   ///
555   /// The values in the array are stored in host-endian format, with the least
556   /// significant bit being assumed to come first in the bitfield.  Therefore,
557   /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
558   /// while a bitfield / with the 63rd bit set will be 1<<64.
559   llvm::Constant *MakeBitField(ArrayRef<bool> bits);
560 
561 public:
562   CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
563       unsigned protocolClassVersion, unsigned classABI=1);
564 
565   ConstantAddress GenerateConstantString(const StringLiteral *) override;
566 
567   RValue
568   GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
569                       QualType ResultType, Selector Sel,
570                       llvm::Value *Receiver, const CallArgList &CallArgs,
571                       const ObjCInterfaceDecl *Class,
572                       const ObjCMethodDecl *Method) override;
573   RValue
574   GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
575                            QualType ResultType, Selector Sel,
576                            const ObjCInterfaceDecl *Class,
577                            bool isCategoryImpl, llvm::Value *Receiver,
578                            bool IsClassMessage, const CallArgList &CallArgs,
579                            const ObjCMethodDecl *Method) override;
580   llvm::Value *GetClass(CodeGenFunction &CGF,
581                         const ObjCInterfaceDecl *OID) override;
582   llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
583   Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
584   llvm::Value *GetSelector(CodeGenFunction &CGF,
585                            const ObjCMethodDecl *Method) override;
586   virtual llvm::Constant *GetConstantSelector(Selector Sel,
587                                               const std::string &TypeEncoding) {
588     llvm_unreachable("Runtime unable to generate constant selector");
589   }
590   llvm::Constant *GetConstantSelector(const ObjCMethodDecl *M) {
591     return GetConstantSelector(M->getSelector(),
592         CGM.getContext().getObjCEncodingForMethodDecl(M));
593   }
594   llvm::Constant *GetEHType(QualType T) override;
595 
596   llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
597                                  const ObjCContainerDecl *CD) override;
598   void GenerateDirectMethodPrologue(CodeGenFunction &CGF, llvm::Function *Fn,
599                                     const ObjCMethodDecl *OMD,
600                                     const ObjCContainerDecl *CD) override;
601   void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
602   void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
603   void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
604   llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
605                                    const ObjCProtocolDecl *PD) override;
606   void GenerateProtocol(const ObjCProtocolDecl *PD) override;
607 
608   virtual llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD);
609 
610   llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override {
611     return GenerateProtocolRef(PD);
612   }
613 
614   llvm::Function *ModuleInitFunction() override;
615   llvm::FunctionCallee GetPropertyGetFunction() override;
616   llvm::FunctionCallee GetPropertySetFunction() override;
617   llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
618                                                        bool copy) override;
619   llvm::FunctionCallee GetSetStructFunction() override;
620   llvm::FunctionCallee GetGetStructFunction() override;
621   llvm::FunctionCallee GetCppAtomicObjectGetFunction() override;
622   llvm::FunctionCallee GetCppAtomicObjectSetFunction() override;
623   llvm::FunctionCallee EnumerationMutationFunction() override;
624 
625   void EmitTryStmt(CodeGenFunction &CGF,
626                    const ObjCAtTryStmt &S) override;
627   void EmitSynchronizedStmt(CodeGenFunction &CGF,
628                             const ObjCAtSynchronizedStmt &S) override;
629   void EmitThrowStmt(CodeGenFunction &CGF,
630                      const ObjCAtThrowStmt &S,
631                      bool ClearInsertionPoint=true) override;
632   llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
633                                  Address AddrWeakObj) override;
634   void EmitObjCWeakAssign(CodeGenFunction &CGF,
635                           llvm::Value *src, Address dst) override;
636   void EmitObjCGlobalAssign(CodeGenFunction &CGF,
637                             llvm::Value *src, Address dest,
638                             bool threadlocal=false) override;
639   void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
640                           Address dest, llvm::Value *ivarOffset) override;
641   void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
642                                 llvm::Value *src, Address dest) override;
643   void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
644                                 Address SrcPtr,
645                                 llvm::Value *Size) override;
646   LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
647                               llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
648                               unsigned CVRQualifiers) override;
649   llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
650                               const ObjCInterfaceDecl *Interface,
651                               const ObjCIvarDecl *Ivar) override;
652   llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
653   llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
654                                      const CGBlockInfo &blockInfo) override {
655     return NULLPtr;
656   }
657   llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
658                                      const CGBlockInfo &blockInfo) override {
659     return NULLPtr;
660   }
661 
662   llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
663     return NULLPtr;
664   }
665 };
666 
667 /// Class representing the legacy GCC Objective-C ABI.  This is the default when
668 /// -fobjc-nonfragile-abi is not specified.
669 ///
670 /// The GCC ABI target actually generates code that is approximately compatible
671 /// with the new GNUstep runtime ABI, but refrains from using any features that
672 /// would not work with the GCC runtime.  For example, clang always generates
673 /// the extended form of the class structure, and the extra fields are simply
674 /// ignored by GCC libobjc.
675 class CGObjCGCC : public CGObjCGNU {
676   /// The GCC ABI message lookup function.  Returns an IMP pointing to the
677   /// method implementation for this message.
678   LazyRuntimeFunction MsgLookupFn;
679   /// The GCC ABI superclass message lookup function.  Takes a pointer to a
680   /// structure describing the receiver and the class, and a selector as
681   /// arguments.  Returns the IMP for the corresponding method.
682   LazyRuntimeFunction MsgLookupSuperFn;
683 
684 protected:
685   llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
686                          llvm::Value *cmd, llvm::MDNode *node,
687                          MessageSendInfo &MSI) override {
688     CGBuilderTy &Builder = CGF.Builder;
689     llvm::Value *args[] = {
690             EnforceType(Builder, Receiver, IdTy),
691             EnforceType(Builder, cmd, SelectorTy) };
692     llvm::CallBase *imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
693     imp->setMetadata(msgSendMDKind, node);
694     return imp;
695   }
696 
697   llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
698                               llvm::Value *cmd, MessageSendInfo &MSI) override {
699     CGBuilderTy &Builder = CGF.Builder;
700     llvm::Value *lookupArgs[] = {
701         EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd};
702     return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
703   }
704 
705 public:
706   CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
707     // IMP objc_msg_lookup(id, SEL);
708     MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
709     // IMP objc_msg_lookup_super(struct objc_super*, SEL);
710     MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
711                           PtrToObjCSuperTy, SelectorTy);
712   }
713 };
714 
715 /// Class used when targeting the new GNUstep runtime ABI.
716 class CGObjCGNUstep : public CGObjCGNU {
717     /// The slot lookup function.  Returns a pointer to a cacheable structure
718     /// that contains (among other things) the IMP.
719     LazyRuntimeFunction SlotLookupFn;
720     /// The GNUstep ABI superclass message lookup function.  Takes a pointer to
721     /// a structure describing the receiver and the class, and a selector as
722     /// arguments.  Returns the slot for the corresponding method.  Superclass
723     /// message lookup rarely changes, so this is a good caching opportunity.
724     LazyRuntimeFunction SlotLookupSuperFn;
725     /// Specialised function for setting atomic retain properties
726     LazyRuntimeFunction SetPropertyAtomic;
727     /// Specialised function for setting atomic copy properties
728     LazyRuntimeFunction SetPropertyAtomicCopy;
729     /// Specialised function for setting nonatomic retain properties
730     LazyRuntimeFunction SetPropertyNonAtomic;
731     /// Specialised function for setting nonatomic copy properties
732     LazyRuntimeFunction SetPropertyNonAtomicCopy;
733     /// Function to perform atomic copies of C++ objects with nontrivial copy
734     /// constructors from Objective-C ivars.
735     LazyRuntimeFunction CxxAtomicObjectGetFn;
736     /// Function to perform atomic copies of C++ objects with nontrivial copy
737     /// constructors to Objective-C ivars.
738     LazyRuntimeFunction CxxAtomicObjectSetFn;
739     /// Type of a slot structure pointer.  This is returned by the various
740     /// lookup functions.
741     llvm::Type *SlotTy;
742     /// Type of a slot structure.
743     llvm::Type *SlotStructTy;
744 
745   public:
746     llvm::Constant *GetEHType(QualType T) override;
747 
748   protected:
749     llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
750                            llvm::Value *cmd, llvm::MDNode *node,
751                            MessageSendInfo &MSI) override {
752       CGBuilderTy &Builder = CGF.Builder;
753       llvm::FunctionCallee LookupFn = SlotLookupFn;
754 
755       // Store the receiver on the stack so that we can reload it later
756       Address ReceiverPtr =
757         CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
758       Builder.CreateStore(Receiver, ReceiverPtr);
759 
760       llvm::Value *self;
761 
762       if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
763         self = CGF.LoadObjCSelf();
764       } else {
765         self = llvm::ConstantPointerNull::get(IdTy);
766       }
767 
768       // The lookup function is guaranteed not to capture the receiver pointer.
769       if (auto *LookupFn2 = dyn_cast<llvm::Function>(LookupFn.getCallee()))
770         LookupFn2->addParamAttr(0, llvm::Attribute::NoCapture);
771 
772       llvm::Value *args[] = {
773               EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
774               EnforceType(Builder, cmd, SelectorTy),
775               EnforceType(Builder, self, IdTy) };
776       llvm::CallBase *slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
777       slot->setOnlyReadsMemory();
778       slot->setMetadata(msgSendMDKind, node);
779 
780       // Load the imp from the slot
781       llvm::Value *imp = Builder.CreateAlignedLoad(
782           IMPTy, Builder.CreateStructGEP(SlotStructTy, slot, 4),
783           CGF.getPointerAlign());
784 
785       // The lookup function may have changed the receiver, so make sure we use
786       // the new one.
787       Receiver = Builder.CreateLoad(ReceiverPtr, true);
788       return imp;
789     }
790 
791     llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
792                                 llvm::Value *cmd,
793                                 MessageSendInfo &MSI) override {
794       CGBuilderTy &Builder = CGF.Builder;
795       llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
796 
797       llvm::CallInst *slot =
798         CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
799       slot->setOnlyReadsMemory();
800 
801       return Builder.CreateAlignedLoad(
802           IMPTy, Builder.CreateStructGEP(SlotStructTy, slot, 4),
803           CGF.getPointerAlign());
804     }
805 
806   public:
807     CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 9, 3, 1) {}
808     CGObjCGNUstep(CodeGenModule &Mod, unsigned ABI, unsigned ProtocolABI,
809         unsigned ClassABI) :
810       CGObjCGNU(Mod, ABI, ProtocolABI, ClassABI) {
811       const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
812 
813       SlotStructTy = llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);
814       SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
815       // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
816       SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
817                         SelectorTy, IdTy);
818       // Slot_t objc_slot_lookup_super(struct objc_super*, SEL);
819       SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
820                              PtrToObjCSuperTy, SelectorTy);
821       // If we're in ObjC++ mode, then we want to make
822       if (usesSEHExceptions) {
823           llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
824           // void objc_exception_rethrow(void)
825           ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
826       } else if (CGM.getLangOpts().CPlusPlus) {
827         llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
828         // void *__cxa_begin_catch(void *e)
829         EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
830         // void __cxa_end_catch(void)
831         ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
832         // void _Unwind_Resume_or_Rethrow(void*)
833         ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
834                                 PtrTy);
835       } else if (R.getVersion() >= VersionTuple(1, 7)) {
836         llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
837         // id objc_begin_catch(void *e)
838         EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy);
839         // void objc_end_catch(void)
840         ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy);
841         // void _Unwind_Resume_or_Rethrow(void*)
842         ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy);
843       }
844       llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
845       SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
846                              SelectorTy, IdTy, PtrDiffTy);
847       SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
848                                  IdTy, SelectorTy, IdTy, PtrDiffTy);
849       SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
850                                 IdTy, SelectorTy, IdTy, PtrDiffTy);
851       SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
852                                     VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy);
853       // void objc_setCppObjectAtomic(void *dest, const void *src, void
854       // *helper);
855       CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
856                                 PtrTy, PtrTy);
857       // void objc_getCppObjectAtomic(void *dest, const void *src, void
858       // *helper);
859       CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
860                                 PtrTy, PtrTy);
861     }
862 
863     llvm::FunctionCallee GetCppAtomicObjectGetFunction() override {
864       // The optimised functions were added in version 1.7 of the GNUstep
865       // runtime.
866       assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
867           VersionTuple(1, 7));
868       return CxxAtomicObjectGetFn;
869     }
870 
871     llvm::FunctionCallee GetCppAtomicObjectSetFunction() override {
872       // The optimised functions were added in version 1.7 of the GNUstep
873       // runtime.
874       assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
875           VersionTuple(1, 7));
876       return CxxAtomicObjectSetFn;
877     }
878 
879     llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
880                                                          bool copy) override {
881       // The optimised property functions omit the GC check, and so are not
882       // safe to use in GC mode.  The standard functions are fast in GC mode,
883       // so there is less advantage in using them.
884       assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
885       // The optimised functions were added in version 1.7 of the GNUstep
886       // runtime.
887       assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
888           VersionTuple(1, 7));
889 
890       if (atomic) {
891         if (copy) return SetPropertyAtomicCopy;
892         return SetPropertyAtomic;
893       }
894 
895       return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
896     }
897 };
898 
899 /// GNUstep Objective-C ABI version 2 implementation.
900 /// This is the ABI that provides a clean break with the legacy GCC ABI and
901 /// cleans up a number of things that were added to work around 1980s linkers.
902 class CGObjCGNUstep2 : public CGObjCGNUstep {
903   enum SectionKind
904   {
905     SelectorSection = 0,
906     ClassSection,
907     ClassReferenceSection,
908     CategorySection,
909     ProtocolSection,
910     ProtocolReferenceSection,
911     ClassAliasSection,
912     ConstantStringSection
913   };
914   static const char *const SectionsBaseNames[8];
915   static const char *const PECOFFSectionsBaseNames[8];
916   template<SectionKind K>
917   std::string sectionName() {
918     if (CGM.getTriple().isOSBinFormatCOFF()) {
919       std::string name(PECOFFSectionsBaseNames[K]);
920       name += "$m";
921       return name;
922     }
923     return SectionsBaseNames[K];
924   }
925   /// The GCC ABI superclass message lookup function.  Takes a pointer to a
926   /// structure describing the receiver and the class, and a selector as
927   /// arguments.  Returns the IMP for the corresponding method.
928   LazyRuntimeFunction MsgLookupSuperFn;
929   /// A flag indicating if we've emitted at least one protocol.
930   /// If we haven't, then we need to emit an empty protocol, to ensure that the
931   /// __start__objc_protocols and __stop__objc_protocols sections exist.
932   bool EmittedProtocol = false;
933   /// A flag indicating if we've emitted at least one protocol reference.
934   /// If we haven't, then we need to emit an empty protocol, to ensure that the
935   /// __start__objc_protocol_refs and __stop__objc_protocol_refs sections
936   /// exist.
937   bool EmittedProtocolRef = false;
938   /// A flag indicating if we've emitted at least one class.
939   /// If we haven't, then we need to emit an empty protocol, to ensure that the
940   /// __start__objc_classes and __stop__objc_classes sections / exist.
941   bool EmittedClass = false;
942   /// Generate the name of a symbol for a reference to a class.  Accesses to
943   /// classes should be indirected via this.
944 
945   typedef std::pair<std::string, std::pair<llvm::GlobalVariable*, int>>
946       EarlyInitPair;
947   std::vector<EarlyInitPair> EarlyInitList;
948 
949   std::string SymbolForClassRef(StringRef Name, bool isWeak) {
950     if (isWeak)
951       return (ManglePublicSymbol("OBJC_WEAK_REF_CLASS_") + Name).str();
952     else
953       return (ManglePublicSymbol("OBJC_REF_CLASS_") + Name).str();
954   }
955   /// Generate the name of a class symbol.
956   std::string SymbolForClass(StringRef Name) {
957     return (ManglePublicSymbol("OBJC_CLASS_") + Name).str();
958   }
959   void CallRuntimeFunction(CGBuilderTy &B, StringRef FunctionName,
960       ArrayRef<llvm::Value*> Args) {
961     SmallVector<llvm::Type *,8> Types;
962     for (auto *Arg : Args)
963       Types.push_back(Arg->getType());
964     llvm::FunctionType *FT = llvm::FunctionType::get(B.getVoidTy(), Types,
965         false);
966     llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FT, FunctionName);
967     B.CreateCall(Fn, Args);
968   }
969 
970   ConstantAddress GenerateConstantString(const StringLiteral *SL) override {
971 
972     auto Str = SL->getString();
973     CharUnits Align = CGM.getPointerAlign();
974 
975     // Look for an existing one
976     llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
977     if (old != ObjCStrings.end())
978       return ConstantAddress(old->getValue(), IdElemTy, Align);
979 
980     bool isNonASCII = SL->containsNonAscii();
981 
982     auto LiteralLength = SL->getLength();
983 
984     if ((CGM.getTarget().getPointerWidth(LangAS::Default) == 64) &&
985         (LiteralLength < 9) && !isNonASCII) {
986       // Tiny strings are only used on 64-bit platforms.  They store 8 7-bit
987       // ASCII characters in the high 56 bits, followed by a 4-bit length and a
988       // 3-bit tag (which is always 4).
989       uint64_t str = 0;
990       // Fill in the characters
991       for (unsigned i=0 ; i<LiteralLength ; i++)
992         str |= ((uint64_t)SL->getCodeUnit(i)) << ((64 - 4 - 3) - (i*7));
993       // Fill in the length
994       str |= LiteralLength << 3;
995       // Set the tag
996       str |= 4;
997       auto *ObjCStr = llvm::ConstantExpr::getIntToPtr(
998           llvm::ConstantInt::get(Int64Ty, str), IdTy);
999       ObjCStrings[Str] = ObjCStr;
1000       return ConstantAddress(ObjCStr, IdElemTy, Align);
1001     }
1002 
1003     StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
1004 
1005     if (StringClass.empty()) StringClass = "NSConstantString";
1006 
1007     std::string Sym = SymbolForClass(StringClass);
1008 
1009     llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1010 
1011     if (!isa) {
1012       isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1013               llvm::GlobalValue::ExternalLinkage, nullptr, Sym);
1014       if (CGM.getTriple().isOSBinFormatCOFF()) {
1015         cast<llvm::GlobalValue>(isa)->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1016       }
1017     } else if (isa->getType() != PtrToIdTy)
1018       isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1019 
1020     //  struct
1021     //  {
1022     //    Class isa;
1023     //    uint32_t flags;
1024     //    uint32_t length; // Number of codepoints
1025     //    uint32_t size; // Number of bytes
1026     //    uint32_t hash;
1027     //    const char *data;
1028     //  };
1029 
1030     ConstantInitBuilder Builder(CGM);
1031     auto Fields = Builder.beginStruct();
1032     if (!CGM.getTriple().isOSBinFormatCOFF()) {
1033       Fields.add(isa);
1034     } else {
1035       Fields.addNullPointer(PtrTy);
1036     }
1037     // For now, all non-ASCII strings are represented as UTF-16.  As such, the
1038     // number of bytes is simply double the number of UTF-16 codepoints.  In
1039     // ASCII strings, the number of bytes is equal to the number of non-ASCII
1040     // codepoints.
1041     if (isNonASCII) {
1042       unsigned NumU8CodeUnits = Str.size();
1043       // A UTF-16 representation of a unicode string contains at most the same
1044       // number of code units as a UTF-8 representation.  Allocate that much
1045       // space, plus one for the final null character.
1046       SmallVector<llvm::UTF16, 128> ToBuf(NumU8CodeUnits + 1);
1047       const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)Str.data();
1048       llvm::UTF16 *ToPtr = &ToBuf[0];
1049       (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumU8CodeUnits,
1050           &ToPtr, ToPtr + NumU8CodeUnits, llvm::strictConversion);
1051       uint32_t StringLength = ToPtr - &ToBuf[0];
1052       // Add null terminator
1053       *ToPtr = 0;
1054       // Flags: 2 indicates UTF-16 encoding
1055       Fields.addInt(Int32Ty, 2);
1056       // Number of UTF-16 codepoints
1057       Fields.addInt(Int32Ty, StringLength);
1058       // Number of bytes
1059       Fields.addInt(Int32Ty, StringLength * 2);
1060       // Hash.  Not currently initialised by the compiler.
1061       Fields.addInt(Int32Ty, 0);
1062       // pointer to the data string.
1063       auto Arr = llvm::ArrayRef(&ToBuf[0], ToPtr + 1);
1064       auto *C = llvm::ConstantDataArray::get(VMContext, Arr);
1065       auto *Buffer = new llvm::GlobalVariable(TheModule, C->getType(),
1066           /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, C, ".str");
1067       Buffer->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1068       Fields.add(Buffer);
1069     } else {
1070       // Flags: 0 indicates ASCII encoding
1071       Fields.addInt(Int32Ty, 0);
1072       // Number of UTF-16 codepoints, each ASCII byte is a UTF-16 codepoint
1073       Fields.addInt(Int32Ty, Str.size());
1074       // Number of bytes
1075       Fields.addInt(Int32Ty, Str.size());
1076       // Hash.  Not currently initialised by the compiler.
1077       Fields.addInt(Int32Ty, 0);
1078       // Data pointer
1079       Fields.add(MakeConstantString(Str));
1080     }
1081     std::string StringName;
1082     bool isNamed = !isNonASCII;
1083     if (isNamed) {
1084       StringName = ".objc_str_";
1085       for (int i=0,e=Str.size() ; i<e ; ++i) {
1086         unsigned char c = Str[i];
1087         if (isalnum(c))
1088           StringName += c;
1089         else if (c == ' ')
1090           StringName += '_';
1091         else {
1092           isNamed = false;
1093           break;
1094         }
1095       }
1096     }
1097     llvm::GlobalVariable *ObjCStrGV =
1098       Fields.finishAndCreateGlobal(
1099           isNamed ? StringRef(StringName) : ".objc_string",
1100           Align, false, isNamed ? llvm::GlobalValue::LinkOnceODRLinkage
1101                                 : llvm::GlobalValue::PrivateLinkage);
1102     ObjCStrGV->setSection(sectionName<ConstantStringSection>());
1103     if (isNamed) {
1104       ObjCStrGV->setComdat(TheModule.getOrInsertComdat(StringName));
1105       ObjCStrGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1106     }
1107     if (CGM.getTriple().isOSBinFormatCOFF()) {
1108       std::pair<llvm::GlobalVariable*, int> v{ObjCStrGV, 0};
1109       EarlyInitList.emplace_back(Sym, v);
1110     }
1111     llvm::Constant *ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStrGV, IdTy);
1112     ObjCStrings[Str] = ObjCStr;
1113     ConstantStrings.push_back(ObjCStr);
1114     return ConstantAddress(ObjCStr, IdElemTy, Align);
1115   }
1116 
1117   void PushProperty(ConstantArrayBuilder &PropertiesArray,
1118             const ObjCPropertyDecl *property,
1119             const Decl *OCD,
1120             bool isSynthesized=true, bool
1121             isDynamic=true) override {
1122     // struct objc_property
1123     // {
1124     //   const char *name;
1125     //   const char *attributes;
1126     //   const char *type;
1127     //   SEL getter;
1128     //   SEL setter;
1129     // };
1130     auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
1131     ASTContext &Context = CGM.getContext();
1132     Fields.add(MakeConstantString(property->getNameAsString()));
1133     std::string TypeStr =
1134       CGM.getContext().getObjCEncodingForPropertyDecl(property, OCD);
1135     Fields.add(MakeConstantString(TypeStr));
1136     std::string typeStr;
1137     Context.getObjCEncodingForType(property->getType(), typeStr);
1138     Fields.add(MakeConstantString(typeStr));
1139     auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
1140       if (accessor) {
1141         std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
1142         Fields.add(GetConstantSelector(accessor->getSelector(), TypeStr));
1143       } else {
1144         Fields.add(NULLPtr);
1145       }
1146     };
1147     addPropertyMethod(property->getGetterMethodDecl());
1148     addPropertyMethod(property->getSetterMethodDecl());
1149     Fields.finishAndAddTo(PropertiesArray);
1150   }
1151 
1152   llvm::Constant *
1153   GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) override {
1154     // struct objc_protocol_method_description
1155     // {
1156     //   SEL selector;
1157     //   const char *types;
1158     // };
1159     llvm::StructType *ObjCMethodDescTy =
1160       llvm::StructType::get(CGM.getLLVMContext(),
1161           { PtrToInt8Ty, PtrToInt8Ty });
1162     ASTContext &Context = CGM.getContext();
1163     ConstantInitBuilder Builder(CGM);
1164     // struct objc_protocol_method_description_list
1165     // {
1166     //   int count;
1167     //   int size;
1168     //   struct objc_protocol_method_description methods[];
1169     // };
1170     auto MethodList = Builder.beginStruct();
1171     // int count;
1172     MethodList.addInt(IntTy, Methods.size());
1173     // int size; // sizeof(struct objc_method_description)
1174     llvm::DataLayout td(&TheModule);
1175     MethodList.addInt(IntTy, td.getTypeSizeInBits(ObjCMethodDescTy) /
1176         CGM.getContext().getCharWidth());
1177     // struct objc_method_description[]
1178     auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
1179     for (auto *M : Methods) {
1180       auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
1181       Method.add(CGObjCGNU::GetConstantSelector(M));
1182       Method.add(GetTypeString(Context.getObjCEncodingForMethodDecl(M, true)));
1183       Method.finishAndAddTo(MethodArray);
1184     }
1185     MethodArray.finishAndAddTo(MethodList);
1186     return MethodList.finishAndCreateGlobal(".objc_protocol_method_list",
1187                                             CGM.getPointerAlign());
1188   }
1189   llvm::Constant *GenerateCategoryProtocolList(const ObjCCategoryDecl *OCD)
1190     override {
1191     const auto &ReferencedProtocols = OCD->getReferencedProtocols();
1192     auto RuntimeProtocols = GetRuntimeProtocolList(ReferencedProtocols.begin(),
1193                                                    ReferencedProtocols.end());
1194     SmallVector<llvm::Constant *, 16> Protocols;
1195     for (const auto *PI : RuntimeProtocols)
1196       Protocols.push_back(
1197           llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
1198             ProtocolPtrTy));
1199     return GenerateProtocolList(Protocols);
1200   }
1201 
1202   llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
1203                               llvm::Value *cmd, MessageSendInfo &MSI) override {
1204     // Don't access the slot unless we're trying to cache the result.
1205     CGBuilderTy &Builder = CGF.Builder;
1206     llvm::Value *lookupArgs[] = {CGObjCGNU::EnforceType(Builder,
1207                                                         ObjCSuper.getPointer(),
1208                                                         PtrToObjCSuperTy),
1209                                  cmd};
1210     return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
1211   }
1212 
1213   llvm::GlobalVariable *GetClassVar(StringRef Name, bool isWeak=false) {
1214     std::string SymbolName = SymbolForClassRef(Name, isWeak);
1215     auto *ClassSymbol = TheModule.getNamedGlobal(SymbolName);
1216     if (ClassSymbol)
1217       return ClassSymbol;
1218     ClassSymbol = new llvm::GlobalVariable(TheModule,
1219         IdTy, false, llvm::GlobalValue::ExternalLinkage,
1220         nullptr, SymbolName);
1221     // If this is a weak symbol, then we are creating a valid definition for
1222     // the symbol, pointing to a weak definition of the real class pointer.  If
1223     // this is not a weak reference, then we are expecting another compilation
1224     // unit to provide the real indirection symbol.
1225     if (isWeak)
1226       ClassSymbol->setInitializer(new llvm::GlobalVariable(TheModule,
1227           Int8Ty, false, llvm::GlobalValue::ExternalWeakLinkage,
1228           nullptr, SymbolForClass(Name)));
1229     else {
1230       if (CGM.getTriple().isOSBinFormatCOFF()) {
1231         IdentifierInfo &II = CGM.getContext().Idents.get(Name);
1232         TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
1233         DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
1234 
1235         const ObjCInterfaceDecl *OID = nullptr;
1236         for (const auto *Result : DC->lookup(&II))
1237           if ((OID = dyn_cast<ObjCInterfaceDecl>(Result)))
1238             break;
1239 
1240         // The first Interface we find may be a @class,
1241         // which should only be treated as the source of
1242         // truth in the absence of a true declaration.
1243         assert(OID && "Failed to find ObjCInterfaceDecl");
1244         const ObjCInterfaceDecl *OIDDef = OID->getDefinition();
1245         if (OIDDef != nullptr)
1246           OID = OIDDef;
1247 
1248         auto Storage = llvm::GlobalValue::DefaultStorageClass;
1249         if (OID->hasAttr<DLLImportAttr>())
1250           Storage = llvm::GlobalValue::DLLImportStorageClass;
1251         else if (OID->hasAttr<DLLExportAttr>())
1252           Storage = llvm::GlobalValue::DLLExportStorageClass;
1253 
1254         cast<llvm::GlobalValue>(ClassSymbol)->setDLLStorageClass(Storage);
1255       }
1256     }
1257     assert(ClassSymbol->getName() == SymbolName);
1258     return ClassSymbol;
1259   }
1260   llvm::Value *GetClassNamed(CodeGenFunction &CGF,
1261                              const std::string &Name,
1262                              bool isWeak) override {
1263     return CGF.Builder.CreateLoad(
1264         Address(GetClassVar(Name, isWeak), IdTy, CGM.getPointerAlign()));
1265   }
1266   int32_t FlagsForOwnership(Qualifiers::ObjCLifetime Ownership) {
1267     // typedef enum {
1268     //   ownership_invalid = 0,
1269     //   ownership_strong  = 1,
1270     //   ownership_weak    = 2,
1271     //   ownership_unsafe  = 3
1272     // } ivar_ownership;
1273     int Flag;
1274     switch (Ownership) {
1275       case Qualifiers::OCL_Strong:
1276           Flag = 1;
1277           break;
1278       case Qualifiers::OCL_Weak:
1279           Flag = 2;
1280           break;
1281       case Qualifiers::OCL_ExplicitNone:
1282           Flag = 3;
1283           break;
1284       case Qualifiers::OCL_None:
1285       case Qualifiers::OCL_Autoreleasing:
1286         assert(Ownership != Qualifiers::OCL_Autoreleasing);
1287         Flag = 0;
1288     }
1289     return Flag;
1290   }
1291   llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1292                    ArrayRef<llvm::Constant *> IvarTypes,
1293                    ArrayRef<llvm::Constant *> IvarOffsets,
1294                    ArrayRef<llvm::Constant *> IvarAlign,
1295                    ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) override {
1296     llvm_unreachable("Method should not be called!");
1297   }
1298 
1299   llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName) override {
1300     std::string Name = SymbolForProtocol(ProtocolName);
1301     auto *GV = TheModule.getGlobalVariable(Name);
1302     if (!GV) {
1303       // Emit a placeholder symbol.
1304       GV = new llvm::GlobalVariable(TheModule, ProtocolTy, false,
1305           llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1306       GV->setAlignment(CGM.getPointerAlign().getAsAlign());
1307     }
1308     return llvm::ConstantExpr::getBitCast(GV, ProtocolPtrTy);
1309   }
1310 
1311   /// Existing protocol references.
1312   llvm::StringMap<llvm::Constant*> ExistingProtocolRefs;
1313 
1314   llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1315                                    const ObjCProtocolDecl *PD) override {
1316     auto Name = PD->getNameAsString();
1317     auto *&Ref = ExistingProtocolRefs[Name];
1318     if (!Ref) {
1319       auto *&Protocol = ExistingProtocols[Name];
1320       if (!Protocol)
1321         Protocol = GenerateProtocolRef(PD);
1322       std::string RefName = SymbolForProtocolRef(Name);
1323       assert(!TheModule.getGlobalVariable(RefName));
1324       // Emit a reference symbol.
1325       auto GV = new llvm::GlobalVariable(TheModule, ProtocolPtrTy,
1326           false, llvm::GlobalValue::LinkOnceODRLinkage,
1327           llvm::ConstantExpr::getBitCast(Protocol, ProtocolPtrTy), RefName);
1328       GV->setComdat(TheModule.getOrInsertComdat(RefName));
1329       GV->setSection(sectionName<ProtocolReferenceSection>());
1330       GV->setAlignment(CGM.getPointerAlign().getAsAlign());
1331       Ref = GV;
1332     }
1333     EmittedProtocolRef = true;
1334     return CGF.Builder.CreateAlignedLoad(ProtocolPtrTy, Ref,
1335                                          CGM.getPointerAlign());
1336   }
1337 
1338   llvm::Constant *GenerateProtocolList(ArrayRef<llvm::Constant*> Protocols) {
1339     llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(ProtocolPtrTy,
1340         Protocols.size());
1341     llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1342         Protocols);
1343     ConstantInitBuilder builder(CGM);
1344     auto ProtocolBuilder = builder.beginStruct();
1345     ProtocolBuilder.addNullPointer(PtrTy);
1346     ProtocolBuilder.addInt(SizeTy, Protocols.size());
1347     ProtocolBuilder.add(ProtocolArray);
1348     return ProtocolBuilder.finishAndCreateGlobal(".objc_protocol_list",
1349         CGM.getPointerAlign(), false, llvm::GlobalValue::InternalLinkage);
1350   }
1351 
1352   void GenerateProtocol(const ObjCProtocolDecl *PD) override {
1353     // Do nothing - we only emit referenced protocols.
1354   }
1355   llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD) override {
1356     std::string ProtocolName = PD->getNameAsString();
1357     auto *&Protocol = ExistingProtocols[ProtocolName];
1358     if (Protocol)
1359       return Protocol;
1360 
1361     EmittedProtocol = true;
1362 
1363     auto SymName = SymbolForProtocol(ProtocolName);
1364     auto *OldGV = TheModule.getGlobalVariable(SymName);
1365 
1366     // Use the protocol definition, if there is one.
1367     if (const ObjCProtocolDecl *Def = PD->getDefinition())
1368       PD = Def;
1369     else {
1370       // If there is no definition, then create an external linkage symbol and
1371       // hope that someone else fills it in for us (and fail to link if they
1372       // don't).
1373       assert(!OldGV);
1374       Protocol = new llvm::GlobalVariable(TheModule, ProtocolTy,
1375         /*isConstant*/false,
1376         llvm::GlobalValue::ExternalLinkage, nullptr, SymName);
1377       return Protocol;
1378     }
1379 
1380     SmallVector<llvm::Constant*, 16> Protocols;
1381     auto RuntimeProtocols =
1382         GetRuntimeProtocolList(PD->protocol_begin(), PD->protocol_end());
1383     for (const auto *PI : RuntimeProtocols)
1384       Protocols.push_back(
1385           llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
1386             ProtocolPtrTy));
1387     llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1388 
1389     // Collect information about methods
1390     llvm::Constant *InstanceMethodList, *OptionalInstanceMethodList;
1391     llvm::Constant *ClassMethodList, *OptionalClassMethodList;
1392     EmitProtocolMethodList(PD->instance_methods(), InstanceMethodList,
1393         OptionalInstanceMethodList);
1394     EmitProtocolMethodList(PD->class_methods(), ClassMethodList,
1395         OptionalClassMethodList);
1396 
1397     // The isa pointer must be set to a magic number so the runtime knows it's
1398     // the correct layout.
1399     ConstantInitBuilder builder(CGM);
1400     auto ProtocolBuilder = builder.beginStruct();
1401     ProtocolBuilder.add(llvm::ConstantExpr::getIntToPtr(
1402           llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1403     ProtocolBuilder.add(MakeConstantString(ProtocolName));
1404     ProtocolBuilder.add(ProtocolList);
1405     ProtocolBuilder.add(InstanceMethodList);
1406     ProtocolBuilder.add(ClassMethodList);
1407     ProtocolBuilder.add(OptionalInstanceMethodList);
1408     ProtocolBuilder.add(OptionalClassMethodList);
1409     // Required instance properties
1410     ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, false));
1411     // Optional instance properties
1412     ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, true));
1413     // Required class properties
1414     ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, false));
1415     // Optional class properties
1416     ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, true));
1417 
1418     auto *GV = ProtocolBuilder.finishAndCreateGlobal(SymName,
1419         CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
1420     GV->setSection(sectionName<ProtocolSection>());
1421     GV->setComdat(TheModule.getOrInsertComdat(SymName));
1422     if (OldGV) {
1423       OldGV->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GV,
1424             OldGV->getType()));
1425       OldGV->removeFromParent();
1426       GV->setName(SymName);
1427     }
1428     Protocol = GV;
1429     return GV;
1430   }
1431   llvm::Constant *EnforceType(llvm::Constant *Val, llvm::Type *Ty) {
1432     if (Val->getType() == Ty)
1433       return Val;
1434     return llvm::ConstantExpr::getBitCast(Val, Ty);
1435   }
1436   llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
1437                                 const std::string &TypeEncoding) override {
1438     return GetConstantSelector(Sel, TypeEncoding);
1439   }
1440   llvm::Constant  *GetTypeString(llvm::StringRef TypeEncoding) {
1441     if (TypeEncoding.empty())
1442       return NULLPtr;
1443     std::string MangledTypes = std::string(TypeEncoding);
1444     std::replace(MangledTypes.begin(), MangledTypes.end(),
1445       '@', '\1');
1446     std::string TypesVarName = ".objc_sel_types_" + MangledTypes;
1447     auto *TypesGlobal = TheModule.getGlobalVariable(TypesVarName);
1448     if (!TypesGlobal) {
1449       llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
1450           TypeEncoding);
1451       auto *GV = new llvm::GlobalVariable(TheModule, Init->getType(),
1452           true, llvm::GlobalValue::LinkOnceODRLinkage, Init, TypesVarName);
1453       GV->setComdat(TheModule.getOrInsertComdat(TypesVarName));
1454       GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1455       TypesGlobal = GV;
1456     }
1457     return llvm::ConstantExpr::getGetElementPtr(TypesGlobal->getValueType(),
1458         TypesGlobal, Zeros);
1459   }
1460   llvm::Constant *GetConstantSelector(Selector Sel,
1461                                       const std::string &TypeEncoding) override {
1462     // @ is used as a special character in symbol names (used for symbol
1463     // versioning), so mangle the name to not include it.  Replace it with a
1464     // character that is not a valid type encoding character (and, being
1465     // non-printable, never will be!)
1466     std::string MangledTypes = TypeEncoding;
1467     std::replace(MangledTypes.begin(), MangledTypes.end(),
1468       '@', '\1');
1469     auto SelVarName = (StringRef(".objc_selector_") + Sel.getAsString() + "_" +
1470       MangledTypes).str();
1471     if (auto *GV = TheModule.getNamedGlobal(SelVarName))
1472       return EnforceType(GV, SelectorTy);
1473     ConstantInitBuilder builder(CGM);
1474     auto SelBuilder = builder.beginStruct();
1475     SelBuilder.add(ExportUniqueString(Sel.getAsString(), ".objc_sel_name_",
1476           true));
1477     SelBuilder.add(GetTypeString(TypeEncoding));
1478     auto *GV = SelBuilder.finishAndCreateGlobal(SelVarName,
1479         CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1480     GV->setComdat(TheModule.getOrInsertComdat(SelVarName));
1481     GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1482     GV->setSection(sectionName<SelectorSection>());
1483     auto *SelVal = EnforceType(GV, SelectorTy);
1484     return SelVal;
1485   }
1486   llvm::StructType *emptyStruct = nullptr;
1487 
1488   /// Return pointers to the start and end of a section.  On ELF platforms, we
1489   /// use the __start_ and __stop_ symbols that GNU-compatible linkers will set
1490   /// to the start and end of section names, as long as those section names are
1491   /// valid identifiers and the symbols are referenced but not defined.  On
1492   /// Windows, we use the fact that MSVC-compatible linkers will lexically sort
1493   /// by subsections and place everything that we want to reference in a middle
1494   /// subsection and then insert zero-sized symbols in subsections a and z.
1495   std::pair<llvm::Constant*,llvm::Constant*>
1496   GetSectionBounds(StringRef Section) {
1497     if (CGM.getTriple().isOSBinFormatCOFF()) {
1498       if (emptyStruct == nullptr) {
1499         emptyStruct = llvm::StructType::create(VMContext, ".objc_section_sentinel");
1500         emptyStruct->setBody({}, /*isPacked*/true);
1501       }
1502       auto ZeroInit = llvm::Constant::getNullValue(emptyStruct);
1503       auto Sym = [&](StringRef Prefix, StringRef SecSuffix) {
1504         auto *Sym = new llvm::GlobalVariable(TheModule, emptyStruct,
1505             /*isConstant*/false,
1506             llvm::GlobalValue::LinkOnceODRLinkage, ZeroInit, Prefix +
1507             Section);
1508         Sym->setVisibility(llvm::GlobalValue::HiddenVisibility);
1509         Sym->setSection((Section + SecSuffix).str());
1510         Sym->setComdat(TheModule.getOrInsertComdat((Prefix +
1511             Section).str()));
1512         Sym->setAlignment(CGM.getPointerAlign().getAsAlign());
1513         return Sym;
1514       };
1515       return { Sym("__start_", "$a"), Sym("__stop", "$z") };
1516     }
1517     auto *Start = new llvm::GlobalVariable(TheModule, PtrTy,
1518         /*isConstant*/false,
1519         llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__start_") +
1520         Section);
1521     Start->setVisibility(llvm::GlobalValue::HiddenVisibility);
1522     auto *Stop = new llvm::GlobalVariable(TheModule, PtrTy,
1523         /*isConstant*/false,
1524         llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__stop_") +
1525         Section);
1526     Stop->setVisibility(llvm::GlobalValue::HiddenVisibility);
1527     return { Start, Stop };
1528   }
1529   CatchTypeInfo getCatchAllTypeInfo() override {
1530     return CGM.getCXXABI().getCatchAllTypeInfo();
1531   }
1532   llvm::Function *ModuleInitFunction() override {
1533     llvm::Function *LoadFunction = llvm::Function::Create(
1534       llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
1535       llvm::GlobalValue::LinkOnceODRLinkage, ".objcv2_load_function",
1536       &TheModule);
1537     LoadFunction->setVisibility(llvm::GlobalValue::HiddenVisibility);
1538     LoadFunction->setComdat(TheModule.getOrInsertComdat(".objcv2_load_function"));
1539 
1540     llvm::BasicBlock *EntryBB =
1541         llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
1542     CGBuilderTy B(CGM, VMContext);
1543     B.SetInsertPoint(EntryBB);
1544     ConstantInitBuilder builder(CGM);
1545     auto InitStructBuilder = builder.beginStruct();
1546     InitStructBuilder.addInt(Int64Ty, 0);
1547     auto &sectionVec = CGM.getTriple().isOSBinFormatCOFF() ? PECOFFSectionsBaseNames : SectionsBaseNames;
1548     for (auto *s : sectionVec) {
1549       auto bounds = GetSectionBounds(s);
1550       InitStructBuilder.add(bounds.first);
1551       InitStructBuilder.add(bounds.second);
1552     }
1553     auto *InitStruct = InitStructBuilder.finishAndCreateGlobal(".objc_init",
1554         CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1555     InitStruct->setVisibility(llvm::GlobalValue::HiddenVisibility);
1556     InitStruct->setComdat(TheModule.getOrInsertComdat(".objc_init"));
1557 
1558     CallRuntimeFunction(B, "__objc_load", {InitStruct});;
1559     B.CreateRetVoid();
1560     // Make sure that the optimisers don't delete this function.
1561     CGM.addCompilerUsedGlobal(LoadFunction);
1562     // FIXME: Currently ELF only!
1563     // We have to do this by hand, rather than with @llvm.ctors, so that the
1564     // linker can remove the duplicate invocations.
1565     auto *InitVar = new llvm::GlobalVariable(TheModule, LoadFunction->getType(),
1566         /*isConstant*/false, llvm::GlobalValue::LinkOnceAnyLinkage,
1567         LoadFunction, ".objc_ctor");
1568     // Check that this hasn't been renamed.  This shouldn't happen, because
1569     // this function should be called precisely once.
1570     assert(InitVar->getName() == ".objc_ctor");
1571     // In Windows, initialisers are sorted by the suffix.  XCL is for library
1572     // initialisers, which run before user initialisers.  We are running
1573     // Objective-C loads at the end of library load.  This means +load methods
1574     // will run before any other static constructors, but that static
1575     // constructors can see a fully initialised Objective-C state.
1576     if (CGM.getTriple().isOSBinFormatCOFF())
1577         InitVar->setSection(".CRT$XCLz");
1578     else
1579     {
1580       if (CGM.getCodeGenOpts().UseInitArray)
1581         InitVar->setSection(".init_array");
1582       else
1583         InitVar->setSection(".ctors");
1584     }
1585     InitVar->setVisibility(llvm::GlobalValue::HiddenVisibility);
1586     InitVar->setComdat(TheModule.getOrInsertComdat(".objc_ctor"));
1587     CGM.addUsedGlobal(InitVar);
1588     for (auto *C : Categories) {
1589       auto *Cat = cast<llvm::GlobalVariable>(C->stripPointerCasts());
1590       Cat->setSection(sectionName<CategorySection>());
1591       CGM.addUsedGlobal(Cat);
1592     }
1593     auto createNullGlobal = [&](StringRef Name, ArrayRef<llvm::Constant*> Init,
1594         StringRef Section) {
1595       auto nullBuilder = builder.beginStruct();
1596       for (auto *F : Init)
1597         nullBuilder.add(F);
1598       auto GV = nullBuilder.finishAndCreateGlobal(Name, CGM.getPointerAlign(),
1599           false, llvm::GlobalValue::LinkOnceODRLinkage);
1600       GV->setSection(Section);
1601       GV->setComdat(TheModule.getOrInsertComdat(Name));
1602       GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1603       CGM.addUsedGlobal(GV);
1604       return GV;
1605     };
1606     for (auto clsAlias : ClassAliases)
1607       createNullGlobal(std::string(".objc_class_alias") +
1608           clsAlias.second, { MakeConstantString(clsAlias.second),
1609           GetClassVar(clsAlias.first) }, sectionName<ClassAliasSection>());
1610     // On ELF platforms, add a null value for each special section so that we
1611     // can always guarantee that the _start and _stop symbols will exist and be
1612     // meaningful.  This is not required on COFF platforms, where our start and
1613     // stop symbols will create the section.
1614     if (!CGM.getTriple().isOSBinFormatCOFF()) {
1615       createNullGlobal(".objc_null_selector", {NULLPtr, NULLPtr},
1616           sectionName<SelectorSection>());
1617       if (Categories.empty())
1618         createNullGlobal(".objc_null_category", {NULLPtr, NULLPtr,
1619                       NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr},
1620             sectionName<CategorySection>());
1621       if (!EmittedClass) {
1622         createNullGlobal(".objc_null_cls_init_ref", NULLPtr,
1623             sectionName<ClassSection>());
1624         createNullGlobal(".objc_null_class_ref", { NULLPtr, NULLPtr },
1625             sectionName<ClassReferenceSection>());
1626       }
1627       if (!EmittedProtocol)
1628         createNullGlobal(".objc_null_protocol", {NULLPtr, NULLPtr, NULLPtr,
1629             NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr,
1630             NULLPtr}, sectionName<ProtocolSection>());
1631       if (!EmittedProtocolRef)
1632         createNullGlobal(".objc_null_protocol_ref", {NULLPtr},
1633             sectionName<ProtocolReferenceSection>());
1634       if (ClassAliases.empty())
1635         createNullGlobal(".objc_null_class_alias", { NULLPtr, NULLPtr },
1636             sectionName<ClassAliasSection>());
1637       if (ConstantStrings.empty()) {
1638         auto i32Zero = llvm::ConstantInt::get(Int32Ty, 0);
1639         createNullGlobal(".objc_null_constant_string", { NULLPtr, i32Zero,
1640             i32Zero, i32Zero, i32Zero, NULLPtr },
1641             sectionName<ConstantStringSection>());
1642       }
1643     }
1644     ConstantStrings.clear();
1645     Categories.clear();
1646     Classes.clear();
1647 
1648     if (EarlyInitList.size() > 0) {
1649       auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
1650             {}), llvm::GlobalValue::InternalLinkage, ".objc_early_init",
1651           &CGM.getModule());
1652       llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
1653             Init));
1654       for (const auto &lateInit : EarlyInitList) {
1655         auto *global = TheModule.getGlobalVariable(lateInit.first);
1656         if (global) {
1657           llvm::GlobalVariable *GV = lateInit.second.first;
1658           b.CreateAlignedStore(
1659               global,
1660               b.CreateStructGEP(GV->getValueType(), GV, lateInit.second.second),
1661               CGM.getPointerAlign().getAsAlign());
1662         }
1663       }
1664       b.CreateRetVoid();
1665       // We can't use the normal LLVM global initialisation array, because we
1666       // need to specify that this runs early in library initialisation.
1667       auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
1668           /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
1669           Init, ".objc_early_init_ptr");
1670       InitVar->setSection(".CRT$XCLb");
1671       CGM.addUsedGlobal(InitVar);
1672     }
1673     return nullptr;
1674   }
1675   /// In the v2 ABI, ivar offset variables use the type encoding in their name
1676   /// to trigger linker failures if the types don't match.
1677   std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
1678                                         const ObjCIvarDecl *Ivar) override {
1679     std::string TypeEncoding;
1680     CGM.getContext().getObjCEncodingForType(Ivar->getType(), TypeEncoding);
1681     // Prevent the @ from being interpreted as a symbol version.
1682     std::replace(TypeEncoding.begin(), TypeEncoding.end(),
1683       '@', '\1');
1684     const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
1685       + '.' + Ivar->getNameAsString() + '.' + TypeEncoding;
1686     return Name;
1687   }
1688   llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
1689                               const ObjCInterfaceDecl *Interface,
1690                               const ObjCIvarDecl *Ivar) override {
1691     const std::string Name = GetIVarOffsetVariableName(Ivar->getContainingInterface(), Ivar);
1692     llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
1693     if (!IvarOffsetPointer)
1694       IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false,
1695               llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1696     CharUnits Align = CGM.getIntAlign();
1697     llvm::Value *Offset =
1698         CGF.Builder.CreateAlignedLoad(IntTy, IvarOffsetPointer, Align);
1699     if (Offset->getType() != PtrDiffTy)
1700       Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
1701     return Offset;
1702   }
1703   void GenerateClass(const ObjCImplementationDecl *OID) override {
1704     ASTContext &Context = CGM.getContext();
1705     bool IsCOFF = CGM.getTriple().isOSBinFormatCOFF();
1706 
1707     // Get the class name
1708     ObjCInterfaceDecl *classDecl =
1709         const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
1710     std::string className = classDecl->getNameAsString();
1711     auto *classNameConstant = MakeConstantString(className);
1712 
1713     ConstantInitBuilder builder(CGM);
1714     auto metaclassFields = builder.beginStruct();
1715     // struct objc_class *isa;
1716     metaclassFields.addNullPointer(PtrTy);
1717     // struct objc_class *super_class;
1718     metaclassFields.addNullPointer(PtrTy);
1719     // const char *name;
1720     metaclassFields.add(classNameConstant);
1721     // long version;
1722     metaclassFields.addInt(LongTy, 0);
1723     // unsigned long info;
1724     // objc_class_flag_meta
1725     metaclassFields.addInt(LongTy, 1);
1726     // long instance_size;
1727     // Setting this to zero is consistent with the older ABI, but it might be
1728     // more sensible to set this to sizeof(struct objc_class)
1729     metaclassFields.addInt(LongTy, 0);
1730     // struct objc_ivar_list *ivars;
1731     metaclassFields.addNullPointer(PtrTy);
1732     // struct objc_method_list *methods
1733     // FIXME: Almost identical code is copied and pasted below for the
1734     // class, but refactoring it cleanly requires C++14 generic lambdas.
1735     if (OID->classmeth_begin() == OID->classmeth_end())
1736       metaclassFields.addNullPointer(PtrTy);
1737     else {
1738       SmallVector<ObjCMethodDecl*, 16> ClassMethods;
1739       ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
1740           OID->classmeth_end());
1741       metaclassFields.addBitCast(
1742               GenerateMethodList(className, "", ClassMethods, true),
1743               PtrTy);
1744     }
1745     // void *dtable;
1746     metaclassFields.addNullPointer(PtrTy);
1747     // IMP cxx_construct;
1748     metaclassFields.addNullPointer(PtrTy);
1749     // IMP cxx_destruct;
1750     metaclassFields.addNullPointer(PtrTy);
1751     // struct objc_class *subclass_list
1752     metaclassFields.addNullPointer(PtrTy);
1753     // struct objc_class *sibling_class
1754     metaclassFields.addNullPointer(PtrTy);
1755     // struct objc_protocol_list *protocols;
1756     metaclassFields.addNullPointer(PtrTy);
1757     // struct reference_list *extra_data;
1758     metaclassFields.addNullPointer(PtrTy);
1759     // long abi_version;
1760     metaclassFields.addInt(LongTy, 0);
1761     // struct objc_property_list *properties
1762     metaclassFields.add(GeneratePropertyList(OID, classDecl, /*isClassProperty*/true));
1763 
1764     auto *metaclass = metaclassFields.finishAndCreateGlobal(
1765         ManglePublicSymbol("OBJC_METACLASS_") + className,
1766         CGM.getPointerAlign());
1767 
1768     auto classFields = builder.beginStruct();
1769     // struct objc_class *isa;
1770     classFields.add(metaclass);
1771     // struct objc_class *super_class;
1772     // Get the superclass name.
1773     const ObjCInterfaceDecl * SuperClassDecl =
1774       OID->getClassInterface()->getSuperClass();
1775     llvm::Constant *SuperClass = nullptr;
1776     if (SuperClassDecl) {
1777       auto SuperClassName = SymbolForClass(SuperClassDecl->getNameAsString());
1778       SuperClass = TheModule.getNamedGlobal(SuperClassName);
1779       if (!SuperClass)
1780       {
1781         SuperClass = new llvm::GlobalVariable(TheModule, PtrTy, false,
1782             llvm::GlobalValue::ExternalLinkage, nullptr, SuperClassName);
1783         if (IsCOFF) {
1784           auto Storage = llvm::GlobalValue::DefaultStorageClass;
1785           if (SuperClassDecl->hasAttr<DLLImportAttr>())
1786             Storage = llvm::GlobalValue::DLLImportStorageClass;
1787           else if (SuperClassDecl->hasAttr<DLLExportAttr>())
1788             Storage = llvm::GlobalValue::DLLExportStorageClass;
1789 
1790           cast<llvm::GlobalValue>(SuperClass)->setDLLStorageClass(Storage);
1791         }
1792       }
1793       if (!IsCOFF)
1794         classFields.add(llvm::ConstantExpr::getBitCast(SuperClass, PtrTy));
1795       else
1796         classFields.addNullPointer(PtrTy);
1797     } else
1798       classFields.addNullPointer(PtrTy);
1799     // const char *name;
1800     classFields.add(classNameConstant);
1801     // long version;
1802     classFields.addInt(LongTy, 0);
1803     // unsigned long info;
1804     // !objc_class_flag_meta
1805     classFields.addInt(LongTy, 0);
1806     // long instance_size;
1807     int superInstanceSize = !SuperClassDecl ? 0 :
1808       Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
1809     // Instance size is negative for classes that have not yet had their ivar
1810     // layout calculated.
1811     classFields.addInt(LongTy,
1812       0 - (Context.getASTObjCImplementationLayout(OID).getSize().getQuantity() -
1813       superInstanceSize));
1814 
1815     if (classDecl->all_declared_ivar_begin() == nullptr)
1816       classFields.addNullPointer(PtrTy);
1817     else {
1818       int ivar_count = 0;
1819       for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1820            IVD = IVD->getNextIvar()) ivar_count++;
1821       llvm::DataLayout td(&TheModule);
1822       // struct objc_ivar_list *ivars;
1823       ConstantInitBuilder b(CGM);
1824       auto ivarListBuilder = b.beginStruct();
1825       // int count;
1826       ivarListBuilder.addInt(IntTy, ivar_count);
1827       // size_t size;
1828       llvm::StructType *ObjCIvarTy = llvm::StructType::get(
1829         PtrToInt8Ty,
1830         PtrToInt8Ty,
1831         PtrToInt8Ty,
1832         Int32Ty,
1833         Int32Ty);
1834       ivarListBuilder.addInt(SizeTy, td.getTypeSizeInBits(ObjCIvarTy) /
1835           CGM.getContext().getCharWidth());
1836       // struct objc_ivar ivars[]
1837       auto ivarArrayBuilder = ivarListBuilder.beginArray();
1838       for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1839            IVD = IVD->getNextIvar()) {
1840         auto ivarTy = IVD->getType();
1841         auto ivarBuilder = ivarArrayBuilder.beginStruct();
1842         // const char *name;
1843         ivarBuilder.add(MakeConstantString(IVD->getNameAsString()));
1844         // const char *type;
1845         std::string TypeStr;
1846         //Context.getObjCEncodingForType(ivarTy, TypeStr, IVD, true);
1847         Context.getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, ivarTy, TypeStr, true);
1848         ivarBuilder.add(MakeConstantString(TypeStr));
1849         // int *offset;
1850         uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
1851         uint64_t Offset = BaseOffset - superInstanceSize;
1852         llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
1853         std::string OffsetName = GetIVarOffsetVariableName(classDecl, IVD);
1854         llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
1855         if (OffsetVar)
1856           OffsetVar->setInitializer(OffsetValue);
1857         else
1858           OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
1859             false, llvm::GlobalValue::ExternalLinkage,
1860             OffsetValue, OffsetName);
1861         auto ivarVisibility =
1862             (IVD->getAccessControl() == ObjCIvarDecl::Private ||
1863              IVD->getAccessControl() == ObjCIvarDecl::Package ||
1864              classDecl->getVisibility() == HiddenVisibility) ?
1865                     llvm::GlobalValue::HiddenVisibility :
1866                     llvm::GlobalValue::DefaultVisibility;
1867         OffsetVar->setVisibility(ivarVisibility);
1868         ivarBuilder.add(OffsetVar);
1869         // Ivar size
1870         ivarBuilder.addInt(Int32Ty,
1871             CGM.getContext().getTypeSizeInChars(ivarTy).getQuantity());
1872         // Alignment will be stored as a base-2 log of the alignment.
1873         unsigned align =
1874             llvm::Log2_32(Context.getTypeAlignInChars(ivarTy).getQuantity());
1875         // Objects that require more than 2^64-byte alignment should be impossible!
1876         assert(align < 64);
1877         // uint32_t flags;
1878         // Bits 0-1 are ownership.
1879         // Bit 2 indicates an extended type encoding
1880         // Bits 3-8 contain log2(aligment)
1881         ivarBuilder.addInt(Int32Ty,
1882             (align << 3) | (1<<2) |
1883             FlagsForOwnership(ivarTy.getQualifiers().getObjCLifetime()));
1884         ivarBuilder.finishAndAddTo(ivarArrayBuilder);
1885       }
1886       ivarArrayBuilder.finishAndAddTo(ivarListBuilder);
1887       auto ivarList = ivarListBuilder.finishAndCreateGlobal(".objc_ivar_list",
1888           CGM.getPointerAlign(), /*constant*/ false,
1889           llvm::GlobalValue::PrivateLinkage);
1890       classFields.add(ivarList);
1891     }
1892     // struct objc_method_list *methods
1893     SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
1894     InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
1895         OID->instmeth_end());
1896     for (auto *propImpl : OID->property_impls())
1897       if (propImpl->getPropertyImplementation() ==
1898           ObjCPropertyImplDecl::Synthesize) {
1899         auto addIfExists = [&](const ObjCMethodDecl *OMD) {
1900           if (OMD && OMD->hasBody())
1901             InstanceMethods.push_back(OMD);
1902         };
1903         addIfExists(propImpl->getGetterMethodDecl());
1904         addIfExists(propImpl->getSetterMethodDecl());
1905       }
1906 
1907     if (InstanceMethods.size() == 0)
1908       classFields.addNullPointer(PtrTy);
1909     else
1910       classFields.addBitCast(
1911               GenerateMethodList(className, "", InstanceMethods, false),
1912               PtrTy);
1913     // void *dtable;
1914     classFields.addNullPointer(PtrTy);
1915     // IMP cxx_construct;
1916     classFields.addNullPointer(PtrTy);
1917     // IMP cxx_destruct;
1918     classFields.addNullPointer(PtrTy);
1919     // struct objc_class *subclass_list
1920     classFields.addNullPointer(PtrTy);
1921     // struct objc_class *sibling_class
1922     classFields.addNullPointer(PtrTy);
1923     // struct objc_protocol_list *protocols;
1924     auto RuntimeProtocols = GetRuntimeProtocolList(classDecl->protocol_begin(),
1925                                                    classDecl->protocol_end());
1926     SmallVector<llvm::Constant *, 16> Protocols;
1927     for (const auto *I : RuntimeProtocols)
1928       Protocols.push_back(
1929           llvm::ConstantExpr::getBitCast(GenerateProtocolRef(I),
1930             ProtocolPtrTy));
1931     if (Protocols.empty())
1932       classFields.addNullPointer(PtrTy);
1933     else
1934       classFields.add(GenerateProtocolList(Protocols));
1935     // struct reference_list *extra_data;
1936     classFields.addNullPointer(PtrTy);
1937     // long abi_version;
1938     classFields.addInt(LongTy, 0);
1939     // struct objc_property_list *properties
1940     classFields.add(GeneratePropertyList(OID, classDecl));
1941 
1942     llvm::GlobalVariable *classStruct =
1943       classFields.finishAndCreateGlobal(SymbolForClass(className),
1944         CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
1945 
1946     auto *classRefSymbol = GetClassVar(className);
1947     classRefSymbol->setSection(sectionName<ClassReferenceSection>());
1948     classRefSymbol->setInitializer(llvm::ConstantExpr::getBitCast(classStruct, IdTy));
1949 
1950     if (IsCOFF) {
1951       // we can't import a class struct.
1952       if (OID->getClassInterface()->hasAttr<DLLExportAttr>()) {
1953         classStruct->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1954         cast<llvm::GlobalValue>(classRefSymbol)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1955       }
1956 
1957       if (SuperClass) {
1958         std::pair<llvm::GlobalVariable*, int> v{classStruct, 1};
1959         EarlyInitList.emplace_back(std::string(SuperClass->getName()),
1960                                    std::move(v));
1961       }
1962 
1963     }
1964 
1965 
1966     // Resolve the class aliases, if they exist.
1967     // FIXME: Class pointer aliases shouldn't exist!
1968     if (ClassPtrAlias) {
1969       ClassPtrAlias->replaceAllUsesWith(
1970           llvm::ConstantExpr::getBitCast(classStruct, IdTy));
1971       ClassPtrAlias->eraseFromParent();
1972       ClassPtrAlias = nullptr;
1973     }
1974     if (auto Placeholder =
1975         TheModule.getNamedGlobal(SymbolForClass(className)))
1976       if (Placeholder != classStruct) {
1977         Placeholder->replaceAllUsesWith(
1978             llvm::ConstantExpr::getBitCast(classStruct, Placeholder->getType()));
1979         Placeholder->eraseFromParent();
1980         classStruct->setName(SymbolForClass(className));
1981       }
1982     if (MetaClassPtrAlias) {
1983       MetaClassPtrAlias->replaceAllUsesWith(
1984           llvm::ConstantExpr::getBitCast(metaclass, IdTy));
1985       MetaClassPtrAlias->eraseFromParent();
1986       MetaClassPtrAlias = nullptr;
1987     }
1988     assert(classStruct->getName() == SymbolForClass(className));
1989 
1990     auto classInitRef = new llvm::GlobalVariable(TheModule,
1991         classStruct->getType(), false, llvm::GlobalValue::ExternalLinkage,
1992         classStruct, ManglePublicSymbol("OBJC_INIT_CLASS_") + className);
1993     classInitRef->setSection(sectionName<ClassSection>());
1994     CGM.addUsedGlobal(classInitRef);
1995 
1996     EmittedClass = true;
1997   }
1998   public:
1999     CGObjCGNUstep2(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 10, 4, 2) {
2000       MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
2001                             PtrToObjCSuperTy, SelectorTy);
2002       // struct objc_property
2003       // {
2004       //   const char *name;
2005       //   const char *attributes;
2006       //   const char *type;
2007       //   SEL getter;
2008       //   SEL setter;
2009       // }
2010       PropertyMetadataTy =
2011         llvm::StructType::get(CGM.getLLVMContext(),
2012             { PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
2013     }
2014 
2015 };
2016 
2017 const char *const CGObjCGNUstep2::SectionsBaseNames[8] =
2018 {
2019 "__objc_selectors",
2020 "__objc_classes",
2021 "__objc_class_refs",
2022 "__objc_cats",
2023 "__objc_protocols",
2024 "__objc_protocol_refs",
2025 "__objc_class_aliases",
2026 "__objc_constant_string"
2027 };
2028 
2029 const char *const CGObjCGNUstep2::PECOFFSectionsBaseNames[8] =
2030 {
2031 ".objcrt$SEL",
2032 ".objcrt$CLS",
2033 ".objcrt$CLR",
2034 ".objcrt$CAT",
2035 ".objcrt$PCL",
2036 ".objcrt$PCR",
2037 ".objcrt$CAL",
2038 ".objcrt$STR"
2039 };
2040 
2041 /// Support for the ObjFW runtime.
2042 class CGObjCObjFW: public CGObjCGNU {
2043 protected:
2044   /// The GCC ABI message lookup function.  Returns an IMP pointing to the
2045   /// method implementation for this message.
2046   LazyRuntimeFunction MsgLookupFn;
2047   /// stret lookup function.  While this does not seem to make sense at the
2048   /// first look, this is required to call the correct forwarding function.
2049   LazyRuntimeFunction MsgLookupFnSRet;
2050   /// The GCC ABI superclass message lookup function.  Takes a pointer to a
2051   /// structure describing the receiver and the class, and a selector as
2052   /// arguments.  Returns the IMP for the corresponding method.
2053   LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
2054 
2055   llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
2056                          llvm::Value *cmd, llvm::MDNode *node,
2057                          MessageSendInfo &MSI) override {
2058     CGBuilderTy &Builder = CGF.Builder;
2059     llvm::Value *args[] = {
2060             EnforceType(Builder, Receiver, IdTy),
2061             EnforceType(Builder, cmd, SelectorTy) };
2062 
2063     llvm::CallBase *imp;
2064     if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
2065       imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
2066     else
2067       imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
2068 
2069     imp->setMetadata(msgSendMDKind, node);
2070     return imp;
2071   }
2072 
2073   llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
2074                               llvm::Value *cmd, MessageSendInfo &MSI) override {
2075     CGBuilderTy &Builder = CGF.Builder;
2076     llvm::Value *lookupArgs[] = {
2077         EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
2078     };
2079 
2080     if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
2081       return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
2082     else
2083       return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
2084   }
2085 
2086   llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
2087                              bool isWeak) override {
2088     if (isWeak)
2089       return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
2090 
2091     EmitClassRef(Name);
2092     std::string SymbolName = "_OBJC_CLASS_" + Name;
2093     llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
2094     if (!ClassSymbol)
2095       ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
2096                                              llvm::GlobalValue::ExternalLinkage,
2097                                              nullptr, SymbolName);
2098     return ClassSymbol;
2099   }
2100 
2101 public:
2102   CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
2103     // IMP objc_msg_lookup(id, SEL);
2104     MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
2105     MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
2106                          SelectorTy);
2107     // IMP objc_msg_lookup_super(struct objc_super*, SEL);
2108     MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
2109                           PtrToObjCSuperTy, SelectorTy);
2110     MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
2111                               PtrToObjCSuperTy, SelectorTy);
2112   }
2113 };
2114 } // end anonymous namespace
2115 
2116 /// Emits a reference to a dummy variable which is emitted with each class.
2117 /// This ensures that a linker error will be generated when trying to link
2118 /// together modules where a referenced class is not defined.
2119 void CGObjCGNU::EmitClassRef(const std::string &className) {
2120   std::string symbolRef = "__objc_class_ref_" + className;
2121   // Don't emit two copies of the same symbol
2122   if (TheModule.getGlobalVariable(symbolRef))
2123     return;
2124   std::string symbolName = "__objc_class_name_" + className;
2125   llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
2126   if (!ClassSymbol) {
2127     ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
2128                                            llvm::GlobalValue::ExternalLinkage,
2129                                            nullptr, symbolName);
2130   }
2131   new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
2132     llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
2133 }
2134 
2135 CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
2136                      unsigned protocolClassVersion, unsigned classABI)
2137   : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
2138     VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
2139     MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
2140     ProtocolVersion(protocolClassVersion), ClassABIVersion(classABI) {
2141 
2142   msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
2143   usesSEHExceptions =
2144       cgm.getContext().getTargetInfo().getTriple().isWindowsMSVCEnvironment();
2145 
2146   CodeGenTypes &Types = CGM.getTypes();
2147   IntTy = cast<llvm::IntegerType>(
2148       Types.ConvertType(CGM.getContext().IntTy));
2149   LongTy = cast<llvm::IntegerType>(
2150       Types.ConvertType(CGM.getContext().LongTy));
2151   SizeTy = cast<llvm::IntegerType>(
2152       Types.ConvertType(CGM.getContext().getSizeType()));
2153   PtrDiffTy = cast<llvm::IntegerType>(
2154       Types.ConvertType(CGM.getContext().getPointerDiffType()));
2155   BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
2156 
2157   Int8Ty = llvm::Type::getInt8Ty(VMContext);
2158   // C string type.  Used in lots of places.
2159   PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
2160   ProtocolPtrTy = llvm::PointerType::getUnqual(
2161       Types.ConvertType(CGM.getContext().getObjCProtoType()));
2162 
2163   Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
2164   Zeros[1] = Zeros[0];
2165   NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
2166   // Get the selector Type.
2167   QualType selTy = CGM.getContext().getObjCSelType();
2168   if (QualType() == selTy) {
2169     SelectorTy = PtrToInt8Ty;
2170     SelectorElemTy = Int8Ty;
2171   } else {
2172     SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
2173     SelectorElemTy = CGM.getTypes().ConvertTypeForMem(selTy->getPointeeType());
2174   }
2175 
2176   PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
2177   PtrTy = PtrToInt8Ty;
2178 
2179   Int32Ty = llvm::Type::getInt32Ty(VMContext);
2180   Int64Ty = llvm::Type::getInt64Ty(VMContext);
2181 
2182   IntPtrTy =
2183       CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
2184 
2185   // Object type
2186   QualType UnqualIdTy = CGM.getContext().getObjCIdType();
2187   ASTIdTy = CanQualType();
2188   if (UnqualIdTy != QualType()) {
2189     ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
2190     IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
2191     IdElemTy = CGM.getTypes().ConvertTypeForMem(
2192         ASTIdTy.getTypePtr()->getPointeeType());
2193   } else {
2194     IdTy = PtrToInt8Ty;
2195     IdElemTy = Int8Ty;
2196   }
2197   PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
2198   ProtocolTy = llvm::StructType::get(IdTy,
2199       PtrToInt8Ty, // name
2200       PtrToInt8Ty, // protocols
2201       PtrToInt8Ty, // instance methods
2202       PtrToInt8Ty, // class methods
2203       PtrToInt8Ty, // optional instance methods
2204       PtrToInt8Ty, // optional class methods
2205       PtrToInt8Ty, // properties
2206       PtrToInt8Ty);// optional properties
2207 
2208   // struct objc_property_gsv1
2209   // {
2210   //   const char *name;
2211   //   char attributes;
2212   //   char attributes2;
2213   //   char unused1;
2214   //   char unused2;
2215   //   const char *getter_name;
2216   //   const char *getter_types;
2217   //   const char *setter_name;
2218   //   const char *setter_types;
2219   // }
2220   PropertyMetadataTy = llvm::StructType::get(CGM.getLLVMContext(), {
2221       PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty,
2222       PtrToInt8Ty, PtrToInt8Ty });
2223 
2224   ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);
2225   PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
2226 
2227   llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
2228 
2229   // void objc_exception_throw(id);
2230   ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
2231   ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
2232   // int objc_sync_enter(id);
2233   SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
2234   // int objc_sync_exit(id);
2235   SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);
2236 
2237   // void objc_enumerationMutation (id)
2238   EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);
2239 
2240   // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
2241   GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
2242                      PtrDiffTy, BoolTy);
2243   // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
2244   SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
2245                      PtrDiffTy, IdTy, BoolTy, BoolTy);
2246   // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
2247   GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
2248                            PtrDiffTy, BoolTy, BoolTy);
2249   // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
2250   SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
2251                            PtrDiffTy, BoolTy, BoolTy);
2252 
2253   // IMP type
2254   llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
2255   IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
2256               true));
2257 
2258   const LangOptions &Opts = CGM.getLangOpts();
2259   if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
2260     RuntimeVersion = 10;
2261 
2262   // Don't bother initialising the GC stuff unless we're compiling in GC mode
2263   if (Opts.getGC() != LangOptions::NonGC) {
2264     // This is a bit of an hack.  We should sort this out by having a proper
2265     // CGObjCGNUstep subclass for GC, but we may want to really support the old
2266     // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
2267     // Get selectors needed in GC mode
2268     RetainSel = GetNullarySelector("retain", CGM.getContext());
2269     ReleaseSel = GetNullarySelector("release", CGM.getContext());
2270     AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
2271 
2272     // Get functions needed in GC mode
2273 
2274     // id objc_assign_ivar(id, id, ptrdiff_t);
2275     IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);
2276     // id objc_assign_strongCast (id, id*)
2277     StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
2278                             PtrToIdTy);
2279     // id objc_assign_global(id, id*);
2280     GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);
2281     // id objc_assign_weak(id, id*);
2282     WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);
2283     // id objc_read_weak(id*);
2284     WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);
2285     // void *objc_memmove_collectable(void*, void *, size_t);
2286     MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
2287                    SizeTy);
2288   }
2289 }
2290 
2291 llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
2292                                       const std::string &Name, bool isWeak) {
2293   llvm::Constant *ClassName = MakeConstantString(Name);
2294   // With the incompatible ABI, this will need to be replaced with a direct
2295   // reference to the class symbol.  For the compatible nonfragile ABI we are
2296   // still performing this lookup at run time but emitting the symbol for the
2297   // class externally so that we can make the switch later.
2298   //
2299   // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
2300   // with memoized versions or with static references if it's safe to do so.
2301   if (!isWeak)
2302     EmitClassRef(Name);
2303 
2304   llvm::FunctionCallee ClassLookupFn = CGM.CreateRuntimeFunction(
2305       llvm::FunctionType::get(IdTy, PtrToInt8Ty, true), "objc_lookup_class");
2306   return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
2307 }
2308 
2309 // This has to perform the lookup every time, since posing and related
2310 // techniques can modify the name -> class mapping.
2311 llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
2312                                  const ObjCInterfaceDecl *OID) {
2313   auto *Value =
2314       GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
2315   if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value))
2316     CGM.setGVProperties(ClassSymbol, OID);
2317   return Value;
2318 }
2319 
2320 llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
2321   auto *Value  = GetClassNamed(CGF, "NSAutoreleasePool", false);
2322   if (CGM.getTriple().isOSBinFormatCOFF()) {
2323     if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
2324       IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
2325       TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2326       DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2327 
2328       const VarDecl *VD = nullptr;
2329       for (const auto *Result : DC->lookup(&II))
2330         if ((VD = dyn_cast<VarDecl>(Result)))
2331           break;
2332 
2333       CGM.setGVProperties(ClassSymbol, VD);
2334     }
2335   }
2336   return Value;
2337 }
2338 
2339 llvm::Value *CGObjCGNU::GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
2340                                          const std::string &TypeEncoding) {
2341   SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
2342   llvm::GlobalAlias *SelValue = nullptr;
2343 
2344   for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
2345       e = Types.end() ; i!=e ; i++) {
2346     if (i->first == TypeEncoding) {
2347       SelValue = i->second;
2348       break;
2349     }
2350   }
2351   if (!SelValue) {
2352     SelValue = llvm::GlobalAlias::create(SelectorElemTy, 0,
2353                                          llvm::GlobalValue::PrivateLinkage,
2354                                          ".objc_selector_" + Sel.getAsString(),
2355                                          &TheModule);
2356     Types.emplace_back(TypeEncoding, SelValue);
2357   }
2358 
2359   return SelValue;
2360 }
2361 
2362 Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
2363   llvm::Value *SelValue = GetSelector(CGF, Sel);
2364 
2365   // Store it to a temporary.  Does this satisfy the semantics of
2366   // GetAddrOfSelector?  Hopefully.
2367   Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
2368                                      CGF.getPointerAlign());
2369   CGF.Builder.CreateStore(SelValue, tmp);
2370   return tmp;
2371 }
2372 
2373 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
2374   return GetTypedSelector(CGF, Sel, std::string());
2375 }
2376 
2377 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
2378                                     const ObjCMethodDecl *Method) {
2379   std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
2380   return GetTypedSelector(CGF, Method->getSelector(), SelTypes);
2381 }
2382 
2383 llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
2384   if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
2385     // With the old ABI, there was only one kind of catchall, which broke
2386     // foreign exceptions.  With the new ABI, we use __objc_id_typeinfo as
2387     // a pointer indicating object catchalls, and NULL to indicate real
2388     // catchalls
2389     if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2390       return MakeConstantString("@id");
2391     } else {
2392       return nullptr;
2393     }
2394   }
2395 
2396   // All other types should be Objective-C interface pointer types.
2397   const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
2398   assert(OPT && "Invalid @catch type.");
2399   const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
2400   assert(IDecl && "Invalid @catch type.");
2401   return MakeConstantString(IDecl->getIdentifier()->getName());
2402 }
2403 
2404 llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
2405   if (usesSEHExceptions)
2406     return CGM.getCXXABI().getAddrOfRTTIDescriptor(T);
2407 
2408   if (!CGM.getLangOpts().CPlusPlus)
2409     return CGObjCGNU::GetEHType(T);
2410 
2411   // For Objective-C++, we want to provide the ability to catch both C++ and
2412   // Objective-C objects in the same function.
2413 
2414   // There's a particular fixed type info for 'id'.
2415   if (T->isObjCIdType() ||
2416       T->isObjCQualifiedIdType()) {
2417     llvm::Constant *IDEHType =
2418       CGM.getModule().getGlobalVariable("__objc_id_type_info");
2419     if (!IDEHType)
2420       IDEHType =
2421         new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
2422                                  false,
2423                                  llvm::GlobalValue::ExternalLinkage,
2424                                  nullptr, "__objc_id_type_info");
2425     return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
2426   }
2427 
2428   const ObjCObjectPointerType *PT =
2429     T->getAs<ObjCObjectPointerType>();
2430   assert(PT && "Invalid @catch type.");
2431   const ObjCInterfaceType *IT = PT->getInterfaceType();
2432   assert(IT && "Invalid @catch type.");
2433   std::string className =
2434       std::string(IT->getDecl()->getIdentifier()->getName());
2435 
2436   std::string typeinfoName = "__objc_eh_typeinfo_" + className;
2437 
2438   // Return the existing typeinfo if it exists
2439   llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
2440   if (typeinfo)
2441     return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
2442 
2443   // Otherwise create it.
2444 
2445   // vtable for gnustep::libobjc::__objc_class_type_info
2446   // It's quite ugly hard-coding this.  Ideally we'd generate it using the host
2447   // platform's name mangling.
2448   const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
2449   auto *Vtable = TheModule.getGlobalVariable(vtableName);
2450   if (!Vtable) {
2451     Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
2452                                       llvm::GlobalValue::ExternalLinkage,
2453                                       nullptr, vtableName);
2454   }
2455   llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
2456   auto *BVtable = llvm::ConstantExpr::getBitCast(
2457       llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
2458       PtrToInt8Ty);
2459 
2460   llvm::Constant *typeName =
2461     ExportUniqueString(className, "__objc_eh_typename_");
2462 
2463   ConstantInitBuilder builder(CGM);
2464   auto fields = builder.beginStruct();
2465   fields.add(BVtable);
2466   fields.add(typeName);
2467   llvm::Constant *TI =
2468     fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
2469                                  CGM.getPointerAlign(),
2470                                  /*constant*/ false,
2471                                  llvm::GlobalValue::LinkOnceODRLinkage);
2472   return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
2473 }
2474 
2475 /// Generate an NSConstantString object.
2476 ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
2477 
2478   std::string Str = SL->getString().str();
2479   CharUnits Align = CGM.getPointerAlign();
2480 
2481   // Look for an existing one
2482   llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
2483   if (old != ObjCStrings.end())
2484     return ConstantAddress(old->getValue(), Int8Ty, Align);
2485 
2486   StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
2487 
2488   if (StringClass.empty()) StringClass = "NSConstantString";
2489 
2490   std::string Sym = "_OBJC_CLASS_";
2491   Sym += StringClass;
2492 
2493   llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
2494 
2495   if (!isa)
2496     isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
2497             llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
2498   else if (isa->getType() != PtrToIdTy)
2499     isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
2500 
2501   ConstantInitBuilder Builder(CGM);
2502   auto Fields = Builder.beginStruct();
2503   Fields.add(isa);
2504   Fields.add(MakeConstantString(Str));
2505   Fields.addInt(IntTy, Str.size());
2506   llvm::Constant *ObjCStr =
2507     Fields.finishAndCreateGlobal(".objc_str", Align);
2508   ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
2509   ObjCStrings[Str] = ObjCStr;
2510   ConstantStrings.push_back(ObjCStr);
2511   return ConstantAddress(ObjCStr, Int8Ty, Align);
2512 }
2513 
2514 ///Generates a message send where the super is the receiver.  This is a message
2515 ///send to self with special delivery semantics indicating which class's method
2516 ///should be called.
2517 RValue
2518 CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
2519                                     ReturnValueSlot Return,
2520                                     QualType ResultType,
2521                                     Selector Sel,
2522                                     const ObjCInterfaceDecl *Class,
2523                                     bool isCategoryImpl,
2524                                     llvm::Value *Receiver,
2525                                     bool IsClassMessage,
2526                                     const CallArgList &CallArgs,
2527                                     const ObjCMethodDecl *Method) {
2528   CGBuilderTy &Builder = CGF.Builder;
2529   if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
2530     if (Sel == RetainSel || Sel == AutoreleaseSel) {
2531       return RValue::get(EnforceType(Builder, Receiver,
2532                   CGM.getTypes().ConvertType(ResultType)));
2533     }
2534     if (Sel == ReleaseSel) {
2535       return RValue::get(nullptr);
2536     }
2537   }
2538 
2539   llvm::Value *cmd = GetSelector(CGF, Sel);
2540   CallArgList ActualArgs;
2541 
2542   ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
2543   ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
2544   ActualArgs.addFrom(CallArgs);
2545 
2546   MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
2547 
2548   llvm::Value *ReceiverClass = nullptr;
2549   bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2550   if (isV2ABI) {
2551     ReceiverClass = GetClassNamed(CGF,
2552         Class->getSuperClass()->getNameAsString(), /*isWeak*/false);
2553     if (IsClassMessage)  {
2554       // Load the isa pointer of the superclass is this is a class method.
2555       ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2556                                             llvm::PointerType::getUnqual(IdTy));
2557       ReceiverClass =
2558         Builder.CreateAlignedLoad(IdTy, ReceiverClass, CGF.getPointerAlign());
2559     }
2560     ReceiverClass = EnforceType(Builder, ReceiverClass, IdTy);
2561   } else {
2562     if (isCategoryImpl) {
2563       llvm::FunctionCallee classLookupFunction = nullptr;
2564       if (IsClassMessage)  {
2565         classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2566               IdTy, PtrTy, true), "objc_get_meta_class");
2567       } else {
2568         classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2569               IdTy, PtrTy, true), "objc_get_class");
2570       }
2571       ReceiverClass = Builder.CreateCall(classLookupFunction,
2572           MakeConstantString(Class->getNameAsString()));
2573     } else {
2574       // Set up global aliases for the metaclass or class pointer if they do not
2575       // already exist.  These will are forward-references which will be set to
2576       // pointers to the class and metaclass structure created for the runtime
2577       // load function.  To send a message to super, we look up the value of the
2578       // super_class pointer from either the class or metaclass structure.
2579       if (IsClassMessage)  {
2580         if (!MetaClassPtrAlias) {
2581           MetaClassPtrAlias = llvm::GlobalAlias::create(
2582               IdElemTy, 0, llvm::GlobalValue::InternalLinkage,
2583               ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
2584         }
2585         ReceiverClass = MetaClassPtrAlias;
2586       } else {
2587         if (!ClassPtrAlias) {
2588           ClassPtrAlias = llvm::GlobalAlias::create(
2589               IdElemTy, 0, llvm::GlobalValue::InternalLinkage,
2590               ".objc_class_ref" + Class->getNameAsString(), &TheModule);
2591         }
2592         ReceiverClass = ClassPtrAlias;
2593       }
2594     }
2595     // Cast the pointer to a simplified version of the class structure
2596     llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);
2597     ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2598                                           llvm::PointerType::getUnqual(CastTy));
2599     // Get the superclass pointer
2600     ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
2601     // Load the superclass pointer
2602     ReceiverClass =
2603       Builder.CreateAlignedLoad(IdTy, ReceiverClass, CGF.getPointerAlign());
2604   }
2605   // Construct the structure used to look up the IMP
2606   llvm::StructType *ObjCSuperTy =
2607       llvm::StructType::get(Receiver->getType(), IdTy);
2608 
2609   Address ObjCSuper = CGF.CreateTempAlloca(ObjCSuperTy,
2610                               CGF.getPointerAlign());
2611 
2612   Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
2613   Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
2614 
2615   // Get the IMP
2616   llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
2617   imp = EnforceType(Builder, imp, MSI.MessengerType);
2618 
2619   llvm::Metadata *impMD[] = {
2620       llvm::MDString::get(VMContext, Sel.getAsString()),
2621       llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
2622       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2623           llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
2624   llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
2625 
2626   CGCallee callee(CGCalleeInfo(), imp);
2627 
2628   llvm::CallBase *call;
2629   RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
2630   call->setMetadata(msgSendMDKind, node);
2631   return msgRet;
2632 }
2633 
2634 /// Generate code for a message send expression.
2635 RValue
2636 CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
2637                                ReturnValueSlot Return,
2638                                QualType ResultType,
2639                                Selector Sel,
2640                                llvm::Value *Receiver,
2641                                const CallArgList &CallArgs,
2642                                const ObjCInterfaceDecl *Class,
2643                                const ObjCMethodDecl *Method) {
2644   CGBuilderTy &Builder = CGF.Builder;
2645 
2646   // Strip out message sends to retain / release in GC mode
2647   if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
2648     if (Sel == RetainSel || Sel == AutoreleaseSel) {
2649       return RValue::get(EnforceType(Builder, Receiver,
2650                   CGM.getTypes().ConvertType(ResultType)));
2651     }
2652     if (Sel == ReleaseSel) {
2653       return RValue::get(nullptr);
2654     }
2655   }
2656 
2657   IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
2658   llvm::Value *cmd;
2659   if (Method)
2660     cmd = GetSelector(CGF, Method);
2661   else
2662     cmd = GetSelector(CGF, Sel);
2663   cmd = EnforceType(Builder, cmd, SelectorTy);
2664   Receiver = EnforceType(Builder, Receiver, IdTy);
2665 
2666   llvm::Metadata *impMD[] = {
2667       llvm::MDString::get(VMContext, Sel.getAsString()),
2668       llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
2669       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2670           llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
2671   llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
2672 
2673   CallArgList ActualArgs;
2674   ActualArgs.add(RValue::get(Receiver), ASTIdTy);
2675   ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
2676   ActualArgs.addFrom(CallArgs);
2677 
2678   MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
2679 
2680   // Message sends are expected to return a zero value when the
2681   // receiver is nil.  At one point, this was only guaranteed for
2682   // simple integer and pointer types, but expectations have grown
2683   // over time.
2684   //
2685   // Given a nil receiver, the GNU runtime's message lookup will
2686   // return a stub function that simply sets various return-value
2687   // registers to zero and then returns.  That's good enough for us
2688   // if and only if (1) the calling conventions of that stub are
2689   // compatible with the signature we're using and (2) the registers
2690   // it sets are sufficient to produce a zero value of the return type.
2691   // Rather than doing a whole target-specific analysis, we assume it
2692   // only works for void, integer, and pointer types, and in all
2693   // other cases we do an explicit nil check is emitted code.  In
2694   // addition to ensuring we produe a zero value for other types, this
2695   // sidesteps the few outright CC incompatibilities we know about that
2696   // could otherwise lead to crashes, like when a method is expected to
2697   // return on the x87 floating point stack or adjust the stack pointer
2698   // because of an indirect return.
2699   bool hasParamDestroyedInCallee = false;
2700   bool requiresExplicitZeroResult = false;
2701   bool requiresNilReceiverCheck = [&] {
2702     // We never need a check if we statically know the receiver isn't nil.
2703     if (!canMessageReceiverBeNull(CGF, Method, /*IsSuper*/ false,
2704                                   Class, Receiver))
2705       return false;
2706 
2707     // If there's a consumed argument, we need a nil check.
2708     if (Method && Method->hasParamDestroyedInCallee()) {
2709       hasParamDestroyedInCallee = true;
2710     }
2711 
2712     // If the return value isn't flagged as unused, and the result
2713     // type isn't in our narrow set where we assume compatibility,
2714     // we need a nil check to ensure a nil value.
2715     if (!Return.isUnused()) {
2716       if (ResultType->isVoidType()) {
2717         // void results are definitely okay.
2718       } else if (ResultType->hasPointerRepresentation() &&
2719                  CGM.getTypes().isZeroInitializable(ResultType)) {
2720         // Pointer types should be fine as long as they have
2721         // bitwise-zero null pointers.  But do we need to worry
2722         // about unusual address spaces?
2723       } else if (ResultType->isIntegralOrEnumerationType()) {
2724         // Bitwise zero should always be zero for integral types.
2725         // FIXME: we probably need a size limit here, but we've
2726         // never imposed one before
2727       } else {
2728         // Otherwise, use an explicit check just to be sure.
2729         requiresExplicitZeroResult = true;
2730       }
2731     }
2732 
2733     return hasParamDestroyedInCallee || requiresExplicitZeroResult;
2734   }();
2735 
2736   // We will need to explicitly zero-initialize an aggregate result slot
2737   // if we generally require explicit zeroing and we have an aggregate
2738   // result.
2739   bool requiresExplicitAggZeroing =
2740     requiresExplicitZeroResult && CGF.hasAggregateEvaluationKind(ResultType);
2741 
2742   // The block we're going to end up in after any message send or nil path.
2743   llvm::BasicBlock *continueBB = nullptr;
2744   // The block that eventually branched to continueBB along the nil path.
2745   llvm::BasicBlock *nilPathBB = nullptr;
2746   // The block to do explicit work in along the nil path, if necessary.
2747   llvm::BasicBlock *nilCleanupBB = nullptr;
2748 
2749   // Emit the nil-receiver check.
2750   if (requiresNilReceiverCheck) {
2751     llvm::BasicBlock *messageBB = CGF.createBasicBlock("msgSend");
2752     continueBB = CGF.createBasicBlock("continue");
2753 
2754     // If we need to zero-initialize an aggregate result or destroy
2755     // consumed arguments, we'll need a separate cleanup block.
2756     // Otherwise we can just branch directly to the continuation block.
2757     if (requiresExplicitAggZeroing || hasParamDestroyedInCallee) {
2758       nilCleanupBB = CGF.createBasicBlock("nilReceiverCleanup");
2759     } else {
2760       nilPathBB = Builder.GetInsertBlock();
2761     }
2762 
2763     llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
2764             llvm::Constant::getNullValue(Receiver->getType()));
2765     Builder.CreateCondBr(isNil, nilCleanupBB ? nilCleanupBB : continueBB,
2766                          messageBB);
2767     CGF.EmitBlock(messageBB);
2768   }
2769 
2770   // Get the IMP to call
2771   llvm::Value *imp;
2772 
2773   // If we have non-legacy dispatch specified, we try using the objc_msgSend()
2774   // functions.  These are not supported on all platforms (or all runtimes on a
2775   // given platform), so we
2776   switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
2777     case CodeGenOptions::Legacy:
2778       imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
2779       break;
2780     case CodeGenOptions::Mixed:
2781     case CodeGenOptions::NonLegacy:
2782       if (CGM.ReturnTypeUsesFPRet(ResultType)) {
2783         imp =
2784             CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2785                                       "objc_msgSend_fpret")
2786                 .getCallee();
2787       } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
2788         // The actual types here don't matter - we're going to bitcast the
2789         // function anyway
2790         imp =
2791             CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2792                                       "objc_msgSend_stret")
2793                 .getCallee();
2794       } else {
2795         imp = CGM.CreateRuntimeFunction(
2796                      llvm::FunctionType::get(IdTy, IdTy, true), "objc_msgSend")
2797                   .getCallee();
2798       }
2799   }
2800 
2801   // Reset the receiver in case the lookup modified it
2802   ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy);
2803 
2804   imp = EnforceType(Builder, imp, MSI.MessengerType);
2805 
2806   llvm::CallBase *call;
2807   CGCallee callee(CGCalleeInfo(), imp);
2808   RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
2809   call->setMetadata(msgSendMDKind, node);
2810 
2811   if (requiresNilReceiverCheck) {
2812     llvm::BasicBlock *nonNilPathBB = CGF.Builder.GetInsertBlock();
2813     CGF.Builder.CreateBr(continueBB);
2814 
2815     // Emit the nil path if we decided it was necessary above.
2816     if (nilCleanupBB) {
2817       CGF.EmitBlock(nilCleanupBB);
2818 
2819       if (hasParamDestroyedInCallee) {
2820         destroyCalleeDestroyedArguments(CGF, Method, CallArgs);
2821       }
2822 
2823       if (requiresExplicitAggZeroing) {
2824         assert(msgRet.isAggregate());
2825         Address addr = msgRet.getAggregateAddress();
2826         CGF.EmitNullInitialization(addr, ResultType);
2827       }
2828 
2829       nilPathBB = CGF.Builder.GetInsertBlock();
2830       CGF.Builder.CreateBr(continueBB);
2831     }
2832 
2833     // Enter the continuation block and emit a phi if required.
2834     CGF.EmitBlock(continueBB);
2835     if (msgRet.isScalar()) {
2836       // If the return type is void, do nothing
2837       if (llvm::Value *v = msgRet.getScalarVal()) {
2838         llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
2839         phi->addIncoming(v, nonNilPathBB);
2840         phi->addIncoming(CGM.EmitNullConstant(ResultType), nilPathBB);
2841         msgRet = RValue::get(phi);
2842       }
2843     } else if (msgRet.isAggregate()) {
2844       // Aggregate zeroing is handled in nilCleanupBB when it's required.
2845     } else /* isComplex() */ {
2846       std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
2847       llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
2848       phi->addIncoming(v.first, nonNilPathBB);
2849       phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
2850                        nilPathBB);
2851       llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
2852       phi2->addIncoming(v.second, nonNilPathBB);
2853       phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
2854                         nilPathBB);
2855       msgRet = RValue::getComplex(phi, phi2);
2856     }
2857   }
2858   return msgRet;
2859 }
2860 
2861 /// Generates a MethodList.  Used in construction of a objc_class and
2862 /// objc_category structures.
2863 llvm::Constant *CGObjCGNU::
2864 GenerateMethodList(StringRef ClassName,
2865                    StringRef CategoryName,
2866                    ArrayRef<const ObjCMethodDecl*> Methods,
2867                    bool isClassMethodList) {
2868   if (Methods.empty())
2869     return NULLPtr;
2870 
2871   ConstantInitBuilder Builder(CGM);
2872 
2873   auto MethodList = Builder.beginStruct();
2874   MethodList.addNullPointer(CGM.Int8PtrTy);
2875   MethodList.addInt(Int32Ty, Methods.size());
2876 
2877   // Get the method structure type.
2878   llvm::StructType *ObjCMethodTy =
2879     llvm::StructType::get(CGM.getLLVMContext(), {
2880       PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2881       PtrToInt8Ty, // Method types
2882       IMPTy        // Method pointer
2883     });
2884   bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2885   if (isV2ABI) {
2886     // size_t size;
2887     llvm::DataLayout td(&TheModule);
2888     MethodList.addInt(SizeTy, td.getTypeSizeInBits(ObjCMethodTy) /
2889         CGM.getContext().getCharWidth());
2890     ObjCMethodTy =
2891       llvm::StructType::get(CGM.getLLVMContext(), {
2892         IMPTy,       // Method pointer
2893         PtrToInt8Ty, // Selector
2894         PtrToInt8Ty  // Extended type encoding
2895       });
2896   } else {
2897     ObjCMethodTy =
2898       llvm::StructType::get(CGM.getLLVMContext(), {
2899         PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2900         PtrToInt8Ty, // Method types
2901         IMPTy        // Method pointer
2902       });
2903   }
2904   auto MethodArray = MethodList.beginArray();
2905   ASTContext &Context = CGM.getContext();
2906   for (const auto *OMD : Methods) {
2907     llvm::Constant *FnPtr =
2908       TheModule.getFunction(getSymbolNameForMethod(OMD));
2909     assert(FnPtr && "Can't generate metadata for method that doesn't exist");
2910     auto Method = MethodArray.beginStruct(ObjCMethodTy);
2911     if (isV2ABI) {
2912       Method.addBitCast(FnPtr, IMPTy);
2913       Method.add(GetConstantSelector(OMD->getSelector(),
2914           Context.getObjCEncodingForMethodDecl(OMD)));
2915       Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD, true)));
2916     } else {
2917       Method.add(MakeConstantString(OMD->getSelector().getAsString()));
2918       Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD)));
2919       Method.addBitCast(FnPtr, IMPTy);
2920     }
2921     Method.finishAndAddTo(MethodArray);
2922   }
2923   MethodArray.finishAndAddTo(MethodList);
2924 
2925   // Create an instance of the structure
2926   return MethodList.finishAndCreateGlobal(".objc_method_list",
2927                                           CGM.getPointerAlign());
2928 }
2929 
2930 /// Generates an IvarList.  Used in construction of a objc_class.
2931 llvm::Constant *CGObjCGNU::
2932 GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
2933                  ArrayRef<llvm::Constant *> IvarTypes,
2934                  ArrayRef<llvm::Constant *> IvarOffsets,
2935                  ArrayRef<llvm::Constant *> IvarAlign,
2936                  ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) {
2937   if (IvarNames.empty())
2938     return NULLPtr;
2939 
2940   ConstantInitBuilder Builder(CGM);
2941 
2942   // Structure containing array count followed by array.
2943   auto IvarList = Builder.beginStruct();
2944   IvarList.addInt(IntTy, (int)IvarNames.size());
2945 
2946   // Get the ivar structure type.
2947   llvm::StructType *ObjCIvarTy =
2948       llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);
2949 
2950   // Array of ivar structures.
2951   auto Ivars = IvarList.beginArray(ObjCIvarTy);
2952   for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
2953     auto Ivar = Ivars.beginStruct(ObjCIvarTy);
2954     Ivar.add(IvarNames[i]);
2955     Ivar.add(IvarTypes[i]);
2956     Ivar.add(IvarOffsets[i]);
2957     Ivar.finishAndAddTo(Ivars);
2958   }
2959   Ivars.finishAndAddTo(IvarList);
2960 
2961   // Create an instance of the structure
2962   return IvarList.finishAndCreateGlobal(".objc_ivar_list",
2963                                         CGM.getPointerAlign());
2964 }
2965 
2966 /// Generate a class structure
2967 llvm::Constant *CGObjCGNU::GenerateClassStructure(
2968     llvm::Constant *MetaClass,
2969     llvm::Constant *SuperClass,
2970     unsigned info,
2971     const char *Name,
2972     llvm::Constant *Version,
2973     llvm::Constant *InstanceSize,
2974     llvm::Constant *IVars,
2975     llvm::Constant *Methods,
2976     llvm::Constant *Protocols,
2977     llvm::Constant *IvarOffsets,
2978     llvm::Constant *Properties,
2979     llvm::Constant *StrongIvarBitmap,
2980     llvm::Constant *WeakIvarBitmap,
2981     bool isMeta) {
2982   // Set up the class structure
2983   // Note:  Several of these are char*s when they should be ids.  This is
2984   // because the runtime performs this translation on load.
2985   //
2986   // Fields marked New ABI are part of the GNUstep runtime.  We emit them
2987   // anyway; the classes will still work with the GNU runtime, they will just
2988   // be ignored.
2989   llvm::StructType *ClassTy = llvm::StructType::get(
2990       PtrToInt8Ty,        // isa
2991       PtrToInt8Ty,        // super_class
2992       PtrToInt8Ty,        // name
2993       LongTy,             // version
2994       LongTy,             // info
2995       LongTy,             // instance_size
2996       IVars->getType(),   // ivars
2997       Methods->getType(), // methods
2998       // These are all filled in by the runtime, so we pretend
2999       PtrTy, // dtable
3000       PtrTy, // subclass_list
3001       PtrTy, // sibling_class
3002       PtrTy, // protocols
3003       PtrTy, // gc_object_type
3004       // New ABI:
3005       LongTy,                 // abi_version
3006       IvarOffsets->getType(), // ivar_offsets
3007       Properties->getType(),  // properties
3008       IntPtrTy,               // strong_pointers
3009       IntPtrTy                // weak_pointers
3010       );
3011 
3012   ConstantInitBuilder Builder(CGM);
3013   auto Elements = Builder.beginStruct(ClassTy);
3014 
3015   // Fill in the structure
3016 
3017   // isa
3018   Elements.addBitCast(MetaClass, PtrToInt8Ty);
3019   // super_class
3020   Elements.add(SuperClass);
3021   // name
3022   Elements.add(MakeConstantString(Name, ".class_name"));
3023   // version
3024   Elements.addInt(LongTy, 0);
3025   // info
3026   Elements.addInt(LongTy, info);
3027   // instance_size
3028   if (isMeta) {
3029     llvm::DataLayout td(&TheModule);
3030     Elements.addInt(LongTy,
3031                     td.getTypeSizeInBits(ClassTy) /
3032                       CGM.getContext().getCharWidth());
3033   } else
3034     Elements.add(InstanceSize);
3035   // ivars
3036   Elements.add(IVars);
3037   // methods
3038   Elements.add(Methods);
3039   // These are all filled in by the runtime, so we pretend
3040   // dtable
3041   Elements.add(NULLPtr);
3042   // subclass_list
3043   Elements.add(NULLPtr);
3044   // sibling_class
3045   Elements.add(NULLPtr);
3046   // protocols
3047   Elements.addBitCast(Protocols, PtrTy);
3048   // gc_object_type
3049   Elements.add(NULLPtr);
3050   // abi_version
3051   Elements.addInt(LongTy, ClassABIVersion);
3052   // ivar_offsets
3053   Elements.add(IvarOffsets);
3054   // properties
3055   Elements.add(Properties);
3056   // strong_pointers
3057   Elements.add(StrongIvarBitmap);
3058   // weak_pointers
3059   Elements.add(WeakIvarBitmap);
3060   // Create an instance of the structure
3061   // This is now an externally visible symbol, so that we can speed up class
3062   // messages in the next ABI.  We may already have some weak references to
3063   // this, so check and fix them properly.
3064   std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
3065           std::string(Name));
3066   llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
3067   llvm::Constant *Class =
3068     Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
3069                                    llvm::GlobalValue::ExternalLinkage);
3070   if (ClassRef) {
3071     ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
3072                   ClassRef->getType()));
3073     ClassRef->removeFromParent();
3074     Class->setName(ClassSym);
3075   }
3076   return Class;
3077 }
3078 
3079 llvm::Constant *CGObjCGNU::
3080 GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) {
3081   // Get the method structure type.
3082   llvm::StructType *ObjCMethodDescTy =
3083     llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
3084   ASTContext &Context = CGM.getContext();
3085   ConstantInitBuilder Builder(CGM);
3086   auto MethodList = Builder.beginStruct();
3087   MethodList.addInt(IntTy, Methods.size());
3088   auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
3089   for (auto *M : Methods) {
3090     auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
3091     Method.add(MakeConstantString(M->getSelector().getAsString()));
3092     Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(M)));
3093     Method.finishAndAddTo(MethodArray);
3094   }
3095   MethodArray.finishAndAddTo(MethodList);
3096   return MethodList.finishAndCreateGlobal(".objc_method_list",
3097                                           CGM.getPointerAlign());
3098 }
3099 
3100 // Create the protocol list structure used in classes, categories and so on
3101 llvm::Constant *
3102 CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
3103 
3104   ConstantInitBuilder Builder(CGM);
3105   auto ProtocolList = Builder.beginStruct();
3106   ProtocolList.add(NULLPtr);
3107   ProtocolList.addInt(LongTy, Protocols.size());
3108 
3109   auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
3110   for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
3111       iter != endIter ; iter++) {
3112     llvm::Constant *protocol = nullptr;
3113     llvm::StringMap<llvm::Constant*>::iterator value =
3114       ExistingProtocols.find(*iter);
3115     if (value == ExistingProtocols.end()) {
3116       protocol = GenerateEmptyProtocol(*iter);
3117     } else {
3118       protocol = value->getValue();
3119     }
3120     Elements.addBitCast(protocol, PtrToInt8Ty);
3121   }
3122   Elements.finishAndAddTo(ProtocolList);
3123   return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3124                                             CGM.getPointerAlign());
3125 }
3126 
3127 llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
3128                                             const ObjCProtocolDecl *PD) {
3129   auto protocol = GenerateProtocolRef(PD);
3130   llvm::Type *T =
3131       CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
3132   return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
3133 }
3134 
3135 llvm::Constant *CGObjCGNU::GenerateProtocolRef(const ObjCProtocolDecl *PD) {
3136   llvm::Constant *&protocol = ExistingProtocols[PD->getNameAsString()];
3137   if (!protocol)
3138     GenerateProtocol(PD);
3139   assert(protocol && "Unknown protocol");
3140   return protocol;
3141 }
3142 
3143 llvm::Constant *
3144 CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) {
3145   llvm::Constant *ProtocolList = GenerateProtocolList({});
3146   llvm::Constant *MethodList = GenerateProtocolMethodList({});
3147   MethodList = llvm::ConstantExpr::getBitCast(MethodList, PtrToInt8Ty);
3148   // Protocols are objects containing lists of the methods implemented and
3149   // protocols adopted.
3150   ConstantInitBuilder Builder(CGM);
3151   auto Elements = Builder.beginStruct();
3152 
3153   // The isa pointer must be set to a magic number so the runtime knows it's
3154   // the correct layout.
3155   Elements.add(llvm::ConstantExpr::getIntToPtr(
3156           llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
3157 
3158   Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
3159   Elements.add(ProtocolList); /* .protocol_list */
3160   Elements.add(MethodList);   /* .instance_methods */
3161   Elements.add(MethodList);   /* .class_methods */
3162   Elements.add(MethodList);   /* .optional_instance_methods */
3163   Elements.add(MethodList);   /* .optional_class_methods */
3164   Elements.add(NULLPtr);      /* .properties */
3165   Elements.add(NULLPtr);      /* .optional_properties */
3166   return Elements.finishAndCreateGlobal(SymbolForProtocol(ProtocolName),
3167                                         CGM.getPointerAlign());
3168 }
3169 
3170 void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
3171   if (PD->isNonRuntimeProtocol())
3172     return;
3173 
3174   std::string ProtocolName = PD->getNameAsString();
3175 
3176   // Use the protocol definition, if there is one.
3177   if (const ObjCProtocolDecl *Def = PD->getDefinition())
3178     PD = Def;
3179 
3180   SmallVector<std::string, 16> Protocols;
3181   for (const auto *PI : PD->protocols())
3182     Protocols.push_back(PI->getNameAsString());
3183   SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3184   SmallVector<const ObjCMethodDecl*, 16> OptionalInstanceMethods;
3185   for (const auto *I : PD->instance_methods())
3186     if (I->isOptional())
3187       OptionalInstanceMethods.push_back(I);
3188     else
3189       InstanceMethods.push_back(I);
3190   // Collect information about class methods:
3191   SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3192   SmallVector<const ObjCMethodDecl*, 16> OptionalClassMethods;
3193   for (const auto *I : PD->class_methods())
3194     if (I->isOptional())
3195       OptionalClassMethods.push_back(I);
3196     else
3197       ClassMethods.push_back(I);
3198 
3199   llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
3200   llvm::Constant *InstanceMethodList =
3201     GenerateProtocolMethodList(InstanceMethods);
3202   llvm::Constant *ClassMethodList =
3203     GenerateProtocolMethodList(ClassMethods);
3204   llvm::Constant *OptionalInstanceMethodList =
3205     GenerateProtocolMethodList(OptionalInstanceMethods);
3206   llvm::Constant *OptionalClassMethodList =
3207     GenerateProtocolMethodList(OptionalClassMethods);
3208 
3209   // Property metadata: name, attributes, isSynthesized, setter name, setter
3210   // types, getter name, getter types.
3211   // The isSynthesized value is always set to 0 in a protocol.  It exists to
3212   // simplify the runtime library by allowing it to use the same data
3213   // structures for protocol metadata everywhere.
3214 
3215   llvm::Constant *PropertyList =
3216     GeneratePropertyList(nullptr, PD, false, false);
3217   llvm::Constant *OptionalPropertyList =
3218     GeneratePropertyList(nullptr, PD, false, true);
3219 
3220   // Protocols are objects containing lists of the methods implemented and
3221   // protocols adopted.
3222   // The isa pointer must be set to a magic number so the runtime knows it's
3223   // the correct layout.
3224   ConstantInitBuilder Builder(CGM);
3225   auto Elements = Builder.beginStruct();
3226   Elements.add(
3227       llvm::ConstantExpr::getIntToPtr(
3228           llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
3229   Elements.add(MakeConstantString(ProtocolName));
3230   Elements.add(ProtocolList);
3231   Elements.add(InstanceMethodList);
3232   Elements.add(ClassMethodList);
3233   Elements.add(OptionalInstanceMethodList);
3234   Elements.add(OptionalClassMethodList);
3235   Elements.add(PropertyList);
3236   Elements.add(OptionalPropertyList);
3237   ExistingProtocols[ProtocolName] =
3238     llvm::ConstantExpr::getBitCast(
3239       Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()),
3240       IdTy);
3241 }
3242 void CGObjCGNU::GenerateProtocolHolderCategory() {
3243   // Collect information about instance methods
3244 
3245   ConstantInitBuilder Builder(CGM);
3246   auto Elements = Builder.beginStruct();
3247 
3248   const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
3249   const std::string CategoryName = "AnotherHack";
3250   Elements.add(MakeConstantString(CategoryName));
3251   Elements.add(MakeConstantString(ClassName));
3252   // Instance method list
3253   Elements.addBitCast(GenerateMethodList(
3254           ClassName, CategoryName, {}, false), PtrTy);
3255   // Class method list
3256   Elements.addBitCast(GenerateMethodList(
3257           ClassName, CategoryName, {}, true), PtrTy);
3258 
3259   // Protocol list
3260   ConstantInitBuilder ProtocolListBuilder(CGM);
3261   auto ProtocolList = ProtocolListBuilder.beginStruct();
3262   ProtocolList.add(NULLPtr);
3263   ProtocolList.addInt(LongTy, ExistingProtocols.size());
3264   auto ProtocolElements = ProtocolList.beginArray(PtrTy);
3265   for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
3266        iter != endIter ; iter++) {
3267     ProtocolElements.addBitCast(iter->getValue(), PtrTy);
3268   }
3269   ProtocolElements.finishAndAddTo(ProtocolList);
3270   Elements.addBitCast(
3271                    ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3272                                                       CGM.getPointerAlign()),
3273                    PtrTy);
3274   Categories.push_back(llvm::ConstantExpr::getBitCast(
3275         Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
3276         PtrTy));
3277 }
3278 
3279 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
3280 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
3281 /// bits set to their values, LSB first, while larger ones are stored in a
3282 /// structure of this / form:
3283 ///
3284 /// struct { int32_t length; int32_t values[length]; };
3285 ///
3286 /// The values in the array are stored in host-endian format, with the least
3287 /// significant bit being assumed to come first in the bitfield.  Therefore, a
3288 /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
3289 /// bitfield / with the 63rd bit set will be 1<<64.
3290 llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
3291   int bitCount = bits.size();
3292   int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
3293   if (bitCount < ptrBits) {
3294     uint64_t val = 1;
3295     for (int i=0 ; i<bitCount ; ++i) {
3296       if (bits[i]) val |= 1ULL<<(i+1);
3297     }
3298     return llvm::ConstantInt::get(IntPtrTy, val);
3299   }
3300   SmallVector<llvm::Constant *, 8> values;
3301   int v=0;
3302   while (v < bitCount) {
3303     int32_t word = 0;
3304     for (int i=0 ; (i<32) && (v<bitCount)  ; ++i) {
3305       if (bits[v]) word |= 1<<i;
3306       v++;
3307     }
3308     values.push_back(llvm::ConstantInt::get(Int32Ty, word));
3309   }
3310 
3311   ConstantInitBuilder builder(CGM);
3312   auto fields = builder.beginStruct();
3313   fields.addInt(Int32Ty, values.size());
3314   auto array = fields.beginArray();
3315   for (auto *v : values) array.add(v);
3316   array.finishAndAddTo(fields);
3317 
3318   llvm::Constant *GS =
3319     fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
3320   llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
3321   return ptr;
3322 }
3323 
3324 llvm::Constant *CGObjCGNU::GenerateCategoryProtocolList(const
3325     ObjCCategoryDecl *OCD) {
3326   const auto &RefPro = OCD->getReferencedProtocols();
3327   const auto RuntimeProtos =
3328       GetRuntimeProtocolList(RefPro.begin(), RefPro.end());
3329   SmallVector<std::string, 16> Protocols;
3330   for (const auto *PD : RuntimeProtos)
3331     Protocols.push_back(PD->getNameAsString());
3332   return GenerateProtocolList(Protocols);
3333 }
3334 
3335 void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
3336   const ObjCInterfaceDecl *Class = OCD->getClassInterface();
3337   std::string ClassName = Class->getNameAsString();
3338   std::string CategoryName = OCD->getNameAsString();
3339 
3340   // Collect the names of referenced protocols
3341   const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
3342 
3343   ConstantInitBuilder Builder(CGM);
3344   auto Elements = Builder.beginStruct();
3345   Elements.add(MakeConstantString(CategoryName));
3346   Elements.add(MakeConstantString(ClassName));
3347   // Instance method list
3348   SmallVector<ObjCMethodDecl*, 16> InstanceMethods;
3349   InstanceMethods.insert(InstanceMethods.begin(), OCD->instmeth_begin(),
3350       OCD->instmeth_end());
3351   Elements.addBitCast(
3352           GenerateMethodList(ClassName, CategoryName, InstanceMethods, false),
3353           PtrTy);
3354   // Class method list
3355 
3356   SmallVector<ObjCMethodDecl*, 16> ClassMethods;
3357   ClassMethods.insert(ClassMethods.begin(), OCD->classmeth_begin(),
3358       OCD->classmeth_end());
3359   Elements.addBitCast(
3360           GenerateMethodList(ClassName, CategoryName, ClassMethods, true),
3361           PtrTy);
3362   // Protocol list
3363   Elements.addBitCast(GenerateCategoryProtocolList(CatDecl), PtrTy);
3364   if (isRuntime(ObjCRuntime::GNUstep, 2)) {
3365     const ObjCCategoryDecl *Category =
3366       Class->FindCategoryDeclaration(OCD->getIdentifier());
3367     if (Category) {
3368       // Instance properties
3369       Elements.addBitCast(GeneratePropertyList(OCD, Category, false), PtrTy);
3370       // Class properties
3371       Elements.addBitCast(GeneratePropertyList(OCD, Category, true), PtrTy);
3372     } else {
3373       Elements.addNullPointer(PtrTy);
3374       Elements.addNullPointer(PtrTy);
3375     }
3376   }
3377 
3378   Categories.push_back(llvm::ConstantExpr::getBitCast(
3379         Elements.finishAndCreateGlobal(
3380           std::string(".objc_category_")+ClassName+CategoryName,
3381           CGM.getPointerAlign()),
3382         PtrTy));
3383 }
3384 
3385 llvm::Constant *CGObjCGNU::GeneratePropertyList(const Decl *Container,
3386     const ObjCContainerDecl *OCD,
3387     bool isClassProperty,
3388     bool protocolOptionalProperties) {
3389 
3390   SmallVector<const ObjCPropertyDecl *, 16> Properties;
3391   llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
3392   bool isProtocol = isa<ObjCProtocolDecl>(OCD);
3393   ASTContext &Context = CGM.getContext();
3394 
3395   std::function<void(const ObjCProtocolDecl *Proto)> collectProtocolProperties
3396     = [&](const ObjCProtocolDecl *Proto) {
3397       for (const auto *P : Proto->protocols())
3398         collectProtocolProperties(P);
3399       for (const auto *PD : Proto->properties()) {
3400         if (isClassProperty != PD->isClassProperty())
3401           continue;
3402         // Skip any properties that are declared in protocols that this class
3403         // conforms to but are not actually implemented by this class.
3404         if (!isProtocol && !Context.getObjCPropertyImplDeclForPropertyDecl(PD, Container))
3405           continue;
3406         if (!PropertySet.insert(PD->getIdentifier()).second)
3407           continue;
3408         Properties.push_back(PD);
3409       }
3410     };
3411 
3412   if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3413     for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
3414       for (auto *PD : ClassExt->properties()) {
3415         if (isClassProperty != PD->isClassProperty())
3416           continue;
3417         PropertySet.insert(PD->getIdentifier());
3418         Properties.push_back(PD);
3419       }
3420 
3421   for (const auto *PD : OCD->properties()) {
3422     if (isClassProperty != PD->isClassProperty())
3423       continue;
3424     // If we're generating a list for a protocol, skip optional / required ones
3425     // when generating the other list.
3426     if (isProtocol && (protocolOptionalProperties != PD->isOptional()))
3427       continue;
3428     // Don't emit duplicate metadata for properties that were already in a
3429     // class extension.
3430     if (!PropertySet.insert(PD->getIdentifier()).second)
3431       continue;
3432 
3433     Properties.push_back(PD);
3434   }
3435 
3436   if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3437     for (const auto *P : OID->all_referenced_protocols())
3438       collectProtocolProperties(P);
3439   else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD))
3440     for (const auto *P : CD->protocols())
3441       collectProtocolProperties(P);
3442 
3443   auto numProperties = Properties.size();
3444 
3445   if (numProperties == 0)
3446     return NULLPtr;
3447 
3448   ConstantInitBuilder builder(CGM);
3449   auto propertyList = builder.beginStruct();
3450   auto properties = PushPropertyListHeader(propertyList, numProperties);
3451 
3452   // Add all of the property methods need adding to the method list and to the
3453   // property metadata list.
3454   for (auto *property : Properties) {
3455     bool isSynthesized = false;
3456     bool isDynamic = false;
3457     if (!isProtocol) {
3458       auto *propertyImpl = Context.getObjCPropertyImplDeclForPropertyDecl(property, Container);
3459       if (propertyImpl) {
3460         isSynthesized = (propertyImpl->getPropertyImplementation() ==
3461             ObjCPropertyImplDecl::Synthesize);
3462         isDynamic = (propertyImpl->getPropertyImplementation() ==
3463             ObjCPropertyImplDecl::Dynamic);
3464       }
3465     }
3466     PushProperty(properties, property, Container, isSynthesized, isDynamic);
3467   }
3468   properties.finishAndAddTo(propertyList);
3469 
3470   return propertyList.finishAndCreateGlobal(".objc_property_list",
3471                                             CGM.getPointerAlign());
3472 }
3473 
3474 void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
3475   // Get the class declaration for which the alias is specified.
3476   ObjCInterfaceDecl *ClassDecl =
3477     const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
3478   ClassAliases.emplace_back(ClassDecl->getNameAsString(),
3479                             OAD->getNameAsString());
3480 }
3481 
3482 void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
3483   ASTContext &Context = CGM.getContext();
3484 
3485   // Get the superclass name.
3486   const ObjCInterfaceDecl * SuperClassDecl =
3487     OID->getClassInterface()->getSuperClass();
3488   std::string SuperClassName;
3489   if (SuperClassDecl) {
3490     SuperClassName = SuperClassDecl->getNameAsString();
3491     EmitClassRef(SuperClassName);
3492   }
3493 
3494   // Get the class name
3495   ObjCInterfaceDecl *ClassDecl =
3496       const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
3497   std::string ClassName = ClassDecl->getNameAsString();
3498 
3499   // Emit the symbol that is used to generate linker errors if this class is
3500   // referenced in other modules but not declared.
3501   std::string classSymbolName = "__objc_class_name_" + ClassName;
3502   if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
3503     symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
3504   } else {
3505     new llvm::GlobalVariable(TheModule, LongTy, false,
3506                              llvm::GlobalValue::ExternalLinkage,
3507                              llvm::ConstantInt::get(LongTy, 0),
3508                              classSymbolName);
3509   }
3510 
3511   // Get the size of instances.
3512   int instanceSize =
3513     Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
3514 
3515   // Collect information about instance variables.
3516   SmallVector<llvm::Constant*, 16> IvarNames;
3517   SmallVector<llvm::Constant*, 16> IvarTypes;
3518   SmallVector<llvm::Constant*, 16> IvarOffsets;
3519   SmallVector<llvm::Constant*, 16> IvarAligns;
3520   SmallVector<Qualifiers::ObjCLifetime, 16> IvarOwnership;
3521 
3522   ConstantInitBuilder IvarOffsetBuilder(CGM);
3523   auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
3524   SmallVector<bool, 16> WeakIvars;
3525   SmallVector<bool, 16> StrongIvars;
3526 
3527   int superInstanceSize = !SuperClassDecl ? 0 :
3528     Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
3529   // For non-fragile ivars, set the instance size to 0 - {the size of just this
3530   // class}.  The runtime will then set this to the correct value on load.
3531   if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
3532     instanceSize = 0 - (instanceSize - superInstanceSize);
3533   }
3534 
3535   for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3536        IVD = IVD->getNextIvar()) {
3537       // Store the name
3538       IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
3539       // Get the type encoding for this ivar
3540       std::string TypeStr;
3541       Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);
3542       IvarTypes.push_back(MakeConstantString(TypeStr));
3543       IvarAligns.push_back(llvm::ConstantInt::get(IntTy,
3544             Context.getTypeSize(IVD->getType())));
3545       // Get the offset
3546       uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
3547       uint64_t Offset = BaseOffset;
3548       if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
3549         Offset = BaseOffset - superInstanceSize;
3550       }
3551       llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
3552       // Create the direct offset value
3553       std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
3554           IVD->getNameAsString();
3555 
3556       llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
3557       if (OffsetVar) {
3558         OffsetVar->setInitializer(OffsetValue);
3559         // If this is the real definition, change its linkage type so that
3560         // different modules will use this one, rather than their private
3561         // copy.
3562         OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
3563       } else
3564         OffsetVar = new llvm::GlobalVariable(TheModule, Int32Ty,
3565           false, llvm::GlobalValue::ExternalLinkage,
3566           OffsetValue, OffsetName);
3567       IvarOffsets.push_back(OffsetValue);
3568       IvarOffsetValues.add(OffsetVar);
3569       Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
3570       IvarOwnership.push_back(lt);
3571       switch (lt) {
3572         case Qualifiers::OCL_Strong:
3573           StrongIvars.push_back(true);
3574           WeakIvars.push_back(false);
3575           break;
3576         case Qualifiers::OCL_Weak:
3577           StrongIvars.push_back(false);
3578           WeakIvars.push_back(true);
3579           break;
3580         default:
3581           StrongIvars.push_back(false);
3582           WeakIvars.push_back(false);
3583       }
3584   }
3585   llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
3586   llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
3587   llvm::GlobalVariable *IvarOffsetArray =
3588     IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
3589                                            CGM.getPointerAlign());
3590 
3591   // Collect information about instance methods
3592   SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3593   InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
3594       OID->instmeth_end());
3595 
3596   SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3597   ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
3598       OID->classmeth_end());
3599 
3600   llvm::Constant *Properties = GeneratePropertyList(OID, ClassDecl);
3601 
3602   // Collect the names of referenced protocols
3603   auto RefProtocols = ClassDecl->protocols();
3604   auto RuntimeProtocols =
3605       GetRuntimeProtocolList(RefProtocols.begin(), RefProtocols.end());
3606   SmallVector<std::string, 16> Protocols;
3607   for (const auto *I : RuntimeProtocols)
3608     Protocols.push_back(I->getNameAsString());
3609 
3610   // Get the superclass pointer.
3611   llvm::Constant *SuperClass;
3612   if (!SuperClassName.empty()) {
3613     SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
3614   } else {
3615     SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
3616   }
3617   // Empty vector used to construct empty method lists
3618   SmallVector<llvm::Constant*, 1>  empty;
3619   // Generate the method and instance variable lists
3620   llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
3621       InstanceMethods, false);
3622   llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
3623       ClassMethods, true);
3624   llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
3625       IvarOffsets, IvarAligns, IvarOwnership);
3626   // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
3627   // we emit a symbol containing the offset for each ivar in the class.  This
3628   // allows code compiled for the non-Fragile ABI to inherit from code compiled
3629   // for the legacy ABI, without causing problems.  The converse is also
3630   // possible, but causes all ivar accesses to be fragile.
3631 
3632   // Offset pointer for getting at the correct field in the ivar list when
3633   // setting up the alias.  These are: The base address for the global, the
3634   // ivar array (second field), the ivar in this list (set for each ivar), and
3635   // the offset (third field in ivar structure)
3636   llvm::Type *IndexTy = Int32Ty;
3637   llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
3638       llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 2 : 1), nullptr,
3639       llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 3 : 2) };
3640 
3641   unsigned ivarIndex = 0;
3642   for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3643        IVD = IVD->getNextIvar()) {
3644       const std::string Name = GetIVarOffsetVariableName(ClassDecl, IVD);
3645       offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
3646       // Get the correct ivar field
3647       llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
3648           cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
3649           offsetPointerIndexes);
3650       // Get the existing variable, if one exists.
3651       llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
3652       if (offset) {
3653         offset->setInitializer(offsetValue);
3654         // If this is the real definition, change its linkage type so that
3655         // different modules will use this one, rather than their private
3656         // copy.
3657         offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
3658       } else
3659         // Add a new alias if there isn't one already.
3660         new llvm::GlobalVariable(TheModule, offsetValue->getType(),
3661                 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
3662       ++ivarIndex;
3663   }
3664   llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
3665 
3666   //Generate metaclass for class methods
3667   llvm::Constant *MetaClassStruct = GenerateClassStructure(
3668       NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
3669       NULLPtr, ClassMethodList, NULLPtr, NULLPtr,
3670       GeneratePropertyList(OID, ClassDecl, true), ZeroPtr, ZeroPtr, true);
3671   CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct),
3672                       OID->getClassInterface());
3673 
3674   // Generate the class structure
3675   llvm::Constant *ClassStruct = GenerateClassStructure(
3676       MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
3677       llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
3678       GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
3679       StrongIvarBitmap, WeakIvarBitmap);
3680   CGM.setGVProperties(cast<llvm::GlobalValue>(ClassStruct),
3681                       OID->getClassInterface());
3682 
3683   // Resolve the class aliases, if they exist.
3684   if (ClassPtrAlias) {
3685     ClassPtrAlias->replaceAllUsesWith(
3686         llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
3687     ClassPtrAlias->eraseFromParent();
3688     ClassPtrAlias = nullptr;
3689   }
3690   if (MetaClassPtrAlias) {
3691     MetaClassPtrAlias->replaceAllUsesWith(
3692         llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
3693     MetaClassPtrAlias->eraseFromParent();
3694     MetaClassPtrAlias = nullptr;
3695   }
3696 
3697   // Add class structure to list to be added to the symtab later
3698   ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
3699   Classes.push_back(ClassStruct);
3700 }
3701 
3702 llvm::Function *CGObjCGNU::ModuleInitFunction() {
3703   // Only emit an ObjC load function if no Objective-C stuff has been called
3704   if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
3705       ExistingProtocols.empty() && SelectorTable.empty())
3706     return nullptr;
3707 
3708   // Add all referenced protocols to a category.
3709   GenerateProtocolHolderCategory();
3710 
3711   llvm::StructType *selStructTy = dyn_cast<llvm::StructType>(SelectorElemTy);
3712   llvm::Type *selStructPtrTy = SelectorTy;
3713   if (!selStructTy) {
3714     selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
3715                                         { PtrToInt8Ty, PtrToInt8Ty });
3716     selStructPtrTy = llvm::PointerType::getUnqual(selStructTy);
3717   }
3718 
3719   // Generate statics list:
3720   llvm::Constant *statics = NULLPtr;
3721   if (!ConstantStrings.empty()) {
3722     llvm::GlobalVariable *fileStatics = [&] {
3723       ConstantInitBuilder builder(CGM);
3724       auto staticsStruct = builder.beginStruct();
3725 
3726       StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
3727       if (stringClass.empty()) stringClass = "NXConstantString";
3728       staticsStruct.add(MakeConstantString(stringClass,
3729                                            ".objc_static_class_name"));
3730 
3731       auto array = staticsStruct.beginArray();
3732       array.addAll(ConstantStrings);
3733       array.add(NULLPtr);
3734       array.finishAndAddTo(staticsStruct);
3735 
3736       return staticsStruct.finishAndCreateGlobal(".objc_statics",
3737                                                  CGM.getPointerAlign());
3738     }();
3739 
3740     ConstantInitBuilder builder(CGM);
3741     auto allStaticsArray = builder.beginArray(fileStatics->getType());
3742     allStaticsArray.add(fileStatics);
3743     allStaticsArray.addNullPointer(fileStatics->getType());
3744 
3745     statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
3746                                                     CGM.getPointerAlign());
3747     statics = llvm::ConstantExpr::getBitCast(statics, PtrTy);
3748   }
3749 
3750   // Array of classes, categories, and constant objects.
3751 
3752   SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
3753   unsigned selectorCount;
3754 
3755   // Pointer to an array of selectors used in this module.
3756   llvm::GlobalVariable *selectorList = [&] {
3757     ConstantInitBuilder builder(CGM);
3758     auto selectors = builder.beginArray(selStructTy);
3759     auto &table = SelectorTable; // MSVC workaround
3760     std::vector<Selector> allSelectors;
3761     for (auto &entry : table)
3762       allSelectors.push_back(entry.first);
3763     llvm::sort(allSelectors);
3764 
3765     for (auto &untypedSel : allSelectors) {
3766       std::string selNameStr = untypedSel.getAsString();
3767       llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
3768 
3769       for (TypedSelector &sel : table[untypedSel]) {
3770         llvm::Constant *selectorTypeEncoding = NULLPtr;
3771         if (!sel.first.empty())
3772           selectorTypeEncoding =
3773             MakeConstantString(sel.first, ".objc_sel_types");
3774 
3775         auto selStruct = selectors.beginStruct(selStructTy);
3776         selStruct.add(selName);
3777         selStruct.add(selectorTypeEncoding);
3778         selStruct.finishAndAddTo(selectors);
3779 
3780         // Store the selector alias for later replacement
3781         selectorAliases.push_back(sel.second);
3782       }
3783     }
3784 
3785     // Remember the number of entries in the selector table.
3786     selectorCount = selectors.size();
3787 
3788     // NULL-terminate the selector list.  This should not actually be required,
3789     // because the selector list has a length field.  Unfortunately, the GCC
3790     // runtime decides to ignore the length field and expects a NULL terminator,
3791     // and GCC cooperates with this by always setting the length to 0.
3792     auto selStruct = selectors.beginStruct(selStructTy);
3793     selStruct.add(NULLPtr);
3794     selStruct.add(NULLPtr);
3795     selStruct.finishAndAddTo(selectors);
3796 
3797     return selectors.finishAndCreateGlobal(".objc_selector_list",
3798                                            CGM.getPointerAlign());
3799   }();
3800 
3801   // Now that all of the static selectors exist, create pointers to them.
3802   for (unsigned i = 0; i < selectorCount; ++i) {
3803     llvm::Constant *idxs[] = {
3804       Zeros[0],
3805       llvm::ConstantInt::get(Int32Ty, i)
3806     };
3807     // FIXME: We're generating redundant loads and stores here!
3808     llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
3809         selectorList->getValueType(), selectorList, idxs);
3810     // If selectors are defined as an opaque type, cast the pointer to this
3811     // type.
3812     selPtr = llvm::ConstantExpr::getBitCast(selPtr, SelectorTy);
3813     selectorAliases[i]->replaceAllUsesWith(selPtr);
3814     selectorAliases[i]->eraseFromParent();
3815   }
3816 
3817   llvm::GlobalVariable *symtab = [&] {
3818     ConstantInitBuilder builder(CGM);
3819     auto symtab = builder.beginStruct();
3820 
3821     // Number of static selectors
3822     symtab.addInt(LongTy, selectorCount);
3823 
3824     symtab.addBitCast(selectorList, selStructPtrTy);
3825 
3826     // Number of classes defined.
3827     symtab.addInt(CGM.Int16Ty, Classes.size());
3828     // Number of categories defined
3829     symtab.addInt(CGM.Int16Ty, Categories.size());
3830 
3831     // Create an array of classes, then categories, then static object instances
3832     auto classList = symtab.beginArray(PtrToInt8Ty);
3833     classList.addAll(Classes);
3834     classList.addAll(Categories);
3835     //  NULL-terminated list of static object instances (mainly constant strings)
3836     classList.add(statics);
3837     classList.add(NULLPtr);
3838     classList.finishAndAddTo(symtab);
3839 
3840     // Construct the symbol table.
3841     return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
3842   }();
3843 
3844   // The symbol table is contained in a module which has some version-checking
3845   // constants
3846   llvm::Constant *module = [&] {
3847     llvm::Type *moduleEltTys[] = {
3848       LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
3849     };
3850     llvm::StructType *moduleTy = llvm::StructType::get(
3851         CGM.getLLVMContext(),
3852         ArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
3853 
3854     ConstantInitBuilder builder(CGM);
3855     auto module = builder.beginStruct(moduleTy);
3856     // Runtime version, used for ABI compatibility checking.
3857     module.addInt(LongTy, RuntimeVersion);
3858     // sizeof(ModuleTy)
3859     module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
3860 
3861     // The path to the source file where this module was declared
3862     SourceManager &SM = CGM.getContext().getSourceManager();
3863     OptionalFileEntryRef mainFile = SM.getFileEntryRefForID(SM.getMainFileID());
3864     std::string path =
3865         (mainFile->getDir().getName() + "/" + mainFile->getName()).str();
3866     module.add(MakeConstantString(path, ".objc_source_file_name"));
3867     module.add(symtab);
3868 
3869     if (RuntimeVersion >= 10) {
3870       switch (CGM.getLangOpts().getGC()) {
3871       case LangOptions::GCOnly:
3872         module.addInt(IntTy, 2);
3873         break;
3874       case LangOptions::NonGC:
3875         if (CGM.getLangOpts().ObjCAutoRefCount)
3876           module.addInt(IntTy, 1);
3877         else
3878           module.addInt(IntTy, 0);
3879         break;
3880       case LangOptions::HybridGC:
3881         module.addInt(IntTy, 1);
3882         break;
3883       }
3884     }
3885 
3886     return module.finishAndCreateGlobal("", CGM.getPointerAlign());
3887   }();
3888 
3889   // Create the load function calling the runtime entry point with the module
3890   // structure
3891   llvm::Function * LoadFunction = llvm::Function::Create(
3892       llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
3893       llvm::GlobalValue::InternalLinkage, ".objc_load_function",
3894       &TheModule);
3895   llvm::BasicBlock *EntryBB =
3896       llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
3897   CGBuilderTy Builder(CGM, VMContext);
3898   Builder.SetInsertPoint(EntryBB);
3899 
3900   llvm::FunctionType *FT =
3901     llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
3902   llvm::FunctionCallee Register =
3903       CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
3904   Builder.CreateCall(Register, module);
3905 
3906   if (!ClassAliases.empty()) {
3907     llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
3908     llvm::FunctionType *RegisterAliasTy =
3909       llvm::FunctionType::get(Builder.getVoidTy(),
3910                               ArgTypes, false);
3911     llvm::Function *RegisterAlias = llvm::Function::Create(
3912       RegisterAliasTy,
3913       llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
3914       &TheModule);
3915     llvm::BasicBlock *AliasBB =
3916       llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
3917     llvm::BasicBlock *NoAliasBB =
3918       llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
3919 
3920     // Branch based on whether the runtime provided class_registerAlias_np()
3921     llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
3922             llvm::Constant::getNullValue(RegisterAlias->getType()));
3923     Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
3924 
3925     // The true branch (has alias registration function):
3926     Builder.SetInsertPoint(AliasBB);
3927     // Emit alias registration calls:
3928     for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
3929        iter != ClassAliases.end(); ++iter) {
3930        llvm::Constant *TheClass =
3931           TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
3932        if (TheClass) {
3933          TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
3934          Builder.CreateCall(RegisterAlias,
3935                             {TheClass, MakeConstantString(iter->second)});
3936        }
3937     }
3938     // Jump to end:
3939     Builder.CreateBr(NoAliasBB);
3940 
3941     // Missing alias registration function, just return from the function:
3942     Builder.SetInsertPoint(NoAliasBB);
3943   }
3944   Builder.CreateRetVoid();
3945 
3946   return LoadFunction;
3947 }
3948 
3949 llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
3950                                           const ObjCContainerDecl *CD) {
3951   CodeGenTypes &Types = CGM.getTypes();
3952   llvm::FunctionType *MethodTy =
3953     Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
3954   std::string FunctionName = getSymbolNameForMethod(OMD);
3955 
3956   llvm::Function *Method
3957     = llvm::Function::Create(MethodTy,
3958                              llvm::GlobalValue::InternalLinkage,
3959                              FunctionName,
3960                              &TheModule);
3961   return Method;
3962 }
3963 
3964 void CGObjCGNU::GenerateDirectMethodPrologue(CodeGenFunction &CGF,
3965                                              llvm::Function *Fn,
3966                                              const ObjCMethodDecl *OMD,
3967                                              const ObjCContainerDecl *CD) {
3968   // GNU runtime doesn't support direct calls at this time
3969 }
3970 
3971 llvm::FunctionCallee CGObjCGNU::GetPropertyGetFunction() {
3972   return GetPropertyFn;
3973 }
3974 
3975 llvm::FunctionCallee CGObjCGNU::GetPropertySetFunction() {
3976   return SetPropertyFn;
3977 }
3978 
3979 llvm::FunctionCallee CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
3980                                                                 bool copy) {
3981   return nullptr;
3982 }
3983 
3984 llvm::FunctionCallee CGObjCGNU::GetGetStructFunction() {
3985   return GetStructPropertyFn;
3986 }
3987 
3988 llvm::FunctionCallee CGObjCGNU::GetSetStructFunction() {
3989   return SetStructPropertyFn;
3990 }
3991 
3992 llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectGetFunction() {
3993   return nullptr;
3994 }
3995 
3996 llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectSetFunction() {
3997   return nullptr;
3998 }
3999 
4000 llvm::FunctionCallee CGObjCGNU::EnumerationMutationFunction() {
4001   return EnumerationMutationFn;
4002 }
4003 
4004 void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
4005                                      const ObjCAtSynchronizedStmt &S) {
4006   EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
4007 }
4008 
4009 
4010 void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
4011                             const ObjCAtTryStmt &S) {
4012   // Unlike the Apple non-fragile runtimes, which also uses
4013   // unwind-based zero cost exceptions, the GNU Objective C runtime's
4014   // EH support isn't a veneer over C++ EH.  Instead, exception
4015   // objects are created by objc_exception_throw and destroyed by
4016   // the personality function; this avoids the need for bracketing
4017   // catch handlers with calls to __blah_begin_catch/__blah_end_catch
4018   // (or even _Unwind_DeleteException), but probably doesn't
4019   // interoperate very well with foreign exceptions.
4020   //
4021   // In Objective-C++ mode, we actually emit something equivalent to the C++
4022   // exception handler.
4023   EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
4024 }
4025 
4026 void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
4027                               const ObjCAtThrowStmt &S,
4028                               bool ClearInsertionPoint) {
4029   llvm::Value *ExceptionAsObject;
4030   bool isRethrow = false;
4031 
4032   if (const Expr *ThrowExpr = S.getThrowExpr()) {
4033     llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
4034     ExceptionAsObject = Exception;
4035   } else {
4036     assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
4037            "Unexpected rethrow outside @catch block.");
4038     ExceptionAsObject = CGF.ObjCEHValueStack.back();
4039     isRethrow = true;
4040   }
4041   if (isRethrow && usesSEHExceptions) {
4042     // For SEH, ExceptionAsObject may be undef, because the catch handler is
4043     // not passed it for catchalls and so it is not visible to the catch
4044     // funclet.  The real thrown object will still be live on the stack at this
4045     // point and will be rethrown.  If we are explicitly rethrowing the object
4046     // that was passed into the `@catch` block, then this code path is not
4047     // reached and we will instead call `objc_exception_throw` with an explicit
4048     // argument.
4049     llvm::CallBase *Throw = CGF.EmitRuntimeCallOrInvoke(ExceptionReThrowFn);
4050     Throw->setDoesNotReturn();
4051   }
4052   else {
4053     ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
4054     llvm::CallBase *Throw =
4055         CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
4056     Throw->setDoesNotReturn();
4057   }
4058   CGF.Builder.CreateUnreachable();
4059   if (ClearInsertionPoint)
4060     CGF.Builder.ClearInsertionPoint();
4061 }
4062 
4063 llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
4064                                           Address AddrWeakObj) {
4065   CGBuilderTy &B = CGF.Builder;
4066   return B.CreateCall(WeakReadFn,
4067                       EnforceType(B, AddrWeakObj.getPointer(), PtrToIdTy));
4068 }
4069 
4070 void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
4071                                    llvm::Value *src, Address dst) {
4072   CGBuilderTy &B = CGF.Builder;
4073   src = EnforceType(B, src, IdTy);
4074   llvm::Value *dstVal = EnforceType(B, dst.getPointer(), PtrToIdTy);
4075   B.CreateCall(WeakAssignFn, {src, dstVal});
4076 }
4077 
4078 void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
4079                                      llvm::Value *src, Address dst,
4080                                      bool threadlocal) {
4081   CGBuilderTy &B = CGF.Builder;
4082   src = EnforceType(B, src, IdTy);
4083   llvm::Value *dstVal = EnforceType(B, dst.getPointer(), PtrToIdTy);
4084   // FIXME. Add threadloca assign API
4085   assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
4086   B.CreateCall(GlobalAssignFn, {src, dstVal});
4087 }
4088 
4089 void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
4090                                    llvm::Value *src, Address dst,
4091                                    llvm::Value *ivarOffset) {
4092   CGBuilderTy &B = CGF.Builder;
4093   src = EnforceType(B, src, IdTy);
4094   llvm::Value *dstVal = EnforceType(B, dst.getPointer(), IdTy);
4095   B.CreateCall(IvarAssignFn, {src, dstVal, ivarOffset});
4096 }
4097 
4098 void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
4099                                          llvm::Value *src, Address dst) {
4100   CGBuilderTy &B = CGF.Builder;
4101   src = EnforceType(B, src, IdTy);
4102   llvm::Value *dstVal = EnforceType(B, dst.getPointer(), PtrToIdTy);
4103   B.CreateCall(StrongCastAssignFn, {src, dstVal});
4104 }
4105 
4106 void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
4107                                          Address DestPtr,
4108                                          Address SrcPtr,
4109                                          llvm::Value *Size) {
4110   CGBuilderTy &B = CGF.Builder;
4111   llvm::Value *DestPtrVal = EnforceType(B, DestPtr.getPointer(), PtrTy);
4112   llvm::Value *SrcPtrVal = EnforceType(B, SrcPtr.getPointer(), PtrTy);
4113 
4114   B.CreateCall(MemMoveFn, {DestPtrVal, SrcPtrVal, Size});
4115 }
4116 
4117 llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
4118                               const ObjCInterfaceDecl *ID,
4119                               const ObjCIvarDecl *Ivar) {
4120   const std::string Name = GetIVarOffsetVariableName(ID, Ivar);
4121   // Emit the variable and initialize it with what we think the correct value
4122   // is.  This allows code compiled with non-fragile ivars to work correctly
4123   // when linked against code which isn't (most of the time).
4124   llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
4125   if (!IvarOffsetPointer)
4126     IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
4127             llvm::Type::getInt32PtrTy(VMContext), false,
4128             llvm::GlobalValue::ExternalLinkage, nullptr, Name);
4129   return IvarOffsetPointer;
4130 }
4131 
4132 LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
4133                                        QualType ObjectTy,
4134                                        llvm::Value *BaseValue,
4135                                        const ObjCIvarDecl *Ivar,
4136                                        unsigned CVRQualifiers) {
4137   const ObjCInterfaceDecl *ID =
4138     ObjectTy->castAs<ObjCObjectType>()->getInterface();
4139   return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4140                                   EmitIvarOffset(CGF, ID, Ivar));
4141 }
4142 
4143 static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
4144                                                   const ObjCInterfaceDecl *OID,
4145                                                   const ObjCIvarDecl *OIVD) {
4146   for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
4147        next = next->getNextIvar()) {
4148     if (OIVD == next)
4149       return OID;
4150   }
4151 
4152   // Otherwise check in the super class.
4153   if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
4154     return FindIvarInterface(Context, Super, OIVD);
4155 
4156   return nullptr;
4157 }
4158 
4159 llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
4160                          const ObjCInterfaceDecl *Interface,
4161                          const ObjCIvarDecl *Ivar) {
4162   if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
4163     Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
4164 
4165     // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
4166     // and ExternalLinkage, so create a reference to the ivar global and rely on
4167     // the definition being created as part of GenerateClass.
4168     if (RuntimeVersion < 10 ||
4169         CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
4170       return CGF.Builder.CreateZExtOrBitCast(
4171           CGF.Builder.CreateAlignedLoad(
4172               Int32Ty, CGF.Builder.CreateAlignedLoad(
4173                            llvm::Type::getInt32PtrTy(VMContext),
4174                            ObjCIvarOffsetVariable(Interface, Ivar),
4175                            CGF.getPointerAlign(), "ivar"),
4176               CharUnits::fromQuantity(4)),
4177           PtrDiffTy);
4178     std::string name = "__objc_ivar_offset_value_" +
4179       Interface->getNameAsString() +"." + Ivar->getNameAsString();
4180     CharUnits Align = CGM.getIntAlign();
4181     llvm::Value *Offset = TheModule.getGlobalVariable(name);
4182     if (!Offset) {
4183       auto GV = new llvm::GlobalVariable(TheModule, IntTy,
4184           false, llvm::GlobalValue::LinkOnceAnyLinkage,
4185           llvm::Constant::getNullValue(IntTy), name);
4186       GV->setAlignment(Align.getAsAlign());
4187       Offset = GV;
4188     }
4189     Offset = CGF.Builder.CreateAlignedLoad(IntTy, Offset, Align);
4190     if (Offset->getType() != PtrDiffTy)
4191       Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
4192     return Offset;
4193   }
4194   uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
4195   return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
4196 }
4197 
4198 CGObjCRuntime *
4199 clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
4200   auto Runtime = CGM.getLangOpts().ObjCRuntime;
4201   switch (Runtime.getKind()) {
4202   case ObjCRuntime::GNUstep:
4203     if (Runtime.getVersion() >= VersionTuple(2, 0))
4204       return new CGObjCGNUstep2(CGM);
4205     return new CGObjCGNUstep(CGM);
4206 
4207   case ObjCRuntime::GCC:
4208     return new CGObjCGCC(CGM);
4209 
4210   case ObjCRuntime::ObjFW:
4211     return new CGObjCObjFW(CGM);
4212 
4213   case ObjCRuntime::FragileMacOSX:
4214   case ObjCRuntime::MacOSX:
4215   case ObjCRuntime::iOS:
4216   case ObjCRuntime::WatchOS:
4217     llvm_unreachable("these runtimes are not GNU runtimes");
4218   }
4219   llvm_unreachable("bad runtime");
4220 }
4221