xref: /freebsd/contrib/llvm-project/clang/lib/CodeGen/CGObjCGNU.cpp (revision 1db9f3b21e39176dd5b67cf8ac378633b172463e)
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     }
1018 
1019     //  struct
1020     //  {
1021     //    Class isa;
1022     //    uint32_t flags;
1023     //    uint32_t length; // Number of codepoints
1024     //    uint32_t size; // Number of bytes
1025     //    uint32_t hash;
1026     //    const char *data;
1027     //  };
1028 
1029     ConstantInitBuilder Builder(CGM);
1030     auto Fields = Builder.beginStruct();
1031     if (!CGM.getTriple().isOSBinFormatCOFF()) {
1032       Fields.add(isa);
1033     } else {
1034       Fields.addNullPointer(PtrTy);
1035     }
1036     // For now, all non-ASCII strings are represented as UTF-16.  As such, the
1037     // number of bytes is simply double the number of UTF-16 codepoints.  In
1038     // ASCII strings, the number of bytes is equal to the number of non-ASCII
1039     // codepoints.
1040     if (isNonASCII) {
1041       unsigned NumU8CodeUnits = Str.size();
1042       // A UTF-16 representation of a unicode string contains at most the same
1043       // number of code units as a UTF-8 representation.  Allocate that much
1044       // space, plus one for the final null character.
1045       SmallVector<llvm::UTF16, 128> ToBuf(NumU8CodeUnits + 1);
1046       const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)Str.data();
1047       llvm::UTF16 *ToPtr = &ToBuf[0];
1048       (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumU8CodeUnits,
1049           &ToPtr, ToPtr + NumU8CodeUnits, llvm::strictConversion);
1050       uint32_t StringLength = ToPtr - &ToBuf[0];
1051       // Add null terminator
1052       *ToPtr = 0;
1053       // Flags: 2 indicates UTF-16 encoding
1054       Fields.addInt(Int32Ty, 2);
1055       // Number of UTF-16 codepoints
1056       Fields.addInt(Int32Ty, StringLength);
1057       // Number of bytes
1058       Fields.addInt(Int32Ty, StringLength * 2);
1059       // Hash.  Not currently initialised by the compiler.
1060       Fields.addInt(Int32Ty, 0);
1061       // pointer to the data string.
1062       auto Arr = llvm::ArrayRef(&ToBuf[0], ToPtr + 1);
1063       auto *C = llvm::ConstantDataArray::get(VMContext, Arr);
1064       auto *Buffer = new llvm::GlobalVariable(TheModule, C->getType(),
1065           /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, C, ".str");
1066       Buffer->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1067       Fields.add(Buffer);
1068     } else {
1069       // Flags: 0 indicates ASCII encoding
1070       Fields.addInt(Int32Ty, 0);
1071       // Number of UTF-16 codepoints, each ASCII byte is a UTF-16 codepoint
1072       Fields.addInt(Int32Ty, Str.size());
1073       // Number of bytes
1074       Fields.addInt(Int32Ty, Str.size());
1075       // Hash.  Not currently initialised by the compiler.
1076       Fields.addInt(Int32Ty, 0);
1077       // Data pointer
1078       Fields.add(MakeConstantString(Str));
1079     }
1080     std::string StringName;
1081     bool isNamed = !isNonASCII;
1082     if (isNamed) {
1083       StringName = ".objc_str_";
1084       for (int i=0,e=Str.size() ; i<e ; ++i) {
1085         unsigned char c = Str[i];
1086         if (isalnum(c))
1087           StringName += c;
1088         else if (c == ' ')
1089           StringName += '_';
1090         else {
1091           isNamed = false;
1092           break;
1093         }
1094       }
1095     }
1096     llvm::GlobalVariable *ObjCStrGV =
1097       Fields.finishAndCreateGlobal(
1098           isNamed ? StringRef(StringName) : ".objc_string",
1099           Align, false, isNamed ? llvm::GlobalValue::LinkOnceODRLinkage
1100                                 : llvm::GlobalValue::PrivateLinkage);
1101     ObjCStrGV->setSection(sectionName<ConstantStringSection>());
1102     if (isNamed) {
1103       ObjCStrGV->setComdat(TheModule.getOrInsertComdat(StringName));
1104       ObjCStrGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1105     }
1106     if (CGM.getTriple().isOSBinFormatCOFF()) {
1107       std::pair<llvm::GlobalVariable*, int> v{ObjCStrGV, 0};
1108       EarlyInitList.emplace_back(Sym, v);
1109     }
1110     ObjCStrings[Str] = ObjCStrGV;
1111     ConstantStrings.push_back(ObjCStrGV);
1112     return ConstantAddress(ObjCStrGV, IdElemTy, Align);
1113   }
1114 
1115   void PushProperty(ConstantArrayBuilder &PropertiesArray,
1116             const ObjCPropertyDecl *property,
1117             const Decl *OCD,
1118             bool isSynthesized=true, bool
1119             isDynamic=true) override {
1120     // struct objc_property
1121     // {
1122     //   const char *name;
1123     //   const char *attributes;
1124     //   const char *type;
1125     //   SEL getter;
1126     //   SEL setter;
1127     // };
1128     auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
1129     ASTContext &Context = CGM.getContext();
1130     Fields.add(MakeConstantString(property->getNameAsString()));
1131     std::string TypeStr =
1132       CGM.getContext().getObjCEncodingForPropertyDecl(property, OCD);
1133     Fields.add(MakeConstantString(TypeStr));
1134     std::string typeStr;
1135     Context.getObjCEncodingForType(property->getType(), typeStr);
1136     Fields.add(MakeConstantString(typeStr));
1137     auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
1138       if (accessor) {
1139         std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
1140         Fields.add(GetConstantSelector(accessor->getSelector(), TypeStr));
1141       } else {
1142         Fields.add(NULLPtr);
1143       }
1144     };
1145     addPropertyMethod(property->getGetterMethodDecl());
1146     addPropertyMethod(property->getSetterMethodDecl());
1147     Fields.finishAndAddTo(PropertiesArray);
1148   }
1149 
1150   llvm::Constant *
1151   GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) override {
1152     // struct objc_protocol_method_description
1153     // {
1154     //   SEL selector;
1155     //   const char *types;
1156     // };
1157     llvm::StructType *ObjCMethodDescTy =
1158       llvm::StructType::get(CGM.getLLVMContext(),
1159           { PtrToInt8Ty, PtrToInt8Ty });
1160     ASTContext &Context = CGM.getContext();
1161     ConstantInitBuilder Builder(CGM);
1162     // struct objc_protocol_method_description_list
1163     // {
1164     //   int count;
1165     //   int size;
1166     //   struct objc_protocol_method_description methods[];
1167     // };
1168     auto MethodList = Builder.beginStruct();
1169     // int count;
1170     MethodList.addInt(IntTy, Methods.size());
1171     // int size; // sizeof(struct objc_method_description)
1172     llvm::DataLayout td(&TheModule);
1173     MethodList.addInt(IntTy, td.getTypeSizeInBits(ObjCMethodDescTy) /
1174         CGM.getContext().getCharWidth());
1175     // struct objc_method_description[]
1176     auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
1177     for (auto *M : Methods) {
1178       auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
1179       Method.add(CGObjCGNU::GetConstantSelector(M));
1180       Method.add(GetTypeString(Context.getObjCEncodingForMethodDecl(M, true)));
1181       Method.finishAndAddTo(MethodArray);
1182     }
1183     MethodArray.finishAndAddTo(MethodList);
1184     return MethodList.finishAndCreateGlobal(".objc_protocol_method_list",
1185                                             CGM.getPointerAlign());
1186   }
1187   llvm::Constant *GenerateCategoryProtocolList(const ObjCCategoryDecl *OCD)
1188     override {
1189     const auto &ReferencedProtocols = OCD->getReferencedProtocols();
1190     auto RuntimeProtocols = GetRuntimeProtocolList(ReferencedProtocols.begin(),
1191                                                    ReferencedProtocols.end());
1192     SmallVector<llvm::Constant *, 16> Protocols;
1193     for (const auto *PI : RuntimeProtocols)
1194       Protocols.push_back(GenerateProtocolRef(PI));
1195     return GenerateProtocolList(Protocols);
1196   }
1197 
1198   llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
1199                               llvm::Value *cmd, MessageSendInfo &MSI) override {
1200     // Don't access the slot unless we're trying to cache the result.
1201     CGBuilderTy &Builder = CGF.Builder;
1202     llvm::Value *lookupArgs[] = {CGObjCGNU::EnforceType(Builder,
1203                                                         ObjCSuper.getPointer(),
1204                                                         PtrToObjCSuperTy),
1205                                  cmd};
1206     return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
1207   }
1208 
1209   llvm::GlobalVariable *GetClassVar(StringRef Name, bool isWeak=false) {
1210     std::string SymbolName = SymbolForClassRef(Name, isWeak);
1211     auto *ClassSymbol = TheModule.getNamedGlobal(SymbolName);
1212     if (ClassSymbol)
1213       return ClassSymbol;
1214     ClassSymbol = new llvm::GlobalVariable(TheModule,
1215         IdTy, false, llvm::GlobalValue::ExternalLinkage,
1216         nullptr, SymbolName);
1217     // If this is a weak symbol, then we are creating a valid definition for
1218     // the symbol, pointing to a weak definition of the real class pointer.  If
1219     // this is not a weak reference, then we are expecting another compilation
1220     // unit to provide the real indirection symbol.
1221     if (isWeak)
1222       ClassSymbol->setInitializer(new llvm::GlobalVariable(TheModule,
1223           Int8Ty, false, llvm::GlobalValue::ExternalWeakLinkage,
1224           nullptr, SymbolForClass(Name)));
1225     else {
1226       if (CGM.getTriple().isOSBinFormatCOFF()) {
1227         IdentifierInfo &II = CGM.getContext().Idents.get(Name);
1228         TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
1229         DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
1230 
1231         const ObjCInterfaceDecl *OID = nullptr;
1232         for (const auto *Result : DC->lookup(&II))
1233           if ((OID = dyn_cast<ObjCInterfaceDecl>(Result)))
1234             break;
1235 
1236         // The first Interface we find may be a @class,
1237         // which should only be treated as the source of
1238         // truth in the absence of a true declaration.
1239         assert(OID && "Failed to find ObjCInterfaceDecl");
1240         const ObjCInterfaceDecl *OIDDef = OID->getDefinition();
1241         if (OIDDef != nullptr)
1242           OID = OIDDef;
1243 
1244         auto Storage = llvm::GlobalValue::DefaultStorageClass;
1245         if (OID->hasAttr<DLLImportAttr>())
1246           Storage = llvm::GlobalValue::DLLImportStorageClass;
1247         else if (OID->hasAttr<DLLExportAttr>())
1248           Storage = llvm::GlobalValue::DLLExportStorageClass;
1249 
1250         cast<llvm::GlobalValue>(ClassSymbol)->setDLLStorageClass(Storage);
1251       }
1252     }
1253     assert(ClassSymbol->getName() == SymbolName);
1254     return ClassSymbol;
1255   }
1256   llvm::Value *GetClassNamed(CodeGenFunction &CGF,
1257                              const std::string &Name,
1258                              bool isWeak) override {
1259     return CGF.Builder.CreateLoad(
1260         Address(GetClassVar(Name, isWeak), IdTy, CGM.getPointerAlign()));
1261   }
1262   int32_t FlagsForOwnership(Qualifiers::ObjCLifetime Ownership) {
1263     // typedef enum {
1264     //   ownership_invalid = 0,
1265     //   ownership_strong  = 1,
1266     //   ownership_weak    = 2,
1267     //   ownership_unsafe  = 3
1268     // } ivar_ownership;
1269     int Flag;
1270     switch (Ownership) {
1271       case Qualifiers::OCL_Strong:
1272           Flag = 1;
1273           break;
1274       case Qualifiers::OCL_Weak:
1275           Flag = 2;
1276           break;
1277       case Qualifiers::OCL_ExplicitNone:
1278           Flag = 3;
1279           break;
1280       case Qualifiers::OCL_None:
1281       case Qualifiers::OCL_Autoreleasing:
1282         assert(Ownership != Qualifiers::OCL_Autoreleasing);
1283         Flag = 0;
1284     }
1285     return Flag;
1286   }
1287   llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1288                    ArrayRef<llvm::Constant *> IvarTypes,
1289                    ArrayRef<llvm::Constant *> IvarOffsets,
1290                    ArrayRef<llvm::Constant *> IvarAlign,
1291                    ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) override {
1292     llvm_unreachable("Method should not be called!");
1293   }
1294 
1295   llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName) override {
1296     std::string Name = SymbolForProtocol(ProtocolName);
1297     auto *GV = TheModule.getGlobalVariable(Name);
1298     if (!GV) {
1299       // Emit a placeholder symbol.
1300       GV = new llvm::GlobalVariable(TheModule, ProtocolTy, false,
1301           llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1302       GV->setAlignment(CGM.getPointerAlign().getAsAlign());
1303     }
1304     return GV;
1305   }
1306 
1307   /// Existing protocol references.
1308   llvm::StringMap<llvm::Constant*> ExistingProtocolRefs;
1309 
1310   llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1311                                    const ObjCProtocolDecl *PD) override {
1312     auto Name = PD->getNameAsString();
1313     auto *&Ref = ExistingProtocolRefs[Name];
1314     if (!Ref) {
1315       auto *&Protocol = ExistingProtocols[Name];
1316       if (!Protocol)
1317         Protocol = GenerateProtocolRef(PD);
1318       std::string RefName = SymbolForProtocolRef(Name);
1319       assert(!TheModule.getGlobalVariable(RefName));
1320       // Emit a reference symbol.
1321       auto GV = new llvm::GlobalVariable(TheModule, ProtocolPtrTy, false,
1322                                          llvm::GlobalValue::LinkOnceODRLinkage,
1323                                          Protocol, RefName);
1324       GV->setComdat(TheModule.getOrInsertComdat(RefName));
1325       GV->setSection(sectionName<ProtocolReferenceSection>());
1326       GV->setAlignment(CGM.getPointerAlign().getAsAlign());
1327       Ref = GV;
1328     }
1329     EmittedProtocolRef = true;
1330     return CGF.Builder.CreateAlignedLoad(ProtocolPtrTy, Ref,
1331                                          CGM.getPointerAlign());
1332   }
1333 
1334   llvm::Constant *GenerateProtocolList(ArrayRef<llvm::Constant*> Protocols) {
1335     llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(ProtocolPtrTy,
1336         Protocols.size());
1337     llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1338         Protocols);
1339     ConstantInitBuilder builder(CGM);
1340     auto ProtocolBuilder = builder.beginStruct();
1341     ProtocolBuilder.addNullPointer(PtrTy);
1342     ProtocolBuilder.addInt(SizeTy, Protocols.size());
1343     ProtocolBuilder.add(ProtocolArray);
1344     return ProtocolBuilder.finishAndCreateGlobal(".objc_protocol_list",
1345         CGM.getPointerAlign(), false, llvm::GlobalValue::InternalLinkage);
1346   }
1347 
1348   void GenerateProtocol(const ObjCProtocolDecl *PD) override {
1349     // Do nothing - we only emit referenced protocols.
1350   }
1351   llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD) override {
1352     std::string ProtocolName = PD->getNameAsString();
1353     auto *&Protocol = ExistingProtocols[ProtocolName];
1354     if (Protocol)
1355       return Protocol;
1356 
1357     EmittedProtocol = true;
1358 
1359     auto SymName = SymbolForProtocol(ProtocolName);
1360     auto *OldGV = TheModule.getGlobalVariable(SymName);
1361 
1362     // Use the protocol definition, if there is one.
1363     if (const ObjCProtocolDecl *Def = PD->getDefinition())
1364       PD = Def;
1365     else {
1366       // If there is no definition, then create an external linkage symbol and
1367       // hope that someone else fills it in for us (and fail to link if they
1368       // don't).
1369       assert(!OldGV);
1370       Protocol = new llvm::GlobalVariable(TheModule, ProtocolTy,
1371         /*isConstant*/false,
1372         llvm::GlobalValue::ExternalLinkage, nullptr, SymName);
1373       return Protocol;
1374     }
1375 
1376     SmallVector<llvm::Constant*, 16> Protocols;
1377     auto RuntimeProtocols =
1378         GetRuntimeProtocolList(PD->protocol_begin(), PD->protocol_end());
1379     for (const auto *PI : RuntimeProtocols)
1380       Protocols.push_back(GenerateProtocolRef(PI));
1381     llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1382 
1383     // Collect information about methods
1384     llvm::Constant *InstanceMethodList, *OptionalInstanceMethodList;
1385     llvm::Constant *ClassMethodList, *OptionalClassMethodList;
1386     EmitProtocolMethodList(PD->instance_methods(), InstanceMethodList,
1387         OptionalInstanceMethodList);
1388     EmitProtocolMethodList(PD->class_methods(), ClassMethodList,
1389         OptionalClassMethodList);
1390 
1391     // The isa pointer must be set to a magic number so the runtime knows it's
1392     // the correct layout.
1393     ConstantInitBuilder builder(CGM);
1394     auto ProtocolBuilder = builder.beginStruct();
1395     ProtocolBuilder.add(llvm::ConstantExpr::getIntToPtr(
1396           llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1397     ProtocolBuilder.add(MakeConstantString(ProtocolName));
1398     ProtocolBuilder.add(ProtocolList);
1399     ProtocolBuilder.add(InstanceMethodList);
1400     ProtocolBuilder.add(ClassMethodList);
1401     ProtocolBuilder.add(OptionalInstanceMethodList);
1402     ProtocolBuilder.add(OptionalClassMethodList);
1403     // Required instance properties
1404     ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, false));
1405     // Optional instance properties
1406     ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, true));
1407     // Required class properties
1408     ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, false));
1409     // Optional class properties
1410     ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, true));
1411 
1412     auto *GV = ProtocolBuilder.finishAndCreateGlobal(SymName,
1413         CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
1414     GV->setSection(sectionName<ProtocolSection>());
1415     GV->setComdat(TheModule.getOrInsertComdat(SymName));
1416     if (OldGV) {
1417       OldGV->replaceAllUsesWith(GV);
1418       OldGV->removeFromParent();
1419       GV->setName(SymName);
1420     }
1421     Protocol = GV;
1422     return GV;
1423   }
1424   llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
1425                                 const std::string &TypeEncoding) override {
1426     return GetConstantSelector(Sel, TypeEncoding);
1427   }
1428   llvm::Constant  *GetTypeString(llvm::StringRef TypeEncoding) {
1429     if (TypeEncoding.empty())
1430       return NULLPtr;
1431     std::string MangledTypes = std::string(TypeEncoding);
1432     std::replace(MangledTypes.begin(), MangledTypes.end(),
1433       '@', '\1');
1434     std::string TypesVarName = ".objc_sel_types_" + MangledTypes;
1435     auto *TypesGlobal = TheModule.getGlobalVariable(TypesVarName);
1436     if (!TypesGlobal) {
1437       llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
1438           TypeEncoding);
1439       auto *GV = new llvm::GlobalVariable(TheModule, Init->getType(),
1440           true, llvm::GlobalValue::LinkOnceODRLinkage, Init, TypesVarName);
1441       GV->setComdat(TheModule.getOrInsertComdat(TypesVarName));
1442       GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1443       TypesGlobal = GV;
1444     }
1445     return llvm::ConstantExpr::getGetElementPtr(TypesGlobal->getValueType(),
1446         TypesGlobal, Zeros);
1447   }
1448   llvm::Constant *GetConstantSelector(Selector Sel,
1449                                       const std::string &TypeEncoding) override {
1450     // @ is used as a special character in symbol names (used for symbol
1451     // versioning), so mangle the name to not include it.  Replace it with a
1452     // character that is not a valid type encoding character (and, being
1453     // non-printable, never will be!)
1454     std::string MangledTypes = TypeEncoding;
1455     std::replace(MangledTypes.begin(), MangledTypes.end(),
1456       '@', '\1');
1457     auto SelVarName = (StringRef(".objc_selector_") + Sel.getAsString() + "_" +
1458       MangledTypes).str();
1459     if (auto *GV = TheModule.getNamedGlobal(SelVarName))
1460       return GV;
1461     ConstantInitBuilder builder(CGM);
1462     auto SelBuilder = builder.beginStruct();
1463     SelBuilder.add(ExportUniqueString(Sel.getAsString(), ".objc_sel_name_",
1464           true));
1465     SelBuilder.add(GetTypeString(TypeEncoding));
1466     auto *GV = SelBuilder.finishAndCreateGlobal(SelVarName,
1467         CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1468     GV->setComdat(TheModule.getOrInsertComdat(SelVarName));
1469     GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1470     GV->setSection(sectionName<SelectorSection>());
1471     return GV;
1472   }
1473   llvm::StructType *emptyStruct = nullptr;
1474 
1475   /// Return pointers to the start and end of a section.  On ELF platforms, we
1476   /// use the __start_ and __stop_ symbols that GNU-compatible linkers will set
1477   /// to the start and end of section names, as long as those section names are
1478   /// valid identifiers and the symbols are referenced but not defined.  On
1479   /// Windows, we use the fact that MSVC-compatible linkers will lexically sort
1480   /// by subsections and place everything that we want to reference in a middle
1481   /// subsection and then insert zero-sized symbols in subsections a and z.
1482   std::pair<llvm::Constant*,llvm::Constant*>
1483   GetSectionBounds(StringRef Section) {
1484     if (CGM.getTriple().isOSBinFormatCOFF()) {
1485       if (emptyStruct == nullptr) {
1486         emptyStruct = llvm::StructType::create(VMContext, ".objc_section_sentinel");
1487         emptyStruct->setBody({}, /*isPacked*/true);
1488       }
1489       auto ZeroInit = llvm::Constant::getNullValue(emptyStruct);
1490       auto Sym = [&](StringRef Prefix, StringRef SecSuffix) {
1491         auto *Sym = new llvm::GlobalVariable(TheModule, emptyStruct,
1492             /*isConstant*/false,
1493             llvm::GlobalValue::LinkOnceODRLinkage, ZeroInit, Prefix +
1494             Section);
1495         Sym->setVisibility(llvm::GlobalValue::HiddenVisibility);
1496         Sym->setSection((Section + SecSuffix).str());
1497         Sym->setComdat(TheModule.getOrInsertComdat((Prefix +
1498             Section).str()));
1499         Sym->setAlignment(CGM.getPointerAlign().getAsAlign());
1500         return Sym;
1501       };
1502       return { Sym("__start_", "$a"), Sym("__stop", "$z") };
1503     }
1504     auto *Start = new llvm::GlobalVariable(TheModule, PtrTy,
1505         /*isConstant*/false,
1506         llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__start_") +
1507         Section);
1508     Start->setVisibility(llvm::GlobalValue::HiddenVisibility);
1509     auto *Stop = new llvm::GlobalVariable(TheModule, PtrTy,
1510         /*isConstant*/false,
1511         llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__stop_") +
1512         Section);
1513     Stop->setVisibility(llvm::GlobalValue::HiddenVisibility);
1514     return { Start, Stop };
1515   }
1516   CatchTypeInfo getCatchAllTypeInfo() override {
1517     return CGM.getCXXABI().getCatchAllTypeInfo();
1518   }
1519   llvm::Function *ModuleInitFunction() override {
1520     llvm::Function *LoadFunction = llvm::Function::Create(
1521       llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
1522       llvm::GlobalValue::LinkOnceODRLinkage, ".objcv2_load_function",
1523       &TheModule);
1524     LoadFunction->setVisibility(llvm::GlobalValue::HiddenVisibility);
1525     LoadFunction->setComdat(TheModule.getOrInsertComdat(".objcv2_load_function"));
1526 
1527     llvm::BasicBlock *EntryBB =
1528         llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
1529     CGBuilderTy B(CGM, VMContext);
1530     B.SetInsertPoint(EntryBB);
1531     ConstantInitBuilder builder(CGM);
1532     auto InitStructBuilder = builder.beginStruct();
1533     InitStructBuilder.addInt(Int64Ty, 0);
1534     auto &sectionVec = CGM.getTriple().isOSBinFormatCOFF() ? PECOFFSectionsBaseNames : SectionsBaseNames;
1535     for (auto *s : sectionVec) {
1536       auto bounds = GetSectionBounds(s);
1537       InitStructBuilder.add(bounds.first);
1538       InitStructBuilder.add(bounds.second);
1539     }
1540     auto *InitStruct = InitStructBuilder.finishAndCreateGlobal(".objc_init",
1541         CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1542     InitStruct->setVisibility(llvm::GlobalValue::HiddenVisibility);
1543     InitStruct->setComdat(TheModule.getOrInsertComdat(".objc_init"));
1544 
1545     CallRuntimeFunction(B, "__objc_load", {InitStruct});;
1546     B.CreateRetVoid();
1547     // Make sure that the optimisers don't delete this function.
1548     CGM.addCompilerUsedGlobal(LoadFunction);
1549     // FIXME: Currently ELF only!
1550     // We have to do this by hand, rather than with @llvm.ctors, so that the
1551     // linker can remove the duplicate invocations.
1552     auto *InitVar = new llvm::GlobalVariable(TheModule, LoadFunction->getType(),
1553         /*isConstant*/false, llvm::GlobalValue::LinkOnceAnyLinkage,
1554         LoadFunction, ".objc_ctor");
1555     // Check that this hasn't been renamed.  This shouldn't happen, because
1556     // this function should be called precisely once.
1557     assert(InitVar->getName() == ".objc_ctor");
1558     // In Windows, initialisers are sorted by the suffix.  XCL is for library
1559     // initialisers, which run before user initialisers.  We are running
1560     // Objective-C loads at the end of library load.  This means +load methods
1561     // will run before any other static constructors, but that static
1562     // constructors can see a fully initialised Objective-C state.
1563     if (CGM.getTriple().isOSBinFormatCOFF())
1564         InitVar->setSection(".CRT$XCLz");
1565     else
1566     {
1567       if (CGM.getCodeGenOpts().UseInitArray)
1568         InitVar->setSection(".init_array");
1569       else
1570         InitVar->setSection(".ctors");
1571     }
1572     InitVar->setVisibility(llvm::GlobalValue::HiddenVisibility);
1573     InitVar->setComdat(TheModule.getOrInsertComdat(".objc_ctor"));
1574     CGM.addUsedGlobal(InitVar);
1575     for (auto *C : Categories) {
1576       auto *Cat = cast<llvm::GlobalVariable>(C->stripPointerCasts());
1577       Cat->setSection(sectionName<CategorySection>());
1578       CGM.addUsedGlobal(Cat);
1579     }
1580     auto createNullGlobal = [&](StringRef Name, ArrayRef<llvm::Constant*> Init,
1581         StringRef Section) {
1582       auto nullBuilder = builder.beginStruct();
1583       for (auto *F : Init)
1584         nullBuilder.add(F);
1585       auto GV = nullBuilder.finishAndCreateGlobal(Name, CGM.getPointerAlign(),
1586           false, llvm::GlobalValue::LinkOnceODRLinkage);
1587       GV->setSection(Section);
1588       GV->setComdat(TheModule.getOrInsertComdat(Name));
1589       GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1590       CGM.addUsedGlobal(GV);
1591       return GV;
1592     };
1593     for (auto clsAlias : ClassAliases)
1594       createNullGlobal(std::string(".objc_class_alias") +
1595           clsAlias.second, { MakeConstantString(clsAlias.second),
1596           GetClassVar(clsAlias.first) }, sectionName<ClassAliasSection>());
1597     // On ELF platforms, add a null value for each special section so that we
1598     // can always guarantee that the _start and _stop symbols will exist and be
1599     // meaningful.  This is not required on COFF platforms, where our start and
1600     // stop symbols will create the section.
1601     if (!CGM.getTriple().isOSBinFormatCOFF()) {
1602       createNullGlobal(".objc_null_selector", {NULLPtr, NULLPtr},
1603           sectionName<SelectorSection>());
1604       if (Categories.empty())
1605         createNullGlobal(".objc_null_category", {NULLPtr, NULLPtr,
1606                       NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr},
1607             sectionName<CategorySection>());
1608       if (!EmittedClass) {
1609         createNullGlobal(".objc_null_cls_init_ref", NULLPtr,
1610             sectionName<ClassSection>());
1611         createNullGlobal(".objc_null_class_ref", { NULLPtr, NULLPtr },
1612             sectionName<ClassReferenceSection>());
1613       }
1614       if (!EmittedProtocol)
1615         createNullGlobal(".objc_null_protocol", {NULLPtr, NULLPtr, NULLPtr,
1616             NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr,
1617             NULLPtr}, sectionName<ProtocolSection>());
1618       if (!EmittedProtocolRef)
1619         createNullGlobal(".objc_null_protocol_ref", {NULLPtr},
1620             sectionName<ProtocolReferenceSection>());
1621       if (ClassAliases.empty())
1622         createNullGlobal(".objc_null_class_alias", { NULLPtr, NULLPtr },
1623             sectionName<ClassAliasSection>());
1624       if (ConstantStrings.empty()) {
1625         auto i32Zero = llvm::ConstantInt::get(Int32Ty, 0);
1626         createNullGlobal(".objc_null_constant_string", { NULLPtr, i32Zero,
1627             i32Zero, i32Zero, i32Zero, NULLPtr },
1628             sectionName<ConstantStringSection>());
1629       }
1630     }
1631     ConstantStrings.clear();
1632     Categories.clear();
1633     Classes.clear();
1634 
1635     if (EarlyInitList.size() > 0) {
1636       auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
1637             {}), llvm::GlobalValue::InternalLinkage, ".objc_early_init",
1638           &CGM.getModule());
1639       llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
1640             Init));
1641       for (const auto &lateInit : EarlyInitList) {
1642         auto *global = TheModule.getGlobalVariable(lateInit.first);
1643         if (global) {
1644           llvm::GlobalVariable *GV = lateInit.second.first;
1645           b.CreateAlignedStore(
1646               global,
1647               b.CreateStructGEP(GV->getValueType(), GV, lateInit.second.second),
1648               CGM.getPointerAlign().getAsAlign());
1649         }
1650       }
1651       b.CreateRetVoid();
1652       // We can't use the normal LLVM global initialisation array, because we
1653       // need to specify that this runs early in library initialisation.
1654       auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
1655           /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
1656           Init, ".objc_early_init_ptr");
1657       InitVar->setSection(".CRT$XCLb");
1658       CGM.addUsedGlobal(InitVar);
1659     }
1660     return nullptr;
1661   }
1662   /// In the v2 ABI, ivar offset variables use the type encoding in their name
1663   /// to trigger linker failures if the types don't match.
1664   std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
1665                                         const ObjCIvarDecl *Ivar) override {
1666     std::string TypeEncoding;
1667     CGM.getContext().getObjCEncodingForType(Ivar->getType(), TypeEncoding);
1668     // Prevent the @ from being interpreted as a symbol version.
1669     std::replace(TypeEncoding.begin(), TypeEncoding.end(),
1670       '@', '\1');
1671     const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
1672       + '.' + Ivar->getNameAsString() + '.' + TypeEncoding;
1673     return Name;
1674   }
1675   llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
1676                               const ObjCInterfaceDecl *Interface,
1677                               const ObjCIvarDecl *Ivar) override {
1678     const std::string Name = GetIVarOffsetVariableName(Ivar->getContainingInterface(), Ivar);
1679     llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
1680     if (!IvarOffsetPointer)
1681       IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false,
1682               llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1683     CharUnits Align = CGM.getIntAlign();
1684     llvm::Value *Offset =
1685         CGF.Builder.CreateAlignedLoad(IntTy, IvarOffsetPointer, Align);
1686     if (Offset->getType() != PtrDiffTy)
1687       Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
1688     return Offset;
1689   }
1690   void GenerateClass(const ObjCImplementationDecl *OID) override {
1691     ASTContext &Context = CGM.getContext();
1692     bool IsCOFF = CGM.getTriple().isOSBinFormatCOFF();
1693 
1694     // Get the class name
1695     ObjCInterfaceDecl *classDecl =
1696         const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
1697     std::string className = classDecl->getNameAsString();
1698     auto *classNameConstant = MakeConstantString(className);
1699 
1700     ConstantInitBuilder builder(CGM);
1701     auto metaclassFields = builder.beginStruct();
1702     // struct objc_class *isa;
1703     metaclassFields.addNullPointer(PtrTy);
1704     // struct objc_class *super_class;
1705     metaclassFields.addNullPointer(PtrTy);
1706     // const char *name;
1707     metaclassFields.add(classNameConstant);
1708     // long version;
1709     metaclassFields.addInt(LongTy, 0);
1710     // unsigned long info;
1711     // objc_class_flag_meta
1712     metaclassFields.addInt(LongTy, 1);
1713     // long instance_size;
1714     // Setting this to zero is consistent with the older ABI, but it might be
1715     // more sensible to set this to sizeof(struct objc_class)
1716     metaclassFields.addInt(LongTy, 0);
1717     // struct objc_ivar_list *ivars;
1718     metaclassFields.addNullPointer(PtrTy);
1719     // struct objc_method_list *methods
1720     // FIXME: Almost identical code is copied and pasted below for the
1721     // class, but refactoring it cleanly requires C++14 generic lambdas.
1722     if (OID->classmeth_begin() == OID->classmeth_end())
1723       metaclassFields.addNullPointer(PtrTy);
1724     else {
1725       SmallVector<ObjCMethodDecl*, 16> ClassMethods;
1726       ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
1727           OID->classmeth_end());
1728       metaclassFields.add(
1729           GenerateMethodList(className, "", ClassMethods, true));
1730     }
1731     // void *dtable;
1732     metaclassFields.addNullPointer(PtrTy);
1733     // IMP cxx_construct;
1734     metaclassFields.addNullPointer(PtrTy);
1735     // IMP cxx_destruct;
1736     metaclassFields.addNullPointer(PtrTy);
1737     // struct objc_class *subclass_list
1738     metaclassFields.addNullPointer(PtrTy);
1739     // struct objc_class *sibling_class
1740     metaclassFields.addNullPointer(PtrTy);
1741     // struct objc_protocol_list *protocols;
1742     metaclassFields.addNullPointer(PtrTy);
1743     // struct reference_list *extra_data;
1744     metaclassFields.addNullPointer(PtrTy);
1745     // long abi_version;
1746     metaclassFields.addInt(LongTy, 0);
1747     // struct objc_property_list *properties
1748     metaclassFields.add(GeneratePropertyList(OID, classDecl, /*isClassProperty*/true));
1749 
1750     auto *metaclass = metaclassFields.finishAndCreateGlobal(
1751         ManglePublicSymbol("OBJC_METACLASS_") + className,
1752         CGM.getPointerAlign());
1753 
1754     auto classFields = builder.beginStruct();
1755     // struct objc_class *isa;
1756     classFields.add(metaclass);
1757     // struct objc_class *super_class;
1758     // Get the superclass name.
1759     const ObjCInterfaceDecl * SuperClassDecl =
1760       OID->getClassInterface()->getSuperClass();
1761     llvm::Constant *SuperClass = nullptr;
1762     if (SuperClassDecl) {
1763       auto SuperClassName = SymbolForClass(SuperClassDecl->getNameAsString());
1764       SuperClass = TheModule.getNamedGlobal(SuperClassName);
1765       if (!SuperClass)
1766       {
1767         SuperClass = new llvm::GlobalVariable(TheModule, PtrTy, false,
1768             llvm::GlobalValue::ExternalLinkage, nullptr, SuperClassName);
1769         if (IsCOFF) {
1770           auto Storage = llvm::GlobalValue::DefaultStorageClass;
1771           if (SuperClassDecl->hasAttr<DLLImportAttr>())
1772             Storage = llvm::GlobalValue::DLLImportStorageClass;
1773           else if (SuperClassDecl->hasAttr<DLLExportAttr>())
1774             Storage = llvm::GlobalValue::DLLExportStorageClass;
1775 
1776           cast<llvm::GlobalValue>(SuperClass)->setDLLStorageClass(Storage);
1777         }
1778       }
1779       if (!IsCOFF)
1780         classFields.add(SuperClass);
1781       else
1782         classFields.addNullPointer(PtrTy);
1783     } else
1784       classFields.addNullPointer(PtrTy);
1785     // const char *name;
1786     classFields.add(classNameConstant);
1787     // long version;
1788     classFields.addInt(LongTy, 0);
1789     // unsigned long info;
1790     // !objc_class_flag_meta
1791     classFields.addInt(LongTy, 0);
1792     // long instance_size;
1793     int superInstanceSize = !SuperClassDecl ? 0 :
1794       Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
1795     // Instance size is negative for classes that have not yet had their ivar
1796     // layout calculated.
1797     classFields.addInt(LongTy,
1798       0 - (Context.getASTObjCImplementationLayout(OID).getSize().getQuantity() -
1799       superInstanceSize));
1800 
1801     if (classDecl->all_declared_ivar_begin() == nullptr)
1802       classFields.addNullPointer(PtrTy);
1803     else {
1804       int ivar_count = 0;
1805       for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1806            IVD = IVD->getNextIvar()) ivar_count++;
1807       llvm::DataLayout td(&TheModule);
1808       // struct objc_ivar_list *ivars;
1809       ConstantInitBuilder b(CGM);
1810       auto ivarListBuilder = b.beginStruct();
1811       // int count;
1812       ivarListBuilder.addInt(IntTy, ivar_count);
1813       // size_t size;
1814       llvm::StructType *ObjCIvarTy = llvm::StructType::get(
1815         PtrToInt8Ty,
1816         PtrToInt8Ty,
1817         PtrToInt8Ty,
1818         Int32Ty,
1819         Int32Ty);
1820       ivarListBuilder.addInt(SizeTy, td.getTypeSizeInBits(ObjCIvarTy) /
1821           CGM.getContext().getCharWidth());
1822       // struct objc_ivar ivars[]
1823       auto ivarArrayBuilder = ivarListBuilder.beginArray();
1824       for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1825            IVD = IVD->getNextIvar()) {
1826         auto ivarTy = IVD->getType();
1827         auto ivarBuilder = ivarArrayBuilder.beginStruct();
1828         // const char *name;
1829         ivarBuilder.add(MakeConstantString(IVD->getNameAsString()));
1830         // const char *type;
1831         std::string TypeStr;
1832         //Context.getObjCEncodingForType(ivarTy, TypeStr, IVD, true);
1833         Context.getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, ivarTy, TypeStr, true);
1834         ivarBuilder.add(MakeConstantString(TypeStr));
1835         // int *offset;
1836         uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
1837         uint64_t Offset = BaseOffset - superInstanceSize;
1838         llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
1839         std::string OffsetName = GetIVarOffsetVariableName(classDecl, IVD);
1840         llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
1841         if (OffsetVar)
1842           OffsetVar->setInitializer(OffsetValue);
1843         else
1844           OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
1845             false, llvm::GlobalValue::ExternalLinkage,
1846             OffsetValue, OffsetName);
1847         auto ivarVisibility =
1848             (IVD->getAccessControl() == ObjCIvarDecl::Private ||
1849              IVD->getAccessControl() == ObjCIvarDecl::Package ||
1850              classDecl->getVisibility() == HiddenVisibility) ?
1851                     llvm::GlobalValue::HiddenVisibility :
1852                     llvm::GlobalValue::DefaultVisibility;
1853         OffsetVar->setVisibility(ivarVisibility);
1854         if (ivarVisibility != llvm::GlobalValue::HiddenVisibility)
1855           CGM.setGVProperties(OffsetVar, OID->getClassInterface());
1856         ivarBuilder.add(OffsetVar);
1857         // Ivar size
1858         ivarBuilder.addInt(Int32Ty,
1859             CGM.getContext().getTypeSizeInChars(ivarTy).getQuantity());
1860         // Alignment will be stored as a base-2 log of the alignment.
1861         unsigned align =
1862             llvm::Log2_32(Context.getTypeAlignInChars(ivarTy).getQuantity());
1863         // Objects that require more than 2^64-byte alignment should be impossible!
1864         assert(align < 64);
1865         // uint32_t flags;
1866         // Bits 0-1 are ownership.
1867         // Bit 2 indicates an extended type encoding
1868         // Bits 3-8 contain log2(aligment)
1869         ivarBuilder.addInt(Int32Ty,
1870             (align << 3) | (1<<2) |
1871             FlagsForOwnership(ivarTy.getQualifiers().getObjCLifetime()));
1872         ivarBuilder.finishAndAddTo(ivarArrayBuilder);
1873       }
1874       ivarArrayBuilder.finishAndAddTo(ivarListBuilder);
1875       auto ivarList = ivarListBuilder.finishAndCreateGlobal(".objc_ivar_list",
1876           CGM.getPointerAlign(), /*constant*/ false,
1877           llvm::GlobalValue::PrivateLinkage);
1878       classFields.add(ivarList);
1879     }
1880     // struct objc_method_list *methods
1881     SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
1882     InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
1883         OID->instmeth_end());
1884     for (auto *propImpl : OID->property_impls())
1885       if (propImpl->getPropertyImplementation() ==
1886           ObjCPropertyImplDecl::Synthesize) {
1887         auto addIfExists = [&](const ObjCMethodDecl *OMD) {
1888           if (OMD && OMD->hasBody())
1889             InstanceMethods.push_back(OMD);
1890         };
1891         addIfExists(propImpl->getGetterMethodDecl());
1892         addIfExists(propImpl->getSetterMethodDecl());
1893       }
1894 
1895     if (InstanceMethods.size() == 0)
1896       classFields.addNullPointer(PtrTy);
1897     else
1898       classFields.add(
1899           GenerateMethodList(className, "", InstanceMethods, false));
1900 
1901     // void *dtable;
1902     classFields.addNullPointer(PtrTy);
1903     // IMP cxx_construct;
1904     classFields.addNullPointer(PtrTy);
1905     // IMP cxx_destruct;
1906     classFields.addNullPointer(PtrTy);
1907     // struct objc_class *subclass_list
1908     classFields.addNullPointer(PtrTy);
1909     // struct objc_class *sibling_class
1910     classFields.addNullPointer(PtrTy);
1911     // struct objc_protocol_list *protocols;
1912     auto RuntimeProtocols = GetRuntimeProtocolList(classDecl->protocol_begin(),
1913                                                    classDecl->protocol_end());
1914     SmallVector<llvm::Constant *, 16> Protocols;
1915     for (const auto *I : RuntimeProtocols)
1916       Protocols.push_back(GenerateProtocolRef(I));
1917 
1918     if (Protocols.empty())
1919       classFields.addNullPointer(PtrTy);
1920     else
1921       classFields.add(GenerateProtocolList(Protocols));
1922     // struct reference_list *extra_data;
1923     classFields.addNullPointer(PtrTy);
1924     // long abi_version;
1925     classFields.addInt(LongTy, 0);
1926     // struct objc_property_list *properties
1927     classFields.add(GeneratePropertyList(OID, classDecl));
1928 
1929     llvm::GlobalVariable *classStruct =
1930       classFields.finishAndCreateGlobal(SymbolForClass(className),
1931         CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
1932 
1933     auto *classRefSymbol = GetClassVar(className);
1934     classRefSymbol->setSection(sectionName<ClassReferenceSection>());
1935     classRefSymbol->setInitializer(classStruct);
1936 
1937     if (IsCOFF) {
1938       // we can't import a class struct.
1939       if (OID->getClassInterface()->hasAttr<DLLExportAttr>()) {
1940         classStruct->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1941         cast<llvm::GlobalValue>(classRefSymbol)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1942       }
1943 
1944       if (SuperClass) {
1945         std::pair<llvm::GlobalVariable*, int> v{classStruct, 1};
1946         EarlyInitList.emplace_back(std::string(SuperClass->getName()),
1947                                    std::move(v));
1948       }
1949 
1950     }
1951 
1952 
1953     // Resolve the class aliases, if they exist.
1954     // FIXME: Class pointer aliases shouldn't exist!
1955     if (ClassPtrAlias) {
1956       ClassPtrAlias->replaceAllUsesWith(classStruct);
1957       ClassPtrAlias->eraseFromParent();
1958       ClassPtrAlias = nullptr;
1959     }
1960     if (auto Placeholder =
1961         TheModule.getNamedGlobal(SymbolForClass(className)))
1962       if (Placeholder != classStruct) {
1963         Placeholder->replaceAllUsesWith(classStruct);
1964         Placeholder->eraseFromParent();
1965         classStruct->setName(SymbolForClass(className));
1966       }
1967     if (MetaClassPtrAlias) {
1968       MetaClassPtrAlias->replaceAllUsesWith(metaclass);
1969       MetaClassPtrAlias->eraseFromParent();
1970       MetaClassPtrAlias = nullptr;
1971     }
1972     assert(classStruct->getName() == SymbolForClass(className));
1973 
1974     auto classInitRef = new llvm::GlobalVariable(TheModule,
1975         classStruct->getType(), false, llvm::GlobalValue::ExternalLinkage,
1976         classStruct, ManglePublicSymbol("OBJC_INIT_CLASS_") + className);
1977     classInitRef->setSection(sectionName<ClassSection>());
1978     CGM.addUsedGlobal(classInitRef);
1979 
1980     EmittedClass = true;
1981   }
1982   public:
1983     CGObjCGNUstep2(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 10, 4, 2) {
1984       MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
1985                             PtrToObjCSuperTy, SelectorTy);
1986       // struct objc_property
1987       // {
1988       //   const char *name;
1989       //   const char *attributes;
1990       //   const char *type;
1991       //   SEL getter;
1992       //   SEL setter;
1993       // }
1994       PropertyMetadataTy =
1995         llvm::StructType::get(CGM.getLLVMContext(),
1996             { PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
1997     }
1998 
1999 };
2000 
2001 const char *const CGObjCGNUstep2::SectionsBaseNames[8] =
2002 {
2003 "__objc_selectors",
2004 "__objc_classes",
2005 "__objc_class_refs",
2006 "__objc_cats",
2007 "__objc_protocols",
2008 "__objc_protocol_refs",
2009 "__objc_class_aliases",
2010 "__objc_constant_string"
2011 };
2012 
2013 const char *const CGObjCGNUstep2::PECOFFSectionsBaseNames[8] =
2014 {
2015 ".objcrt$SEL",
2016 ".objcrt$CLS",
2017 ".objcrt$CLR",
2018 ".objcrt$CAT",
2019 ".objcrt$PCL",
2020 ".objcrt$PCR",
2021 ".objcrt$CAL",
2022 ".objcrt$STR"
2023 };
2024 
2025 /// Support for the ObjFW runtime.
2026 class CGObjCObjFW: public CGObjCGNU {
2027 protected:
2028   /// The GCC ABI message lookup function.  Returns an IMP pointing to the
2029   /// method implementation for this message.
2030   LazyRuntimeFunction MsgLookupFn;
2031   /// stret lookup function.  While this does not seem to make sense at the
2032   /// first look, this is required to call the correct forwarding function.
2033   LazyRuntimeFunction MsgLookupFnSRet;
2034   /// The GCC ABI superclass message lookup function.  Takes a pointer to a
2035   /// structure describing the receiver and the class, and a selector as
2036   /// arguments.  Returns the IMP for the corresponding method.
2037   LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
2038 
2039   llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
2040                          llvm::Value *cmd, llvm::MDNode *node,
2041                          MessageSendInfo &MSI) override {
2042     CGBuilderTy &Builder = CGF.Builder;
2043     llvm::Value *args[] = {
2044             EnforceType(Builder, Receiver, IdTy),
2045             EnforceType(Builder, cmd, SelectorTy) };
2046 
2047     llvm::CallBase *imp;
2048     if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
2049       imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
2050     else
2051       imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
2052 
2053     imp->setMetadata(msgSendMDKind, node);
2054     return imp;
2055   }
2056 
2057   llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
2058                               llvm::Value *cmd, MessageSendInfo &MSI) override {
2059     CGBuilderTy &Builder = CGF.Builder;
2060     llvm::Value *lookupArgs[] = {
2061         EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
2062     };
2063 
2064     if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
2065       return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
2066     else
2067       return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
2068   }
2069 
2070   llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
2071                              bool isWeak) override {
2072     if (isWeak)
2073       return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
2074 
2075     EmitClassRef(Name);
2076     std::string SymbolName = "_OBJC_CLASS_" + Name;
2077     llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
2078     if (!ClassSymbol)
2079       ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
2080                                              llvm::GlobalValue::ExternalLinkage,
2081                                              nullptr, SymbolName);
2082     return ClassSymbol;
2083   }
2084 
2085 public:
2086   CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
2087     // IMP objc_msg_lookup(id, SEL);
2088     MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
2089     MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
2090                          SelectorTy);
2091     // IMP objc_msg_lookup_super(struct objc_super*, SEL);
2092     MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
2093                           PtrToObjCSuperTy, SelectorTy);
2094     MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
2095                               PtrToObjCSuperTy, SelectorTy);
2096   }
2097 };
2098 } // end anonymous namespace
2099 
2100 /// Emits a reference to a dummy variable which is emitted with each class.
2101 /// This ensures that a linker error will be generated when trying to link
2102 /// together modules where a referenced class is not defined.
2103 void CGObjCGNU::EmitClassRef(const std::string &className) {
2104   std::string symbolRef = "__objc_class_ref_" + className;
2105   // Don't emit two copies of the same symbol
2106   if (TheModule.getGlobalVariable(symbolRef))
2107     return;
2108   std::string symbolName = "__objc_class_name_" + className;
2109   llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
2110   if (!ClassSymbol) {
2111     ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
2112                                            llvm::GlobalValue::ExternalLinkage,
2113                                            nullptr, symbolName);
2114   }
2115   new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
2116     llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
2117 }
2118 
2119 CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
2120                      unsigned protocolClassVersion, unsigned classABI)
2121   : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
2122     VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
2123     MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
2124     ProtocolVersion(protocolClassVersion), ClassABIVersion(classABI) {
2125 
2126   msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
2127   usesSEHExceptions =
2128       cgm.getContext().getTargetInfo().getTriple().isWindowsMSVCEnvironment();
2129 
2130   CodeGenTypes &Types = CGM.getTypes();
2131   IntTy = cast<llvm::IntegerType>(
2132       Types.ConvertType(CGM.getContext().IntTy));
2133   LongTy = cast<llvm::IntegerType>(
2134       Types.ConvertType(CGM.getContext().LongTy));
2135   SizeTy = cast<llvm::IntegerType>(
2136       Types.ConvertType(CGM.getContext().getSizeType()));
2137   PtrDiffTy = cast<llvm::IntegerType>(
2138       Types.ConvertType(CGM.getContext().getPointerDiffType()));
2139   BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
2140 
2141   Int8Ty = llvm::Type::getInt8Ty(VMContext);
2142   // C string type.  Used in lots of places.
2143   PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
2144   ProtocolPtrTy = llvm::PointerType::getUnqual(
2145       Types.ConvertType(CGM.getContext().getObjCProtoType()));
2146 
2147   Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
2148   Zeros[1] = Zeros[0];
2149   NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
2150   // Get the selector Type.
2151   QualType selTy = CGM.getContext().getObjCSelType();
2152   if (QualType() == selTy) {
2153     SelectorTy = PtrToInt8Ty;
2154     SelectorElemTy = Int8Ty;
2155   } else {
2156     SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
2157     SelectorElemTy = CGM.getTypes().ConvertTypeForMem(selTy->getPointeeType());
2158   }
2159 
2160   PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
2161   PtrTy = PtrToInt8Ty;
2162 
2163   Int32Ty = llvm::Type::getInt32Ty(VMContext);
2164   Int64Ty = llvm::Type::getInt64Ty(VMContext);
2165 
2166   IntPtrTy =
2167       CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
2168 
2169   // Object type
2170   QualType UnqualIdTy = CGM.getContext().getObjCIdType();
2171   ASTIdTy = CanQualType();
2172   if (UnqualIdTy != QualType()) {
2173     ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
2174     IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
2175     IdElemTy = CGM.getTypes().ConvertTypeForMem(
2176         ASTIdTy.getTypePtr()->getPointeeType());
2177   } else {
2178     IdTy = PtrToInt8Ty;
2179     IdElemTy = Int8Ty;
2180   }
2181   PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
2182   ProtocolTy = llvm::StructType::get(IdTy,
2183       PtrToInt8Ty, // name
2184       PtrToInt8Ty, // protocols
2185       PtrToInt8Ty, // instance methods
2186       PtrToInt8Ty, // class methods
2187       PtrToInt8Ty, // optional instance methods
2188       PtrToInt8Ty, // optional class methods
2189       PtrToInt8Ty, // properties
2190       PtrToInt8Ty);// optional properties
2191 
2192   // struct objc_property_gsv1
2193   // {
2194   //   const char *name;
2195   //   char attributes;
2196   //   char attributes2;
2197   //   char unused1;
2198   //   char unused2;
2199   //   const char *getter_name;
2200   //   const char *getter_types;
2201   //   const char *setter_name;
2202   //   const char *setter_types;
2203   // }
2204   PropertyMetadataTy = llvm::StructType::get(CGM.getLLVMContext(), {
2205       PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty,
2206       PtrToInt8Ty, PtrToInt8Ty });
2207 
2208   ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);
2209   PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
2210 
2211   llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
2212 
2213   // void objc_exception_throw(id);
2214   ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
2215   ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
2216   // int objc_sync_enter(id);
2217   SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
2218   // int objc_sync_exit(id);
2219   SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);
2220 
2221   // void objc_enumerationMutation (id)
2222   EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);
2223 
2224   // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
2225   GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
2226                      PtrDiffTy, BoolTy);
2227   // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
2228   SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
2229                      PtrDiffTy, IdTy, BoolTy, BoolTy);
2230   // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
2231   GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
2232                            PtrDiffTy, BoolTy, BoolTy);
2233   // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
2234   SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
2235                            PtrDiffTy, BoolTy, BoolTy);
2236 
2237   // IMP type
2238   llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
2239   IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
2240               true));
2241 
2242   const LangOptions &Opts = CGM.getLangOpts();
2243   if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
2244     RuntimeVersion = 10;
2245 
2246   // Don't bother initialising the GC stuff unless we're compiling in GC mode
2247   if (Opts.getGC() != LangOptions::NonGC) {
2248     // This is a bit of an hack.  We should sort this out by having a proper
2249     // CGObjCGNUstep subclass for GC, but we may want to really support the old
2250     // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
2251     // Get selectors needed in GC mode
2252     RetainSel = GetNullarySelector("retain", CGM.getContext());
2253     ReleaseSel = GetNullarySelector("release", CGM.getContext());
2254     AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
2255 
2256     // Get functions needed in GC mode
2257 
2258     // id objc_assign_ivar(id, id, ptrdiff_t);
2259     IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);
2260     // id objc_assign_strongCast (id, id*)
2261     StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
2262                             PtrToIdTy);
2263     // id objc_assign_global(id, id*);
2264     GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);
2265     // id objc_assign_weak(id, id*);
2266     WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);
2267     // id objc_read_weak(id*);
2268     WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);
2269     // void *objc_memmove_collectable(void*, void *, size_t);
2270     MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
2271                    SizeTy);
2272   }
2273 }
2274 
2275 llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
2276                                       const std::string &Name, bool isWeak) {
2277   llvm::Constant *ClassName = MakeConstantString(Name);
2278   // With the incompatible ABI, this will need to be replaced with a direct
2279   // reference to the class symbol.  For the compatible nonfragile ABI we are
2280   // still performing this lookup at run time but emitting the symbol for the
2281   // class externally so that we can make the switch later.
2282   //
2283   // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
2284   // with memoized versions or with static references if it's safe to do so.
2285   if (!isWeak)
2286     EmitClassRef(Name);
2287 
2288   llvm::FunctionCallee ClassLookupFn = CGM.CreateRuntimeFunction(
2289       llvm::FunctionType::get(IdTy, PtrToInt8Ty, true), "objc_lookup_class");
2290   return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
2291 }
2292 
2293 // This has to perform the lookup every time, since posing and related
2294 // techniques can modify the name -> class mapping.
2295 llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
2296                                  const ObjCInterfaceDecl *OID) {
2297   auto *Value =
2298       GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
2299   if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value))
2300     CGM.setGVProperties(ClassSymbol, OID);
2301   return Value;
2302 }
2303 
2304 llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
2305   auto *Value  = GetClassNamed(CGF, "NSAutoreleasePool", false);
2306   if (CGM.getTriple().isOSBinFormatCOFF()) {
2307     if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
2308       IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
2309       TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2310       DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2311 
2312       const VarDecl *VD = nullptr;
2313       for (const auto *Result : DC->lookup(&II))
2314         if ((VD = dyn_cast<VarDecl>(Result)))
2315           break;
2316 
2317       CGM.setGVProperties(ClassSymbol, VD);
2318     }
2319   }
2320   return Value;
2321 }
2322 
2323 llvm::Value *CGObjCGNU::GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
2324                                          const std::string &TypeEncoding) {
2325   SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
2326   llvm::GlobalAlias *SelValue = nullptr;
2327 
2328   for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
2329       e = Types.end() ; i!=e ; i++) {
2330     if (i->first == TypeEncoding) {
2331       SelValue = i->second;
2332       break;
2333     }
2334   }
2335   if (!SelValue) {
2336     SelValue = llvm::GlobalAlias::create(SelectorElemTy, 0,
2337                                          llvm::GlobalValue::PrivateLinkage,
2338                                          ".objc_selector_" + Sel.getAsString(),
2339                                          &TheModule);
2340     Types.emplace_back(TypeEncoding, SelValue);
2341   }
2342 
2343   return SelValue;
2344 }
2345 
2346 Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
2347   llvm::Value *SelValue = GetSelector(CGF, Sel);
2348 
2349   // Store it to a temporary.  Does this satisfy the semantics of
2350   // GetAddrOfSelector?  Hopefully.
2351   Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
2352                                      CGF.getPointerAlign());
2353   CGF.Builder.CreateStore(SelValue, tmp);
2354   return tmp;
2355 }
2356 
2357 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
2358   return GetTypedSelector(CGF, Sel, std::string());
2359 }
2360 
2361 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
2362                                     const ObjCMethodDecl *Method) {
2363   std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
2364   return GetTypedSelector(CGF, Method->getSelector(), SelTypes);
2365 }
2366 
2367 llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
2368   if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
2369     // With the old ABI, there was only one kind of catchall, which broke
2370     // foreign exceptions.  With the new ABI, we use __objc_id_typeinfo as
2371     // a pointer indicating object catchalls, and NULL to indicate real
2372     // catchalls
2373     if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2374       return MakeConstantString("@id");
2375     } else {
2376       return nullptr;
2377     }
2378   }
2379 
2380   // All other types should be Objective-C interface pointer types.
2381   const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
2382   assert(OPT && "Invalid @catch type.");
2383   const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
2384   assert(IDecl && "Invalid @catch type.");
2385   return MakeConstantString(IDecl->getIdentifier()->getName());
2386 }
2387 
2388 llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
2389   if (usesSEHExceptions)
2390     return CGM.getCXXABI().getAddrOfRTTIDescriptor(T);
2391 
2392   if (!CGM.getLangOpts().CPlusPlus)
2393     return CGObjCGNU::GetEHType(T);
2394 
2395   // For Objective-C++, we want to provide the ability to catch both C++ and
2396   // Objective-C objects in the same function.
2397 
2398   // There's a particular fixed type info for 'id'.
2399   if (T->isObjCIdType() ||
2400       T->isObjCQualifiedIdType()) {
2401     llvm::Constant *IDEHType =
2402       CGM.getModule().getGlobalVariable("__objc_id_type_info");
2403     if (!IDEHType)
2404       IDEHType =
2405         new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
2406                                  false,
2407                                  llvm::GlobalValue::ExternalLinkage,
2408                                  nullptr, "__objc_id_type_info");
2409     return IDEHType;
2410   }
2411 
2412   const ObjCObjectPointerType *PT =
2413     T->getAs<ObjCObjectPointerType>();
2414   assert(PT && "Invalid @catch type.");
2415   const ObjCInterfaceType *IT = PT->getInterfaceType();
2416   assert(IT && "Invalid @catch type.");
2417   std::string className =
2418       std::string(IT->getDecl()->getIdentifier()->getName());
2419 
2420   std::string typeinfoName = "__objc_eh_typeinfo_" + className;
2421 
2422   // Return the existing typeinfo if it exists
2423   if (llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName))
2424     return typeinfo;
2425 
2426   // Otherwise create it.
2427 
2428   // vtable for gnustep::libobjc::__objc_class_type_info
2429   // It's quite ugly hard-coding this.  Ideally we'd generate it using the host
2430   // platform's name mangling.
2431   const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
2432   auto *Vtable = TheModule.getGlobalVariable(vtableName);
2433   if (!Vtable) {
2434     Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
2435                                       llvm::GlobalValue::ExternalLinkage,
2436                                       nullptr, vtableName);
2437   }
2438   llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
2439   auto *BVtable =
2440       llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two);
2441 
2442   llvm::Constant *typeName =
2443     ExportUniqueString(className, "__objc_eh_typename_");
2444 
2445   ConstantInitBuilder builder(CGM);
2446   auto fields = builder.beginStruct();
2447   fields.add(BVtable);
2448   fields.add(typeName);
2449   llvm::Constant *TI =
2450     fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
2451                                  CGM.getPointerAlign(),
2452                                  /*constant*/ false,
2453                                  llvm::GlobalValue::LinkOnceODRLinkage);
2454   return TI;
2455 }
2456 
2457 /// Generate an NSConstantString object.
2458 ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
2459 
2460   std::string Str = SL->getString().str();
2461   CharUnits Align = CGM.getPointerAlign();
2462 
2463   // Look for an existing one
2464   llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
2465   if (old != ObjCStrings.end())
2466     return ConstantAddress(old->getValue(), Int8Ty, Align);
2467 
2468   StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
2469 
2470   if (StringClass.empty()) StringClass = "NSConstantString";
2471 
2472   std::string Sym = "_OBJC_CLASS_";
2473   Sym += StringClass;
2474 
2475   llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
2476 
2477   if (!isa)
2478     isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */ false,
2479                                    llvm::GlobalValue::ExternalWeakLinkage,
2480                                    nullptr, Sym);
2481 
2482   ConstantInitBuilder Builder(CGM);
2483   auto Fields = Builder.beginStruct();
2484   Fields.add(isa);
2485   Fields.add(MakeConstantString(Str));
2486   Fields.addInt(IntTy, Str.size());
2487   llvm::Constant *ObjCStr = Fields.finishAndCreateGlobal(".objc_str", Align);
2488   ObjCStrings[Str] = ObjCStr;
2489   ConstantStrings.push_back(ObjCStr);
2490   return ConstantAddress(ObjCStr, Int8Ty, Align);
2491 }
2492 
2493 ///Generates a message send where the super is the receiver.  This is a message
2494 ///send to self with special delivery semantics indicating which class's method
2495 ///should be called.
2496 RValue
2497 CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
2498                                     ReturnValueSlot Return,
2499                                     QualType ResultType,
2500                                     Selector Sel,
2501                                     const ObjCInterfaceDecl *Class,
2502                                     bool isCategoryImpl,
2503                                     llvm::Value *Receiver,
2504                                     bool IsClassMessage,
2505                                     const CallArgList &CallArgs,
2506                                     const ObjCMethodDecl *Method) {
2507   CGBuilderTy &Builder = CGF.Builder;
2508   if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
2509     if (Sel == RetainSel || Sel == AutoreleaseSel) {
2510       return RValue::get(EnforceType(Builder, Receiver,
2511                   CGM.getTypes().ConvertType(ResultType)));
2512     }
2513     if (Sel == ReleaseSel) {
2514       return RValue::get(nullptr);
2515     }
2516   }
2517 
2518   llvm::Value *cmd = GetSelector(CGF, Sel);
2519   CallArgList ActualArgs;
2520 
2521   ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
2522   ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
2523   ActualArgs.addFrom(CallArgs);
2524 
2525   MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
2526 
2527   llvm::Value *ReceiverClass = nullptr;
2528   bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2529   if (isV2ABI) {
2530     ReceiverClass = GetClassNamed(CGF,
2531         Class->getSuperClass()->getNameAsString(), /*isWeak*/false);
2532     if (IsClassMessage)  {
2533       // Load the isa pointer of the superclass is this is a class method.
2534       ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2535                                             llvm::PointerType::getUnqual(IdTy));
2536       ReceiverClass =
2537         Builder.CreateAlignedLoad(IdTy, ReceiverClass, CGF.getPointerAlign());
2538     }
2539     ReceiverClass = EnforceType(Builder, ReceiverClass, IdTy);
2540   } else {
2541     if (isCategoryImpl) {
2542       llvm::FunctionCallee classLookupFunction = nullptr;
2543       if (IsClassMessage)  {
2544         classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2545               IdTy, PtrTy, true), "objc_get_meta_class");
2546       } else {
2547         classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2548               IdTy, PtrTy, true), "objc_get_class");
2549       }
2550       ReceiverClass = Builder.CreateCall(classLookupFunction,
2551           MakeConstantString(Class->getNameAsString()));
2552     } else {
2553       // Set up global aliases for the metaclass or class pointer if they do not
2554       // already exist.  These will are forward-references which will be set to
2555       // pointers to the class and metaclass structure created for the runtime
2556       // load function.  To send a message to super, we look up the value of the
2557       // super_class pointer from either the class or metaclass structure.
2558       if (IsClassMessage)  {
2559         if (!MetaClassPtrAlias) {
2560           MetaClassPtrAlias = llvm::GlobalAlias::create(
2561               IdElemTy, 0, llvm::GlobalValue::InternalLinkage,
2562               ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
2563         }
2564         ReceiverClass = MetaClassPtrAlias;
2565       } else {
2566         if (!ClassPtrAlias) {
2567           ClassPtrAlias = llvm::GlobalAlias::create(
2568               IdElemTy, 0, llvm::GlobalValue::InternalLinkage,
2569               ".objc_class_ref" + Class->getNameAsString(), &TheModule);
2570         }
2571         ReceiverClass = ClassPtrAlias;
2572       }
2573     }
2574     // Cast the pointer to a simplified version of the class structure
2575     llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);
2576     ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2577                                           llvm::PointerType::getUnqual(CastTy));
2578     // Get the superclass pointer
2579     ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
2580     // Load the superclass pointer
2581     ReceiverClass =
2582       Builder.CreateAlignedLoad(IdTy, ReceiverClass, CGF.getPointerAlign());
2583   }
2584   // Construct the structure used to look up the IMP
2585   llvm::StructType *ObjCSuperTy =
2586       llvm::StructType::get(Receiver->getType(), IdTy);
2587 
2588   Address ObjCSuper = CGF.CreateTempAlloca(ObjCSuperTy,
2589                               CGF.getPointerAlign());
2590 
2591   Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
2592   Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
2593 
2594   // Get the IMP
2595   llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
2596   imp = EnforceType(Builder, imp, MSI.MessengerType);
2597 
2598   llvm::Metadata *impMD[] = {
2599       llvm::MDString::get(VMContext, Sel.getAsString()),
2600       llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
2601       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2602           llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
2603   llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
2604 
2605   CGCallee callee(CGCalleeInfo(), imp);
2606 
2607   llvm::CallBase *call;
2608   RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
2609   call->setMetadata(msgSendMDKind, node);
2610   return msgRet;
2611 }
2612 
2613 /// Generate code for a message send expression.
2614 RValue
2615 CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
2616                                ReturnValueSlot Return,
2617                                QualType ResultType,
2618                                Selector Sel,
2619                                llvm::Value *Receiver,
2620                                const CallArgList &CallArgs,
2621                                const ObjCInterfaceDecl *Class,
2622                                const ObjCMethodDecl *Method) {
2623   CGBuilderTy &Builder = CGF.Builder;
2624 
2625   // Strip out message sends to retain / release in GC mode
2626   if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
2627     if (Sel == RetainSel || Sel == AutoreleaseSel) {
2628       return RValue::get(EnforceType(Builder, Receiver,
2629                   CGM.getTypes().ConvertType(ResultType)));
2630     }
2631     if (Sel == ReleaseSel) {
2632       return RValue::get(nullptr);
2633     }
2634   }
2635 
2636   IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
2637   llvm::Value *cmd;
2638   if (Method)
2639     cmd = GetSelector(CGF, Method);
2640   else
2641     cmd = GetSelector(CGF, Sel);
2642   cmd = EnforceType(Builder, cmd, SelectorTy);
2643   Receiver = EnforceType(Builder, Receiver, IdTy);
2644 
2645   llvm::Metadata *impMD[] = {
2646       llvm::MDString::get(VMContext, Sel.getAsString()),
2647       llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
2648       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2649           llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
2650   llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
2651 
2652   CallArgList ActualArgs;
2653   ActualArgs.add(RValue::get(Receiver), ASTIdTy);
2654   ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
2655   ActualArgs.addFrom(CallArgs);
2656 
2657   MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
2658 
2659   // Message sends are expected to return a zero value when the
2660   // receiver is nil.  At one point, this was only guaranteed for
2661   // simple integer and pointer types, but expectations have grown
2662   // over time.
2663   //
2664   // Given a nil receiver, the GNU runtime's message lookup will
2665   // return a stub function that simply sets various return-value
2666   // registers to zero and then returns.  That's good enough for us
2667   // if and only if (1) the calling conventions of that stub are
2668   // compatible with the signature we're using and (2) the registers
2669   // it sets are sufficient to produce a zero value of the return type.
2670   // Rather than doing a whole target-specific analysis, we assume it
2671   // only works for void, integer, and pointer types, and in all
2672   // other cases we do an explicit nil check is emitted code.  In
2673   // addition to ensuring we produe a zero value for other types, this
2674   // sidesteps the few outright CC incompatibilities we know about that
2675   // could otherwise lead to crashes, like when a method is expected to
2676   // return on the x87 floating point stack or adjust the stack pointer
2677   // because of an indirect return.
2678   bool hasParamDestroyedInCallee = false;
2679   bool requiresExplicitZeroResult = false;
2680   bool requiresNilReceiverCheck = [&] {
2681     // We never need a check if we statically know the receiver isn't nil.
2682     if (!canMessageReceiverBeNull(CGF, Method, /*IsSuper*/ false,
2683                                   Class, Receiver))
2684       return false;
2685 
2686     // If there's a consumed argument, we need a nil check.
2687     if (Method && Method->hasParamDestroyedInCallee()) {
2688       hasParamDestroyedInCallee = true;
2689     }
2690 
2691     // If the return value isn't flagged as unused, and the result
2692     // type isn't in our narrow set where we assume compatibility,
2693     // we need a nil check to ensure a nil value.
2694     if (!Return.isUnused()) {
2695       if (ResultType->isVoidType()) {
2696         // void results are definitely okay.
2697       } else if (ResultType->hasPointerRepresentation() &&
2698                  CGM.getTypes().isZeroInitializable(ResultType)) {
2699         // Pointer types should be fine as long as they have
2700         // bitwise-zero null pointers.  But do we need to worry
2701         // about unusual address spaces?
2702       } else if (ResultType->isIntegralOrEnumerationType()) {
2703         // Bitwise zero should always be zero for integral types.
2704         // FIXME: we probably need a size limit here, but we've
2705         // never imposed one before
2706       } else {
2707         // Otherwise, use an explicit check just to be sure.
2708         requiresExplicitZeroResult = true;
2709       }
2710     }
2711 
2712     return hasParamDestroyedInCallee || requiresExplicitZeroResult;
2713   }();
2714 
2715   // We will need to explicitly zero-initialize an aggregate result slot
2716   // if we generally require explicit zeroing and we have an aggregate
2717   // result.
2718   bool requiresExplicitAggZeroing =
2719     requiresExplicitZeroResult && CGF.hasAggregateEvaluationKind(ResultType);
2720 
2721   // The block we're going to end up in after any message send or nil path.
2722   llvm::BasicBlock *continueBB = nullptr;
2723   // The block that eventually branched to continueBB along the nil path.
2724   llvm::BasicBlock *nilPathBB = nullptr;
2725   // The block to do explicit work in along the nil path, if necessary.
2726   llvm::BasicBlock *nilCleanupBB = nullptr;
2727 
2728   // Emit the nil-receiver check.
2729   if (requiresNilReceiverCheck) {
2730     llvm::BasicBlock *messageBB = CGF.createBasicBlock("msgSend");
2731     continueBB = CGF.createBasicBlock("continue");
2732 
2733     // If we need to zero-initialize an aggregate result or destroy
2734     // consumed arguments, we'll need a separate cleanup block.
2735     // Otherwise we can just branch directly to the continuation block.
2736     if (requiresExplicitAggZeroing || hasParamDestroyedInCallee) {
2737       nilCleanupBB = CGF.createBasicBlock("nilReceiverCleanup");
2738     } else {
2739       nilPathBB = Builder.GetInsertBlock();
2740     }
2741 
2742     llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
2743             llvm::Constant::getNullValue(Receiver->getType()));
2744     Builder.CreateCondBr(isNil, nilCleanupBB ? nilCleanupBB : continueBB,
2745                          messageBB);
2746     CGF.EmitBlock(messageBB);
2747   }
2748 
2749   // Get the IMP to call
2750   llvm::Value *imp;
2751 
2752   // If we have non-legacy dispatch specified, we try using the objc_msgSend()
2753   // functions.  These are not supported on all platforms (or all runtimes on a
2754   // given platform), so we
2755   switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
2756     case CodeGenOptions::Legacy:
2757       imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
2758       break;
2759     case CodeGenOptions::Mixed:
2760     case CodeGenOptions::NonLegacy:
2761       if (CGM.ReturnTypeUsesFPRet(ResultType)) {
2762         imp =
2763             CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2764                                       "objc_msgSend_fpret")
2765                 .getCallee();
2766       } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
2767         // The actual types here don't matter - we're going to bitcast the
2768         // function anyway
2769         imp =
2770             CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2771                                       "objc_msgSend_stret")
2772                 .getCallee();
2773       } else {
2774         imp = CGM.CreateRuntimeFunction(
2775                      llvm::FunctionType::get(IdTy, IdTy, true), "objc_msgSend")
2776                   .getCallee();
2777       }
2778   }
2779 
2780   // Reset the receiver in case the lookup modified it
2781   ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy);
2782 
2783   imp = EnforceType(Builder, imp, MSI.MessengerType);
2784 
2785   llvm::CallBase *call;
2786   CGCallee callee(CGCalleeInfo(), imp);
2787   RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
2788   call->setMetadata(msgSendMDKind, node);
2789 
2790   if (requiresNilReceiverCheck) {
2791     llvm::BasicBlock *nonNilPathBB = CGF.Builder.GetInsertBlock();
2792     CGF.Builder.CreateBr(continueBB);
2793 
2794     // Emit the nil path if we decided it was necessary above.
2795     if (nilCleanupBB) {
2796       CGF.EmitBlock(nilCleanupBB);
2797 
2798       if (hasParamDestroyedInCallee) {
2799         destroyCalleeDestroyedArguments(CGF, Method, CallArgs);
2800       }
2801 
2802       if (requiresExplicitAggZeroing) {
2803         assert(msgRet.isAggregate());
2804         Address addr = msgRet.getAggregateAddress();
2805         CGF.EmitNullInitialization(addr, ResultType);
2806       }
2807 
2808       nilPathBB = CGF.Builder.GetInsertBlock();
2809       CGF.Builder.CreateBr(continueBB);
2810     }
2811 
2812     // Enter the continuation block and emit a phi if required.
2813     CGF.EmitBlock(continueBB);
2814     if (msgRet.isScalar()) {
2815       // If the return type is void, do nothing
2816       if (llvm::Value *v = msgRet.getScalarVal()) {
2817         llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
2818         phi->addIncoming(v, nonNilPathBB);
2819         phi->addIncoming(CGM.EmitNullConstant(ResultType), nilPathBB);
2820         msgRet = RValue::get(phi);
2821       }
2822     } else if (msgRet.isAggregate()) {
2823       // Aggregate zeroing is handled in nilCleanupBB when it's required.
2824     } else /* isComplex() */ {
2825       std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
2826       llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
2827       phi->addIncoming(v.first, nonNilPathBB);
2828       phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
2829                        nilPathBB);
2830       llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
2831       phi2->addIncoming(v.second, nonNilPathBB);
2832       phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
2833                         nilPathBB);
2834       msgRet = RValue::getComplex(phi, phi2);
2835     }
2836   }
2837   return msgRet;
2838 }
2839 
2840 /// Generates a MethodList.  Used in construction of a objc_class and
2841 /// objc_category structures.
2842 llvm::Constant *CGObjCGNU::
2843 GenerateMethodList(StringRef ClassName,
2844                    StringRef CategoryName,
2845                    ArrayRef<const ObjCMethodDecl*> Methods,
2846                    bool isClassMethodList) {
2847   if (Methods.empty())
2848     return NULLPtr;
2849 
2850   ConstantInitBuilder Builder(CGM);
2851 
2852   auto MethodList = Builder.beginStruct();
2853   MethodList.addNullPointer(CGM.Int8PtrTy);
2854   MethodList.addInt(Int32Ty, Methods.size());
2855 
2856   // Get the method structure type.
2857   llvm::StructType *ObjCMethodTy =
2858     llvm::StructType::get(CGM.getLLVMContext(), {
2859       PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2860       PtrToInt8Ty, // Method types
2861       IMPTy        // Method pointer
2862     });
2863   bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2864   if (isV2ABI) {
2865     // size_t size;
2866     llvm::DataLayout td(&TheModule);
2867     MethodList.addInt(SizeTy, td.getTypeSizeInBits(ObjCMethodTy) /
2868         CGM.getContext().getCharWidth());
2869     ObjCMethodTy =
2870       llvm::StructType::get(CGM.getLLVMContext(), {
2871         IMPTy,       // Method pointer
2872         PtrToInt8Ty, // Selector
2873         PtrToInt8Ty  // Extended type encoding
2874       });
2875   } else {
2876     ObjCMethodTy =
2877       llvm::StructType::get(CGM.getLLVMContext(), {
2878         PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2879         PtrToInt8Ty, // Method types
2880         IMPTy        // Method pointer
2881       });
2882   }
2883   auto MethodArray = MethodList.beginArray();
2884   ASTContext &Context = CGM.getContext();
2885   for (const auto *OMD : Methods) {
2886     llvm::Constant *FnPtr =
2887       TheModule.getFunction(getSymbolNameForMethod(OMD));
2888     assert(FnPtr && "Can't generate metadata for method that doesn't exist");
2889     auto Method = MethodArray.beginStruct(ObjCMethodTy);
2890     if (isV2ABI) {
2891       Method.add(FnPtr);
2892       Method.add(GetConstantSelector(OMD->getSelector(),
2893           Context.getObjCEncodingForMethodDecl(OMD)));
2894       Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD, true)));
2895     } else {
2896       Method.add(MakeConstantString(OMD->getSelector().getAsString()));
2897       Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD)));
2898       Method.add(FnPtr);
2899     }
2900     Method.finishAndAddTo(MethodArray);
2901   }
2902   MethodArray.finishAndAddTo(MethodList);
2903 
2904   // Create an instance of the structure
2905   return MethodList.finishAndCreateGlobal(".objc_method_list",
2906                                           CGM.getPointerAlign());
2907 }
2908 
2909 /// Generates an IvarList.  Used in construction of a objc_class.
2910 llvm::Constant *CGObjCGNU::
2911 GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
2912                  ArrayRef<llvm::Constant *> IvarTypes,
2913                  ArrayRef<llvm::Constant *> IvarOffsets,
2914                  ArrayRef<llvm::Constant *> IvarAlign,
2915                  ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) {
2916   if (IvarNames.empty())
2917     return NULLPtr;
2918 
2919   ConstantInitBuilder Builder(CGM);
2920 
2921   // Structure containing array count followed by array.
2922   auto IvarList = Builder.beginStruct();
2923   IvarList.addInt(IntTy, (int)IvarNames.size());
2924 
2925   // Get the ivar structure type.
2926   llvm::StructType *ObjCIvarTy =
2927       llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);
2928 
2929   // Array of ivar structures.
2930   auto Ivars = IvarList.beginArray(ObjCIvarTy);
2931   for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
2932     auto Ivar = Ivars.beginStruct(ObjCIvarTy);
2933     Ivar.add(IvarNames[i]);
2934     Ivar.add(IvarTypes[i]);
2935     Ivar.add(IvarOffsets[i]);
2936     Ivar.finishAndAddTo(Ivars);
2937   }
2938   Ivars.finishAndAddTo(IvarList);
2939 
2940   // Create an instance of the structure
2941   return IvarList.finishAndCreateGlobal(".objc_ivar_list",
2942                                         CGM.getPointerAlign());
2943 }
2944 
2945 /// Generate a class structure
2946 llvm::Constant *CGObjCGNU::GenerateClassStructure(
2947     llvm::Constant *MetaClass,
2948     llvm::Constant *SuperClass,
2949     unsigned info,
2950     const char *Name,
2951     llvm::Constant *Version,
2952     llvm::Constant *InstanceSize,
2953     llvm::Constant *IVars,
2954     llvm::Constant *Methods,
2955     llvm::Constant *Protocols,
2956     llvm::Constant *IvarOffsets,
2957     llvm::Constant *Properties,
2958     llvm::Constant *StrongIvarBitmap,
2959     llvm::Constant *WeakIvarBitmap,
2960     bool isMeta) {
2961   // Set up the class structure
2962   // Note:  Several of these are char*s when they should be ids.  This is
2963   // because the runtime performs this translation on load.
2964   //
2965   // Fields marked New ABI are part of the GNUstep runtime.  We emit them
2966   // anyway; the classes will still work with the GNU runtime, they will just
2967   // be ignored.
2968   llvm::StructType *ClassTy = llvm::StructType::get(
2969       PtrToInt8Ty,        // isa
2970       PtrToInt8Ty,        // super_class
2971       PtrToInt8Ty,        // name
2972       LongTy,             // version
2973       LongTy,             // info
2974       LongTy,             // instance_size
2975       IVars->getType(),   // ivars
2976       Methods->getType(), // methods
2977       // These are all filled in by the runtime, so we pretend
2978       PtrTy, // dtable
2979       PtrTy, // subclass_list
2980       PtrTy, // sibling_class
2981       PtrTy, // protocols
2982       PtrTy, // gc_object_type
2983       // New ABI:
2984       LongTy,                 // abi_version
2985       IvarOffsets->getType(), // ivar_offsets
2986       Properties->getType(),  // properties
2987       IntPtrTy,               // strong_pointers
2988       IntPtrTy                // weak_pointers
2989       );
2990 
2991   ConstantInitBuilder Builder(CGM);
2992   auto Elements = Builder.beginStruct(ClassTy);
2993 
2994   // Fill in the structure
2995 
2996   // isa
2997   Elements.add(MetaClass);
2998   // super_class
2999   Elements.add(SuperClass);
3000   // name
3001   Elements.add(MakeConstantString(Name, ".class_name"));
3002   // version
3003   Elements.addInt(LongTy, 0);
3004   // info
3005   Elements.addInt(LongTy, info);
3006   // instance_size
3007   if (isMeta) {
3008     llvm::DataLayout td(&TheModule);
3009     Elements.addInt(LongTy,
3010                     td.getTypeSizeInBits(ClassTy) /
3011                       CGM.getContext().getCharWidth());
3012   } else
3013     Elements.add(InstanceSize);
3014   // ivars
3015   Elements.add(IVars);
3016   // methods
3017   Elements.add(Methods);
3018   // These are all filled in by the runtime, so we pretend
3019   // dtable
3020   Elements.add(NULLPtr);
3021   // subclass_list
3022   Elements.add(NULLPtr);
3023   // sibling_class
3024   Elements.add(NULLPtr);
3025   // protocols
3026   Elements.add(Protocols);
3027   // gc_object_type
3028   Elements.add(NULLPtr);
3029   // abi_version
3030   Elements.addInt(LongTy, ClassABIVersion);
3031   // ivar_offsets
3032   Elements.add(IvarOffsets);
3033   // properties
3034   Elements.add(Properties);
3035   // strong_pointers
3036   Elements.add(StrongIvarBitmap);
3037   // weak_pointers
3038   Elements.add(WeakIvarBitmap);
3039   // Create an instance of the structure
3040   // This is now an externally visible symbol, so that we can speed up class
3041   // messages in the next ABI.  We may already have some weak references to
3042   // this, so check and fix them properly.
3043   std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
3044           std::string(Name));
3045   llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
3046   llvm::Constant *Class =
3047     Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
3048                                    llvm::GlobalValue::ExternalLinkage);
3049   if (ClassRef) {
3050     ClassRef->replaceAllUsesWith(Class);
3051     ClassRef->removeFromParent();
3052     Class->setName(ClassSym);
3053   }
3054   return Class;
3055 }
3056 
3057 llvm::Constant *CGObjCGNU::
3058 GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) {
3059   // Get the method structure type.
3060   llvm::StructType *ObjCMethodDescTy =
3061     llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
3062   ASTContext &Context = CGM.getContext();
3063   ConstantInitBuilder Builder(CGM);
3064   auto MethodList = Builder.beginStruct();
3065   MethodList.addInt(IntTy, Methods.size());
3066   auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
3067   for (auto *M : Methods) {
3068     auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
3069     Method.add(MakeConstantString(M->getSelector().getAsString()));
3070     Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(M)));
3071     Method.finishAndAddTo(MethodArray);
3072   }
3073   MethodArray.finishAndAddTo(MethodList);
3074   return MethodList.finishAndCreateGlobal(".objc_method_list",
3075                                           CGM.getPointerAlign());
3076 }
3077 
3078 // Create the protocol list structure used in classes, categories and so on
3079 llvm::Constant *
3080 CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
3081 
3082   ConstantInitBuilder Builder(CGM);
3083   auto ProtocolList = Builder.beginStruct();
3084   ProtocolList.add(NULLPtr);
3085   ProtocolList.addInt(LongTy, Protocols.size());
3086 
3087   auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
3088   for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
3089       iter != endIter ; iter++) {
3090     llvm::Constant *protocol = nullptr;
3091     llvm::StringMap<llvm::Constant*>::iterator value =
3092       ExistingProtocols.find(*iter);
3093     if (value == ExistingProtocols.end()) {
3094       protocol = GenerateEmptyProtocol(*iter);
3095     } else {
3096       protocol = value->getValue();
3097     }
3098     Elements.add(protocol);
3099   }
3100   Elements.finishAndAddTo(ProtocolList);
3101   return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3102                                             CGM.getPointerAlign());
3103 }
3104 
3105 llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
3106                                             const ObjCProtocolDecl *PD) {
3107   auto protocol = GenerateProtocolRef(PD);
3108   llvm::Type *T =
3109       CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
3110   return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
3111 }
3112 
3113 llvm::Constant *CGObjCGNU::GenerateProtocolRef(const ObjCProtocolDecl *PD) {
3114   llvm::Constant *&protocol = ExistingProtocols[PD->getNameAsString()];
3115   if (!protocol)
3116     GenerateProtocol(PD);
3117   assert(protocol && "Unknown protocol");
3118   return protocol;
3119 }
3120 
3121 llvm::Constant *
3122 CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) {
3123   llvm::Constant *ProtocolList = GenerateProtocolList({});
3124   llvm::Constant *MethodList = GenerateProtocolMethodList({});
3125   // Protocols are objects containing lists of the methods implemented and
3126   // protocols adopted.
3127   ConstantInitBuilder Builder(CGM);
3128   auto Elements = Builder.beginStruct();
3129 
3130   // The isa pointer must be set to a magic number so the runtime knows it's
3131   // the correct layout.
3132   Elements.add(llvm::ConstantExpr::getIntToPtr(
3133           llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
3134 
3135   Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
3136   Elements.add(ProtocolList); /* .protocol_list */
3137   Elements.add(MethodList);   /* .instance_methods */
3138   Elements.add(MethodList);   /* .class_methods */
3139   Elements.add(MethodList);   /* .optional_instance_methods */
3140   Elements.add(MethodList);   /* .optional_class_methods */
3141   Elements.add(NULLPtr);      /* .properties */
3142   Elements.add(NULLPtr);      /* .optional_properties */
3143   return Elements.finishAndCreateGlobal(SymbolForProtocol(ProtocolName),
3144                                         CGM.getPointerAlign());
3145 }
3146 
3147 void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
3148   if (PD->isNonRuntimeProtocol())
3149     return;
3150 
3151   std::string ProtocolName = PD->getNameAsString();
3152 
3153   // Use the protocol definition, if there is one.
3154   if (const ObjCProtocolDecl *Def = PD->getDefinition())
3155     PD = Def;
3156 
3157   SmallVector<std::string, 16> Protocols;
3158   for (const auto *PI : PD->protocols())
3159     Protocols.push_back(PI->getNameAsString());
3160   SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3161   SmallVector<const ObjCMethodDecl*, 16> OptionalInstanceMethods;
3162   for (const auto *I : PD->instance_methods())
3163     if (I->isOptional())
3164       OptionalInstanceMethods.push_back(I);
3165     else
3166       InstanceMethods.push_back(I);
3167   // Collect information about class methods:
3168   SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3169   SmallVector<const ObjCMethodDecl*, 16> OptionalClassMethods;
3170   for (const auto *I : PD->class_methods())
3171     if (I->isOptional())
3172       OptionalClassMethods.push_back(I);
3173     else
3174       ClassMethods.push_back(I);
3175 
3176   llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
3177   llvm::Constant *InstanceMethodList =
3178     GenerateProtocolMethodList(InstanceMethods);
3179   llvm::Constant *ClassMethodList =
3180     GenerateProtocolMethodList(ClassMethods);
3181   llvm::Constant *OptionalInstanceMethodList =
3182     GenerateProtocolMethodList(OptionalInstanceMethods);
3183   llvm::Constant *OptionalClassMethodList =
3184     GenerateProtocolMethodList(OptionalClassMethods);
3185 
3186   // Property metadata: name, attributes, isSynthesized, setter name, setter
3187   // types, getter name, getter types.
3188   // The isSynthesized value is always set to 0 in a protocol.  It exists to
3189   // simplify the runtime library by allowing it to use the same data
3190   // structures for protocol metadata everywhere.
3191 
3192   llvm::Constant *PropertyList =
3193     GeneratePropertyList(nullptr, PD, false, false);
3194   llvm::Constant *OptionalPropertyList =
3195     GeneratePropertyList(nullptr, PD, false, true);
3196 
3197   // Protocols are objects containing lists of the methods implemented and
3198   // protocols adopted.
3199   // The isa pointer must be set to a magic number so the runtime knows it's
3200   // the correct layout.
3201   ConstantInitBuilder Builder(CGM);
3202   auto Elements = Builder.beginStruct();
3203   Elements.add(
3204       llvm::ConstantExpr::getIntToPtr(
3205           llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
3206   Elements.add(MakeConstantString(ProtocolName));
3207   Elements.add(ProtocolList);
3208   Elements.add(InstanceMethodList);
3209   Elements.add(ClassMethodList);
3210   Elements.add(OptionalInstanceMethodList);
3211   Elements.add(OptionalClassMethodList);
3212   Elements.add(PropertyList);
3213   Elements.add(OptionalPropertyList);
3214   ExistingProtocols[ProtocolName] =
3215       Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign());
3216 }
3217 void CGObjCGNU::GenerateProtocolHolderCategory() {
3218   // Collect information about instance methods
3219 
3220   ConstantInitBuilder Builder(CGM);
3221   auto Elements = Builder.beginStruct();
3222 
3223   const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
3224   const std::string CategoryName = "AnotherHack";
3225   Elements.add(MakeConstantString(CategoryName));
3226   Elements.add(MakeConstantString(ClassName));
3227   // Instance method list
3228   Elements.add(GenerateMethodList(ClassName, CategoryName, {}, false));
3229   // Class method list
3230   Elements.add(GenerateMethodList(ClassName, CategoryName, {}, true));
3231 
3232   // Protocol list
3233   ConstantInitBuilder ProtocolListBuilder(CGM);
3234   auto ProtocolList = ProtocolListBuilder.beginStruct();
3235   ProtocolList.add(NULLPtr);
3236   ProtocolList.addInt(LongTy, ExistingProtocols.size());
3237   auto ProtocolElements = ProtocolList.beginArray(PtrTy);
3238   for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
3239        iter != endIter ; iter++) {
3240     ProtocolElements.add(iter->getValue());
3241   }
3242   ProtocolElements.finishAndAddTo(ProtocolList);
3243   Elements.add(ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3244                                                   CGM.getPointerAlign()));
3245   Categories.push_back(
3246       Elements.finishAndCreateGlobal("", CGM.getPointerAlign()));
3247 }
3248 
3249 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
3250 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
3251 /// bits set to their values, LSB first, while larger ones are stored in a
3252 /// structure of this / form:
3253 ///
3254 /// struct { int32_t length; int32_t values[length]; };
3255 ///
3256 /// The values in the array are stored in host-endian format, with the least
3257 /// significant bit being assumed to come first in the bitfield.  Therefore, a
3258 /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
3259 /// bitfield / with the 63rd bit set will be 1<<64.
3260 llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
3261   int bitCount = bits.size();
3262   int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
3263   if (bitCount < ptrBits) {
3264     uint64_t val = 1;
3265     for (int i=0 ; i<bitCount ; ++i) {
3266       if (bits[i]) val |= 1ULL<<(i+1);
3267     }
3268     return llvm::ConstantInt::get(IntPtrTy, val);
3269   }
3270   SmallVector<llvm::Constant *, 8> values;
3271   int v=0;
3272   while (v < bitCount) {
3273     int32_t word = 0;
3274     for (int i=0 ; (i<32) && (v<bitCount)  ; ++i) {
3275       if (bits[v]) word |= 1<<i;
3276       v++;
3277     }
3278     values.push_back(llvm::ConstantInt::get(Int32Ty, word));
3279   }
3280 
3281   ConstantInitBuilder builder(CGM);
3282   auto fields = builder.beginStruct();
3283   fields.addInt(Int32Ty, values.size());
3284   auto array = fields.beginArray();
3285   for (auto *v : values) array.add(v);
3286   array.finishAndAddTo(fields);
3287 
3288   llvm::Constant *GS =
3289     fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
3290   llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
3291   return ptr;
3292 }
3293 
3294 llvm::Constant *CGObjCGNU::GenerateCategoryProtocolList(const
3295     ObjCCategoryDecl *OCD) {
3296   const auto &RefPro = OCD->getReferencedProtocols();
3297   const auto RuntimeProtos =
3298       GetRuntimeProtocolList(RefPro.begin(), RefPro.end());
3299   SmallVector<std::string, 16> Protocols;
3300   for (const auto *PD : RuntimeProtos)
3301     Protocols.push_back(PD->getNameAsString());
3302   return GenerateProtocolList(Protocols);
3303 }
3304 
3305 void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
3306   const ObjCInterfaceDecl *Class = OCD->getClassInterface();
3307   std::string ClassName = Class->getNameAsString();
3308   std::string CategoryName = OCD->getNameAsString();
3309 
3310   // Collect the names of referenced protocols
3311   const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
3312 
3313   ConstantInitBuilder Builder(CGM);
3314   auto Elements = Builder.beginStruct();
3315   Elements.add(MakeConstantString(CategoryName));
3316   Elements.add(MakeConstantString(ClassName));
3317   // Instance method list
3318   SmallVector<ObjCMethodDecl*, 16> InstanceMethods;
3319   InstanceMethods.insert(InstanceMethods.begin(), OCD->instmeth_begin(),
3320       OCD->instmeth_end());
3321   Elements.add(
3322       GenerateMethodList(ClassName, CategoryName, InstanceMethods, false));
3323 
3324   // Class method list
3325 
3326   SmallVector<ObjCMethodDecl*, 16> ClassMethods;
3327   ClassMethods.insert(ClassMethods.begin(), OCD->classmeth_begin(),
3328       OCD->classmeth_end());
3329   Elements.add(GenerateMethodList(ClassName, CategoryName, ClassMethods, true));
3330 
3331   // Protocol list
3332   Elements.add(GenerateCategoryProtocolList(CatDecl));
3333   if (isRuntime(ObjCRuntime::GNUstep, 2)) {
3334     const ObjCCategoryDecl *Category =
3335       Class->FindCategoryDeclaration(OCD->getIdentifier());
3336     if (Category) {
3337       // Instance properties
3338       Elements.add(GeneratePropertyList(OCD, Category, false));
3339       // Class properties
3340       Elements.add(GeneratePropertyList(OCD, Category, true));
3341     } else {
3342       Elements.addNullPointer(PtrTy);
3343       Elements.addNullPointer(PtrTy);
3344     }
3345   }
3346 
3347   Categories.push_back(Elements.finishAndCreateGlobal(
3348       std::string(".objc_category_") + ClassName + CategoryName,
3349       CGM.getPointerAlign()));
3350 }
3351 
3352 llvm::Constant *CGObjCGNU::GeneratePropertyList(const Decl *Container,
3353     const ObjCContainerDecl *OCD,
3354     bool isClassProperty,
3355     bool protocolOptionalProperties) {
3356 
3357   SmallVector<const ObjCPropertyDecl *, 16> Properties;
3358   llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
3359   bool isProtocol = isa<ObjCProtocolDecl>(OCD);
3360   ASTContext &Context = CGM.getContext();
3361 
3362   std::function<void(const ObjCProtocolDecl *Proto)> collectProtocolProperties
3363     = [&](const ObjCProtocolDecl *Proto) {
3364       for (const auto *P : Proto->protocols())
3365         collectProtocolProperties(P);
3366       for (const auto *PD : Proto->properties()) {
3367         if (isClassProperty != PD->isClassProperty())
3368           continue;
3369         // Skip any properties that are declared in protocols that this class
3370         // conforms to but are not actually implemented by this class.
3371         if (!isProtocol && !Context.getObjCPropertyImplDeclForPropertyDecl(PD, Container))
3372           continue;
3373         if (!PropertySet.insert(PD->getIdentifier()).second)
3374           continue;
3375         Properties.push_back(PD);
3376       }
3377     };
3378 
3379   if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3380     for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
3381       for (auto *PD : ClassExt->properties()) {
3382         if (isClassProperty != PD->isClassProperty())
3383           continue;
3384         PropertySet.insert(PD->getIdentifier());
3385         Properties.push_back(PD);
3386       }
3387 
3388   for (const auto *PD : OCD->properties()) {
3389     if (isClassProperty != PD->isClassProperty())
3390       continue;
3391     // If we're generating a list for a protocol, skip optional / required ones
3392     // when generating the other list.
3393     if (isProtocol && (protocolOptionalProperties != PD->isOptional()))
3394       continue;
3395     // Don't emit duplicate metadata for properties that were already in a
3396     // class extension.
3397     if (!PropertySet.insert(PD->getIdentifier()).second)
3398       continue;
3399 
3400     Properties.push_back(PD);
3401   }
3402 
3403   if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3404     for (const auto *P : OID->all_referenced_protocols())
3405       collectProtocolProperties(P);
3406   else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD))
3407     for (const auto *P : CD->protocols())
3408       collectProtocolProperties(P);
3409 
3410   auto numProperties = Properties.size();
3411 
3412   if (numProperties == 0)
3413     return NULLPtr;
3414 
3415   ConstantInitBuilder builder(CGM);
3416   auto propertyList = builder.beginStruct();
3417   auto properties = PushPropertyListHeader(propertyList, numProperties);
3418 
3419   // Add all of the property methods need adding to the method list and to the
3420   // property metadata list.
3421   for (auto *property : Properties) {
3422     bool isSynthesized = false;
3423     bool isDynamic = false;
3424     if (!isProtocol) {
3425       auto *propertyImpl = Context.getObjCPropertyImplDeclForPropertyDecl(property, Container);
3426       if (propertyImpl) {
3427         isSynthesized = (propertyImpl->getPropertyImplementation() ==
3428             ObjCPropertyImplDecl::Synthesize);
3429         isDynamic = (propertyImpl->getPropertyImplementation() ==
3430             ObjCPropertyImplDecl::Dynamic);
3431       }
3432     }
3433     PushProperty(properties, property, Container, isSynthesized, isDynamic);
3434   }
3435   properties.finishAndAddTo(propertyList);
3436 
3437   return propertyList.finishAndCreateGlobal(".objc_property_list",
3438                                             CGM.getPointerAlign());
3439 }
3440 
3441 void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
3442   // Get the class declaration for which the alias is specified.
3443   ObjCInterfaceDecl *ClassDecl =
3444     const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
3445   ClassAliases.emplace_back(ClassDecl->getNameAsString(),
3446                             OAD->getNameAsString());
3447 }
3448 
3449 void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
3450   ASTContext &Context = CGM.getContext();
3451 
3452   // Get the superclass name.
3453   const ObjCInterfaceDecl * SuperClassDecl =
3454     OID->getClassInterface()->getSuperClass();
3455   std::string SuperClassName;
3456   if (SuperClassDecl) {
3457     SuperClassName = SuperClassDecl->getNameAsString();
3458     EmitClassRef(SuperClassName);
3459   }
3460 
3461   // Get the class name
3462   ObjCInterfaceDecl *ClassDecl =
3463       const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
3464   std::string ClassName = ClassDecl->getNameAsString();
3465 
3466   // Emit the symbol that is used to generate linker errors if this class is
3467   // referenced in other modules but not declared.
3468   std::string classSymbolName = "__objc_class_name_" + ClassName;
3469   if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
3470     symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
3471   } else {
3472     new llvm::GlobalVariable(TheModule, LongTy, false,
3473                              llvm::GlobalValue::ExternalLinkage,
3474                              llvm::ConstantInt::get(LongTy, 0),
3475                              classSymbolName);
3476   }
3477 
3478   // Get the size of instances.
3479   int instanceSize =
3480     Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
3481 
3482   // Collect information about instance variables.
3483   SmallVector<llvm::Constant*, 16> IvarNames;
3484   SmallVector<llvm::Constant*, 16> IvarTypes;
3485   SmallVector<llvm::Constant*, 16> IvarOffsets;
3486   SmallVector<llvm::Constant*, 16> IvarAligns;
3487   SmallVector<Qualifiers::ObjCLifetime, 16> IvarOwnership;
3488 
3489   ConstantInitBuilder IvarOffsetBuilder(CGM);
3490   auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
3491   SmallVector<bool, 16> WeakIvars;
3492   SmallVector<bool, 16> StrongIvars;
3493 
3494   int superInstanceSize = !SuperClassDecl ? 0 :
3495     Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
3496   // For non-fragile ivars, set the instance size to 0 - {the size of just this
3497   // class}.  The runtime will then set this to the correct value on load.
3498   if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
3499     instanceSize = 0 - (instanceSize - superInstanceSize);
3500   }
3501 
3502   for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3503        IVD = IVD->getNextIvar()) {
3504       // Store the name
3505       IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
3506       // Get the type encoding for this ivar
3507       std::string TypeStr;
3508       Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);
3509       IvarTypes.push_back(MakeConstantString(TypeStr));
3510       IvarAligns.push_back(llvm::ConstantInt::get(IntTy,
3511             Context.getTypeSize(IVD->getType())));
3512       // Get the offset
3513       uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
3514       uint64_t Offset = BaseOffset;
3515       if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
3516         Offset = BaseOffset - superInstanceSize;
3517       }
3518       llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
3519       // Create the direct offset value
3520       std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
3521           IVD->getNameAsString();
3522 
3523       llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
3524       if (OffsetVar) {
3525         OffsetVar->setInitializer(OffsetValue);
3526         // If this is the real definition, change its linkage type so that
3527         // different modules will use this one, rather than their private
3528         // copy.
3529         OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
3530       } else
3531         OffsetVar = new llvm::GlobalVariable(TheModule, Int32Ty,
3532           false, llvm::GlobalValue::ExternalLinkage,
3533           OffsetValue, OffsetName);
3534       IvarOffsets.push_back(OffsetValue);
3535       IvarOffsetValues.add(OffsetVar);
3536       Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
3537       IvarOwnership.push_back(lt);
3538       switch (lt) {
3539         case Qualifiers::OCL_Strong:
3540           StrongIvars.push_back(true);
3541           WeakIvars.push_back(false);
3542           break;
3543         case Qualifiers::OCL_Weak:
3544           StrongIvars.push_back(false);
3545           WeakIvars.push_back(true);
3546           break;
3547         default:
3548           StrongIvars.push_back(false);
3549           WeakIvars.push_back(false);
3550       }
3551   }
3552   llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
3553   llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
3554   llvm::GlobalVariable *IvarOffsetArray =
3555     IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
3556                                            CGM.getPointerAlign());
3557 
3558   // Collect information about instance methods
3559   SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3560   InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
3561       OID->instmeth_end());
3562 
3563   SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3564   ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
3565       OID->classmeth_end());
3566 
3567   llvm::Constant *Properties = GeneratePropertyList(OID, ClassDecl);
3568 
3569   // Collect the names of referenced protocols
3570   auto RefProtocols = ClassDecl->protocols();
3571   auto RuntimeProtocols =
3572       GetRuntimeProtocolList(RefProtocols.begin(), RefProtocols.end());
3573   SmallVector<std::string, 16> Protocols;
3574   for (const auto *I : RuntimeProtocols)
3575     Protocols.push_back(I->getNameAsString());
3576 
3577   // Get the superclass pointer.
3578   llvm::Constant *SuperClass;
3579   if (!SuperClassName.empty()) {
3580     SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
3581   } else {
3582     SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
3583   }
3584   // Empty vector used to construct empty method lists
3585   SmallVector<llvm::Constant*, 1>  empty;
3586   // Generate the method and instance variable lists
3587   llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
3588       InstanceMethods, false);
3589   llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
3590       ClassMethods, true);
3591   llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
3592       IvarOffsets, IvarAligns, IvarOwnership);
3593   // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
3594   // we emit a symbol containing the offset for each ivar in the class.  This
3595   // allows code compiled for the non-Fragile ABI to inherit from code compiled
3596   // for the legacy ABI, without causing problems.  The converse is also
3597   // possible, but causes all ivar accesses to be fragile.
3598 
3599   // Offset pointer for getting at the correct field in the ivar list when
3600   // setting up the alias.  These are: The base address for the global, the
3601   // ivar array (second field), the ivar in this list (set for each ivar), and
3602   // the offset (third field in ivar structure)
3603   llvm::Type *IndexTy = Int32Ty;
3604   llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
3605       llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 2 : 1), nullptr,
3606       llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 3 : 2) };
3607 
3608   unsigned ivarIndex = 0;
3609   for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3610        IVD = IVD->getNextIvar()) {
3611       const std::string Name = GetIVarOffsetVariableName(ClassDecl, IVD);
3612       offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
3613       // Get the correct ivar field
3614       llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
3615           cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
3616           offsetPointerIndexes);
3617       // Get the existing variable, if one exists.
3618       llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
3619       if (offset) {
3620         offset->setInitializer(offsetValue);
3621         // If this is the real definition, change its linkage type so that
3622         // different modules will use this one, rather than their private
3623         // copy.
3624         offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
3625       } else
3626         // Add a new alias if there isn't one already.
3627         new llvm::GlobalVariable(TheModule, offsetValue->getType(),
3628                 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
3629       ++ivarIndex;
3630   }
3631   llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
3632 
3633   //Generate metaclass for class methods
3634   llvm::Constant *MetaClassStruct = GenerateClassStructure(
3635       NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
3636       NULLPtr, ClassMethodList, NULLPtr, NULLPtr,
3637       GeneratePropertyList(OID, ClassDecl, true), ZeroPtr, ZeroPtr, true);
3638   CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct),
3639                       OID->getClassInterface());
3640 
3641   // Generate the class structure
3642   llvm::Constant *ClassStruct = GenerateClassStructure(
3643       MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
3644       llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
3645       GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
3646       StrongIvarBitmap, WeakIvarBitmap);
3647   CGM.setGVProperties(cast<llvm::GlobalValue>(ClassStruct),
3648                       OID->getClassInterface());
3649 
3650   // Resolve the class aliases, if they exist.
3651   if (ClassPtrAlias) {
3652     ClassPtrAlias->replaceAllUsesWith(ClassStruct);
3653     ClassPtrAlias->eraseFromParent();
3654     ClassPtrAlias = nullptr;
3655   }
3656   if (MetaClassPtrAlias) {
3657     MetaClassPtrAlias->replaceAllUsesWith(MetaClassStruct);
3658     MetaClassPtrAlias->eraseFromParent();
3659     MetaClassPtrAlias = nullptr;
3660   }
3661 
3662   // Add class structure to list to be added to the symtab later
3663   Classes.push_back(ClassStruct);
3664 }
3665 
3666 llvm::Function *CGObjCGNU::ModuleInitFunction() {
3667   // Only emit an ObjC load function if no Objective-C stuff has been called
3668   if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
3669       ExistingProtocols.empty() && SelectorTable.empty())
3670     return nullptr;
3671 
3672   // Add all referenced protocols to a category.
3673   GenerateProtocolHolderCategory();
3674 
3675   llvm::StructType *selStructTy = dyn_cast<llvm::StructType>(SelectorElemTy);
3676   if (!selStructTy) {
3677     selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
3678                                         { PtrToInt8Ty, PtrToInt8Ty });
3679   }
3680 
3681   // Generate statics list:
3682   llvm::Constant *statics = NULLPtr;
3683   if (!ConstantStrings.empty()) {
3684     llvm::GlobalVariable *fileStatics = [&] {
3685       ConstantInitBuilder builder(CGM);
3686       auto staticsStruct = builder.beginStruct();
3687 
3688       StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
3689       if (stringClass.empty()) stringClass = "NXConstantString";
3690       staticsStruct.add(MakeConstantString(stringClass,
3691                                            ".objc_static_class_name"));
3692 
3693       auto array = staticsStruct.beginArray();
3694       array.addAll(ConstantStrings);
3695       array.add(NULLPtr);
3696       array.finishAndAddTo(staticsStruct);
3697 
3698       return staticsStruct.finishAndCreateGlobal(".objc_statics",
3699                                                  CGM.getPointerAlign());
3700     }();
3701 
3702     ConstantInitBuilder builder(CGM);
3703     auto allStaticsArray = builder.beginArray(fileStatics->getType());
3704     allStaticsArray.add(fileStatics);
3705     allStaticsArray.addNullPointer(fileStatics->getType());
3706 
3707     statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
3708                                                     CGM.getPointerAlign());
3709   }
3710 
3711   // Array of classes, categories, and constant objects.
3712 
3713   SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
3714   unsigned selectorCount;
3715 
3716   // Pointer to an array of selectors used in this module.
3717   llvm::GlobalVariable *selectorList = [&] {
3718     ConstantInitBuilder builder(CGM);
3719     auto selectors = builder.beginArray(selStructTy);
3720     auto &table = SelectorTable; // MSVC workaround
3721     std::vector<Selector> allSelectors;
3722     for (auto &entry : table)
3723       allSelectors.push_back(entry.first);
3724     llvm::sort(allSelectors);
3725 
3726     for (auto &untypedSel : allSelectors) {
3727       std::string selNameStr = untypedSel.getAsString();
3728       llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
3729 
3730       for (TypedSelector &sel : table[untypedSel]) {
3731         llvm::Constant *selectorTypeEncoding = NULLPtr;
3732         if (!sel.first.empty())
3733           selectorTypeEncoding =
3734             MakeConstantString(sel.first, ".objc_sel_types");
3735 
3736         auto selStruct = selectors.beginStruct(selStructTy);
3737         selStruct.add(selName);
3738         selStruct.add(selectorTypeEncoding);
3739         selStruct.finishAndAddTo(selectors);
3740 
3741         // Store the selector alias for later replacement
3742         selectorAliases.push_back(sel.second);
3743       }
3744     }
3745 
3746     // Remember the number of entries in the selector table.
3747     selectorCount = selectors.size();
3748 
3749     // NULL-terminate the selector list.  This should not actually be required,
3750     // because the selector list has a length field.  Unfortunately, the GCC
3751     // runtime decides to ignore the length field and expects a NULL terminator,
3752     // and GCC cooperates with this by always setting the length to 0.
3753     auto selStruct = selectors.beginStruct(selStructTy);
3754     selStruct.add(NULLPtr);
3755     selStruct.add(NULLPtr);
3756     selStruct.finishAndAddTo(selectors);
3757 
3758     return selectors.finishAndCreateGlobal(".objc_selector_list",
3759                                            CGM.getPointerAlign());
3760   }();
3761 
3762   // Now that all of the static selectors exist, create pointers to them.
3763   for (unsigned i = 0; i < selectorCount; ++i) {
3764     llvm::Constant *idxs[] = {
3765       Zeros[0],
3766       llvm::ConstantInt::get(Int32Ty, i)
3767     };
3768     // FIXME: We're generating redundant loads and stores here!
3769     llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
3770         selectorList->getValueType(), selectorList, idxs);
3771     selectorAliases[i]->replaceAllUsesWith(selPtr);
3772     selectorAliases[i]->eraseFromParent();
3773   }
3774 
3775   llvm::GlobalVariable *symtab = [&] {
3776     ConstantInitBuilder builder(CGM);
3777     auto symtab = builder.beginStruct();
3778 
3779     // Number of static selectors
3780     symtab.addInt(LongTy, selectorCount);
3781 
3782     symtab.add(selectorList);
3783 
3784     // Number of classes defined.
3785     symtab.addInt(CGM.Int16Ty, Classes.size());
3786     // Number of categories defined
3787     symtab.addInt(CGM.Int16Ty, Categories.size());
3788 
3789     // Create an array of classes, then categories, then static object instances
3790     auto classList = symtab.beginArray(PtrToInt8Ty);
3791     classList.addAll(Classes);
3792     classList.addAll(Categories);
3793     //  NULL-terminated list of static object instances (mainly constant strings)
3794     classList.add(statics);
3795     classList.add(NULLPtr);
3796     classList.finishAndAddTo(symtab);
3797 
3798     // Construct the symbol table.
3799     return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
3800   }();
3801 
3802   // The symbol table is contained in a module which has some version-checking
3803   // constants
3804   llvm::Constant *module = [&] {
3805     llvm::Type *moduleEltTys[] = {
3806       LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
3807     };
3808     llvm::StructType *moduleTy = llvm::StructType::get(
3809         CGM.getLLVMContext(),
3810         ArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
3811 
3812     ConstantInitBuilder builder(CGM);
3813     auto module = builder.beginStruct(moduleTy);
3814     // Runtime version, used for ABI compatibility checking.
3815     module.addInt(LongTy, RuntimeVersion);
3816     // sizeof(ModuleTy)
3817     module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
3818 
3819     // The path to the source file where this module was declared
3820     SourceManager &SM = CGM.getContext().getSourceManager();
3821     OptionalFileEntryRef mainFile = SM.getFileEntryRefForID(SM.getMainFileID());
3822     std::string path =
3823         (mainFile->getDir().getName() + "/" + mainFile->getName()).str();
3824     module.add(MakeConstantString(path, ".objc_source_file_name"));
3825     module.add(symtab);
3826 
3827     if (RuntimeVersion >= 10) {
3828       switch (CGM.getLangOpts().getGC()) {
3829       case LangOptions::GCOnly:
3830         module.addInt(IntTy, 2);
3831         break;
3832       case LangOptions::NonGC:
3833         if (CGM.getLangOpts().ObjCAutoRefCount)
3834           module.addInt(IntTy, 1);
3835         else
3836           module.addInt(IntTy, 0);
3837         break;
3838       case LangOptions::HybridGC:
3839         module.addInt(IntTy, 1);
3840         break;
3841       }
3842     }
3843 
3844     return module.finishAndCreateGlobal("", CGM.getPointerAlign());
3845   }();
3846 
3847   // Create the load function calling the runtime entry point with the module
3848   // structure
3849   llvm::Function * LoadFunction = llvm::Function::Create(
3850       llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
3851       llvm::GlobalValue::InternalLinkage, ".objc_load_function",
3852       &TheModule);
3853   llvm::BasicBlock *EntryBB =
3854       llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
3855   CGBuilderTy Builder(CGM, VMContext);
3856   Builder.SetInsertPoint(EntryBB);
3857 
3858   llvm::FunctionType *FT =
3859     llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
3860   llvm::FunctionCallee Register =
3861       CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
3862   Builder.CreateCall(Register, module);
3863 
3864   if (!ClassAliases.empty()) {
3865     llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
3866     llvm::FunctionType *RegisterAliasTy =
3867       llvm::FunctionType::get(Builder.getVoidTy(),
3868                               ArgTypes, false);
3869     llvm::Function *RegisterAlias = llvm::Function::Create(
3870       RegisterAliasTy,
3871       llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
3872       &TheModule);
3873     llvm::BasicBlock *AliasBB =
3874       llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
3875     llvm::BasicBlock *NoAliasBB =
3876       llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
3877 
3878     // Branch based on whether the runtime provided class_registerAlias_np()
3879     llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
3880             llvm::Constant::getNullValue(RegisterAlias->getType()));
3881     Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
3882 
3883     // The true branch (has alias registration function):
3884     Builder.SetInsertPoint(AliasBB);
3885     // Emit alias registration calls:
3886     for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
3887        iter != ClassAliases.end(); ++iter) {
3888        llvm::Constant *TheClass =
3889           TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
3890        if (TheClass) {
3891          Builder.CreateCall(RegisterAlias,
3892                             {TheClass, MakeConstantString(iter->second)});
3893        }
3894     }
3895     // Jump to end:
3896     Builder.CreateBr(NoAliasBB);
3897 
3898     // Missing alias registration function, just return from the function:
3899     Builder.SetInsertPoint(NoAliasBB);
3900   }
3901   Builder.CreateRetVoid();
3902 
3903   return LoadFunction;
3904 }
3905 
3906 llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
3907                                           const ObjCContainerDecl *CD) {
3908   CodeGenTypes &Types = CGM.getTypes();
3909   llvm::FunctionType *MethodTy =
3910     Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
3911   std::string FunctionName = getSymbolNameForMethod(OMD);
3912 
3913   llvm::Function *Method
3914     = llvm::Function::Create(MethodTy,
3915                              llvm::GlobalValue::InternalLinkage,
3916                              FunctionName,
3917                              &TheModule);
3918   return Method;
3919 }
3920 
3921 void CGObjCGNU::GenerateDirectMethodPrologue(CodeGenFunction &CGF,
3922                                              llvm::Function *Fn,
3923                                              const ObjCMethodDecl *OMD,
3924                                              const ObjCContainerDecl *CD) {
3925   // GNU runtime doesn't support direct calls at this time
3926 }
3927 
3928 llvm::FunctionCallee CGObjCGNU::GetPropertyGetFunction() {
3929   return GetPropertyFn;
3930 }
3931 
3932 llvm::FunctionCallee CGObjCGNU::GetPropertySetFunction() {
3933   return SetPropertyFn;
3934 }
3935 
3936 llvm::FunctionCallee CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
3937                                                                 bool copy) {
3938   return nullptr;
3939 }
3940 
3941 llvm::FunctionCallee CGObjCGNU::GetGetStructFunction() {
3942   return GetStructPropertyFn;
3943 }
3944 
3945 llvm::FunctionCallee CGObjCGNU::GetSetStructFunction() {
3946   return SetStructPropertyFn;
3947 }
3948 
3949 llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectGetFunction() {
3950   return nullptr;
3951 }
3952 
3953 llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectSetFunction() {
3954   return nullptr;
3955 }
3956 
3957 llvm::FunctionCallee CGObjCGNU::EnumerationMutationFunction() {
3958   return EnumerationMutationFn;
3959 }
3960 
3961 void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
3962                                      const ObjCAtSynchronizedStmt &S) {
3963   EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
3964 }
3965 
3966 
3967 void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
3968                             const ObjCAtTryStmt &S) {
3969   // Unlike the Apple non-fragile runtimes, which also uses
3970   // unwind-based zero cost exceptions, the GNU Objective C runtime's
3971   // EH support isn't a veneer over C++ EH.  Instead, exception
3972   // objects are created by objc_exception_throw and destroyed by
3973   // the personality function; this avoids the need for bracketing
3974   // catch handlers with calls to __blah_begin_catch/__blah_end_catch
3975   // (or even _Unwind_DeleteException), but probably doesn't
3976   // interoperate very well with foreign exceptions.
3977   //
3978   // In Objective-C++ mode, we actually emit something equivalent to the C++
3979   // exception handler.
3980   EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
3981 }
3982 
3983 void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
3984                               const ObjCAtThrowStmt &S,
3985                               bool ClearInsertionPoint) {
3986   llvm::Value *ExceptionAsObject;
3987   bool isRethrow = false;
3988 
3989   if (const Expr *ThrowExpr = S.getThrowExpr()) {
3990     llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
3991     ExceptionAsObject = Exception;
3992   } else {
3993     assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
3994            "Unexpected rethrow outside @catch block.");
3995     ExceptionAsObject = CGF.ObjCEHValueStack.back();
3996     isRethrow = true;
3997   }
3998   if (isRethrow && usesSEHExceptions) {
3999     // For SEH, ExceptionAsObject may be undef, because the catch handler is
4000     // not passed it for catchalls and so it is not visible to the catch
4001     // funclet.  The real thrown object will still be live on the stack at this
4002     // point and will be rethrown.  If we are explicitly rethrowing the object
4003     // that was passed into the `@catch` block, then this code path is not
4004     // reached and we will instead call `objc_exception_throw` with an explicit
4005     // argument.
4006     llvm::CallBase *Throw = CGF.EmitRuntimeCallOrInvoke(ExceptionReThrowFn);
4007     Throw->setDoesNotReturn();
4008   }
4009   else {
4010     ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
4011     llvm::CallBase *Throw =
4012         CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
4013     Throw->setDoesNotReturn();
4014   }
4015   CGF.Builder.CreateUnreachable();
4016   if (ClearInsertionPoint)
4017     CGF.Builder.ClearInsertionPoint();
4018 }
4019 
4020 llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
4021                                           Address AddrWeakObj) {
4022   CGBuilderTy &B = CGF.Builder;
4023   return B.CreateCall(WeakReadFn,
4024                       EnforceType(B, AddrWeakObj.getPointer(), PtrToIdTy));
4025 }
4026 
4027 void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
4028                                    llvm::Value *src, Address dst) {
4029   CGBuilderTy &B = CGF.Builder;
4030   src = EnforceType(B, src, IdTy);
4031   llvm::Value *dstVal = EnforceType(B, dst.getPointer(), PtrToIdTy);
4032   B.CreateCall(WeakAssignFn, {src, dstVal});
4033 }
4034 
4035 void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
4036                                      llvm::Value *src, Address dst,
4037                                      bool threadlocal) {
4038   CGBuilderTy &B = CGF.Builder;
4039   src = EnforceType(B, src, IdTy);
4040   llvm::Value *dstVal = EnforceType(B, dst.getPointer(), PtrToIdTy);
4041   // FIXME. Add threadloca assign API
4042   assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
4043   B.CreateCall(GlobalAssignFn, {src, dstVal});
4044 }
4045 
4046 void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
4047                                    llvm::Value *src, Address dst,
4048                                    llvm::Value *ivarOffset) {
4049   CGBuilderTy &B = CGF.Builder;
4050   src = EnforceType(B, src, IdTy);
4051   llvm::Value *dstVal = EnforceType(B, dst.getPointer(), IdTy);
4052   B.CreateCall(IvarAssignFn, {src, dstVal, ivarOffset});
4053 }
4054 
4055 void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
4056                                          llvm::Value *src, Address dst) {
4057   CGBuilderTy &B = CGF.Builder;
4058   src = EnforceType(B, src, IdTy);
4059   llvm::Value *dstVal = EnforceType(B, dst.getPointer(), PtrToIdTy);
4060   B.CreateCall(StrongCastAssignFn, {src, dstVal});
4061 }
4062 
4063 void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
4064                                          Address DestPtr,
4065                                          Address SrcPtr,
4066                                          llvm::Value *Size) {
4067   CGBuilderTy &B = CGF.Builder;
4068   llvm::Value *DestPtrVal = EnforceType(B, DestPtr.getPointer(), PtrTy);
4069   llvm::Value *SrcPtrVal = EnforceType(B, SrcPtr.getPointer(), PtrTy);
4070 
4071   B.CreateCall(MemMoveFn, {DestPtrVal, SrcPtrVal, Size});
4072 }
4073 
4074 llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
4075                               const ObjCInterfaceDecl *ID,
4076                               const ObjCIvarDecl *Ivar) {
4077   const std::string Name = GetIVarOffsetVariableName(ID, Ivar);
4078   // Emit the variable and initialize it with what we think the correct value
4079   // is.  This allows code compiled with non-fragile ivars to work correctly
4080   // when linked against code which isn't (most of the time).
4081   llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
4082   if (!IvarOffsetPointer)
4083     IvarOffsetPointer = new llvm::GlobalVariable(
4084         TheModule, llvm::PointerType::getUnqual(VMContext), false,
4085         llvm::GlobalValue::ExternalLinkage, nullptr, Name);
4086   return IvarOffsetPointer;
4087 }
4088 
4089 LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
4090                                        QualType ObjectTy,
4091                                        llvm::Value *BaseValue,
4092                                        const ObjCIvarDecl *Ivar,
4093                                        unsigned CVRQualifiers) {
4094   const ObjCInterfaceDecl *ID =
4095     ObjectTy->castAs<ObjCObjectType>()->getInterface();
4096   return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4097                                   EmitIvarOffset(CGF, ID, Ivar));
4098 }
4099 
4100 static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
4101                                                   const ObjCInterfaceDecl *OID,
4102                                                   const ObjCIvarDecl *OIVD) {
4103   for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
4104        next = next->getNextIvar()) {
4105     if (OIVD == next)
4106       return OID;
4107   }
4108 
4109   // Otherwise check in the super class.
4110   if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
4111     return FindIvarInterface(Context, Super, OIVD);
4112 
4113   return nullptr;
4114 }
4115 
4116 llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
4117                          const ObjCInterfaceDecl *Interface,
4118                          const ObjCIvarDecl *Ivar) {
4119   if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
4120     Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
4121 
4122     // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
4123     // and ExternalLinkage, so create a reference to the ivar global and rely on
4124     // the definition being created as part of GenerateClass.
4125     if (RuntimeVersion < 10 ||
4126         CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
4127       return CGF.Builder.CreateZExtOrBitCast(
4128           CGF.Builder.CreateAlignedLoad(
4129               Int32Ty,
4130               CGF.Builder.CreateAlignedLoad(
4131                   llvm::PointerType::getUnqual(VMContext),
4132                   ObjCIvarOffsetVariable(Interface, Ivar),
4133                   CGF.getPointerAlign(), "ivar"),
4134               CharUnits::fromQuantity(4)),
4135           PtrDiffTy);
4136     std::string name = "__objc_ivar_offset_value_" +
4137       Interface->getNameAsString() +"." + Ivar->getNameAsString();
4138     CharUnits Align = CGM.getIntAlign();
4139     llvm::Value *Offset = TheModule.getGlobalVariable(name);
4140     if (!Offset) {
4141       auto GV = new llvm::GlobalVariable(TheModule, IntTy,
4142           false, llvm::GlobalValue::LinkOnceAnyLinkage,
4143           llvm::Constant::getNullValue(IntTy), name);
4144       GV->setAlignment(Align.getAsAlign());
4145       Offset = GV;
4146     }
4147     Offset = CGF.Builder.CreateAlignedLoad(IntTy, Offset, Align);
4148     if (Offset->getType() != PtrDiffTy)
4149       Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
4150     return Offset;
4151   }
4152   uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
4153   return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
4154 }
4155 
4156 CGObjCRuntime *
4157 clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
4158   auto Runtime = CGM.getLangOpts().ObjCRuntime;
4159   switch (Runtime.getKind()) {
4160   case ObjCRuntime::GNUstep:
4161     if (Runtime.getVersion() >= VersionTuple(2, 0))
4162       return new CGObjCGNUstep2(CGM);
4163     return new CGObjCGNUstep(CGM);
4164 
4165   case ObjCRuntime::GCC:
4166     return new CGObjCGCC(CGM);
4167 
4168   case ObjCRuntime::ObjFW:
4169     return new CGObjCObjFW(CGM);
4170 
4171   case ObjCRuntime::FragileMacOSX:
4172   case ObjCRuntime::MacOSX:
4173   case ObjCRuntime::iOS:
4174   case ObjCRuntime::WatchOS:
4175     llvm_unreachable("these runtimes are not GNU runtimes");
4176   }
4177   llvm_unreachable("bad runtime");
4178 }
4179