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