1 //===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This provides Objective-C code generation targeting the GNU runtime.  The
11 // class in this file generates structures used by the GNU Objective-C runtime
12 // library.  These structures are defined in objc/objc.h and objc/objc-api.h in
13 // the GNU runtime distribution.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "CGObjCRuntime.h"
18 #include "CGCleanup.h"
19 #include "CodeGenFunction.h"
20 #include "CodeGenModule.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/RecordLayout.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/Basic/FileManager.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/StringMap.h"
30 #include "llvm/IR/CallSite.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/Support/Compiler.h"
36 #include <cstdarg>
37 
38 
39 using namespace clang;
40 using namespace CodeGen;
41 
42 
43 namespace {
44 /// Class that lazily initialises the runtime function.  Avoids inserting the
45 /// types and the function declaration into a module if they're not used, and
46 /// avoids constructing the type more than once if it's used more than once.
47 class LazyRuntimeFunction {
48   CodeGenModule *CGM;
49   llvm::FunctionType *FTy;
50   const char *FunctionName;
51   llvm::Constant *Function;
52 
53 public:
54   /// Constructor leaves this class uninitialized, because it is intended to
55   /// be used as a field in another class and not all of the types that are
56   /// used as arguments will necessarily be available at construction time.
57   LazyRuntimeFunction()
58       : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
59 
60   /// Initialises the lazy function with the name, return type, and the types
61   /// of the arguments.
62   LLVM_END_WITH_NULL
63   void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy, ...) {
64     CGM = Mod;
65     FunctionName = name;
66     Function = nullptr;
67     std::vector<llvm::Type *> ArgTys;
68     va_list Args;
69     va_start(Args, RetTy);
70     while (llvm::Type *ArgTy = va_arg(Args, llvm::Type *))
71       ArgTys.push_back(ArgTy);
72     va_end(Args);
73     FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
74   }
75 
76   llvm::FunctionType *getType() { return FTy; }
77 
78   /// Overloaded cast operator, allows the class to be implicitly cast to an
79   /// LLVM constant.
80   operator llvm::Constant *() {
81     if (!Function) {
82       if (!FunctionName)
83         return nullptr;
84       Function =
85           cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
86     }
87     return Function;
88   }
89   operator llvm::Function *() {
90     return cast<llvm::Function>((llvm::Constant *)*this);
91   }
92 };
93 
94 
95 /// GNU Objective-C runtime code generation.  This class implements the parts of
96 /// Objective-C support that are specific to the GNU family of runtimes (GCC,
97 /// GNUstep and ObjFW).
98 class CGObjCGNU : public CGObjCRuntime {
99 protected:
100   /// The LLVM module into which output is inserted
101   llvm::Module &TheModule;
102   /// strut objc_super.  Used for sending messages to super.  This structure
103   /// contains the receiver (object) and the expected class.
104   llvm::StructType *ObjCSuperTy;
105   /// struct objc_super*.  The type of the argument to the superclass message
106   /// lookup functions.
107   llvm::PointerType *PtrToObjCSuperTy;
108   /// LLVM type for selectors.  Opaque pointer (i8*) unless a header declaring
109   /// SEL is included in a header somewhere, in which case it will be whatever
110   /// type is declared in that header, most likely {i8*, i8*}.
111   llvm::PointerType *SelectorTy;
112   /// LLVM i8 type.  Cached here to avoid repeatedly getting it in all of the
113   /// places where it's used
114   llvm::IntegerType *Int8Ty;
115   /// Pointer to i8 - LLVM type of char*, for all of the places where the
116   /// runtime needs to deal with C strings.
117   llvm::PointerType *PtrToInt8Ty;
118   /// Instance Method Pointer type.  This is a pointer to a function that takes,
119   /// at a minimum, an object and a selector, and is the generic type for
120   /// Objective-C methods.  Due to differences between variadic / non-variadic
121   /// calling conventions, it must always be cast to the correct type before
122   /// actually being used.
123   llvm::PointerType *IMPTy;
124   /// Type of an untyped Objective-C object.  Clang treats id as a built-in type
125   /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
126   /// but if the runtime header declaring it is included then it may be a
127   /// pointer to a structure.
128   llvm::PointerType *IdTy;
129   /// Pointer to a pointer to an Objective-C object.  Used in the new ABI
130   /// message lookup function and some GC-related functions.
131   llvm::PointerType *PtrToIdTy;
132   /// The clang type of id.  Used when using the clang CGCall infrastructure to
133   /// call Objective-C methods.
134   CanQualType ASTIdTy;
135   /// LLVM type for C int type.
136   llvm::IntegerType *IntTy;
137   /// LLVM type for an opaque pointer.  This is identical to PtrToInt8Ty, but is
138   /// used in the code to document the difference between i8* meaning a pointer
139   /// to a C string and i8* meaning a pointer to some opaque type.
140   llvm::PointerType *PtrTy;
141   /// LLVM type for C long type.  The runtime uses this in a lot of places where
142   /// it should be using intptr_t, but we can't fix this without breaking
143   /// compatibility with GCC...
144   llvm::IntegerType *LongTy;
145   /// LLVM type for C size_t.  Used in various runtime data structures.
146   llvm::IntegerType *SizeTy;
147   /// LLVM type for C intptr_t.
148   llvm::IntegerType *IntPtrTy;
149   /// LLVM type for C ptrdiff_t.  Mainly used in property accessor functions.
150   llvm::IntegerType *PtrDiffTy;
151   /// LLVM type for C int*.  Used for GCC-ABI-compatible non-fragile instance
152   /// variables.
153   llvm::PointerType *PtrToIntTy;
154   /// LLVM type for Objective-C BOOL type.
155   llvm::Type *BoolTy;
156   /// 32-bit integer type, to save us needing to look it up every time it's used.
157   llvm::IntegerType *Int32Ty;
158   /// 64-bit integer type, to save us needing to look it up every time it's used.
159   llvm::IntegerType *Int64Ty;
160   /// Metadata kind used to tie method lookups to message sends.  The GNUstep
161   /// runtime provides some LLVM passes that can use this to do things like
162   /// automatic IMP caching and speculative inlining.
163   unsigned msgSendMDKind;
164   /// Helper function that generates a constant string and returns a pointer to
165   /// the start of the string.  The result of this function can be used anywhere
166   /// where the C code specifies const char*.
167   llvm::Constant *MakeConstantString(const std::string &Str,
168                                      const std::string &Name="") {
169     auto *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
170     return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
171                                                 ConstStr, Zeros);
172   }
173   /// Emits a linkonce_odr string, whose name is the prefix followed by the
174   /// string value.  This allows the linker to combine the strings between
175   /// different modules.  Used for EH typeinfo names, selector strings, and a
176   /// few other things.
177   llvm::Constant *ExportUniqueString(const std::string &Str,
178                                      const std::string prefix) {
179     std::string name = prefix + Str;
180     auto *ConstStr = TheModule.getGlobalVariable(name);
181     if (!ConstStr) {
182       llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
183       ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
184               llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
185     }
186     return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
187                                                 ConstStr, Zeros);
188   }
189   /// Generates a global structure, initialized by the elements in the vector.
190   /// The element types must match the types of the structure elements in the
191   /// first argument.
192   llvm::GlobalVariable *MakeGlobal(llvm::StructType *Ty,
193                                    ArrayRef<llvm::Constant *> V,
194                                    StringRef Name="",
195                                    llvm::GlobalValue::LinkageTypes linkage
196                                          =llvm::GlobalValue::InternalLinkage) {
197     llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
198     return new llvm::GlobalVariable(TheModule, Ty, false,
199         linkage, C, Name);
200   }
201   /// Generates a global array.  The vector must contain the same number of
202   /// elements that the array type declares, of the type specified as the array
203   /// element type.
204   llvm::GlobalVariable *MakeGlobal(llvm::ArrayType *Ty,
205                                    ArrayRef<llvm::Constant *> V,
206                                    StringRef Name="",
207                                    llvm::GlobalValue::LinkageTypes linkage
208                                          =llvm::GlobalValue::InternalLinkage) {
209     llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
210     return new llvm::GlobalVariable(TheModule, Ty, false,
211                                     linkage, C, Name);
212   }
213   /// Generates a global array, inferring the array type from the specified
214   /// element type and the size of the initialiser.
215   llvm::GlobalVariable *MakeGlobalArray(llvm::Type *Ty,
216                                         ArrayRef<llvm::Constant *> V,
217                                         StringRef Name="",
218                                         llvm::GlobalValue::LinkageTypes linkage
219                                          =llvm::GlobalValue::InternalLinkage) {
220     llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
221     return MakeGlobal(ArrayTy, V, Name, linkage);
222   }
223   /// Returns a property name and encoding string.
224   llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
225                                              const Decl *Container) {
226     const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
227     if ((R.getKind() == ObjCRuntime::GNUstep) &&
228         (R.getVersion() >= VersionTuple(1, 6))) {
229       std::string NameAndAttributes;
230       std::string TypeStr;
231       CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
232       NameAndAttributes += '\0';
233       NameAndAttributes += TypeStr.length() + 3;
234       NameAndAttributes += TypeStr;
235       NameAndAttributes += '\0';
236       NameAndAttributes += PD->getNameAsString();
237       auto *ConstStr = CGM.GetAddrOfConstantCString(NameAndAttributes);
238       return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
239                                                   ConstStr, Zeros);
240     }
241     return MakeConstantString(PD->getNameAsString());
242   }
243   /// Push the property attributes into two structure fields.
244   void PushPropertyAttributes(std::vector<llvm::Constant*> &Fields,
245       ObjCPropertyDecl *property, bool isSynthesized=true, bool
246       isDynamic=true) {
247     int attrs = property->getPropertyAttributes();
248     // For read-only properties, clear the copy and retain flags
249     if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
250       attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
251       attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
252       attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
253       attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
254     }
255     // The first flags field has the same attribute values as clang uses internally
256     Fields.push_back(llvm::ConstantInt::get(Int8Ty, attrs & 0xff));
257     attrs >>= 8;
258     attrs <<= 2;
259     // For protocol properties, synthesized and dynamic have no meaning, so we
260     // reuse these flags to indicate that this is a protocol property (both set
261     // has no meaning, as a property can't be both synthesized and dynamic)
262     attrs |= isSynthesized ? (1<<0) : 0;
263     attrs |= isDynamic ? (1<<1) : 0;
264     // The second field is the next four fields left shifted by two, with the
265     // low bit set to indicate whether the field is synthesized or dynamic.
266     Fields.push_back(llvm::ConstantInt::get(Int8Ty, attrs & 0xff));
267     // Two padding fields
268     Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
269     Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
270   }
271   /// Ensures that the value has the required type, by inserting a bitcast if
272   /// required.  This function lets us avoid inserting bitcasts that are
273   /// redundant.
274   llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
275     if (V->getType() == Ty) return V;
276     return B.CreateBitCast(V, Ty);
277   }
278   // Some zeros used for GEPs in lots of places.
279   llvm::Constant *Zeros[2];
280   /// Null pointer value.  Mainly used as a terminator in various arrays.
281   llvm::Constant *NULLPtr;
282   /// LLVM context.
283   llvm::LLVMContext &VMContext;
284 private:
285   /// Placeholder for the class.  Lots of things refer to the class before we've
286   /// actually emitted it.  We use this alias as a placeholder, and then replace
287   /// it with a pointer to the class structure before finally emitting the
288   /// module.
289   llvm::GlobalAlias *ClassPtrAlias;
290   /// Placeholder for the metaclass.  Lots of things refer to the class before
291   /// we've / actually emitted it.  We use this alias as a placeholder, and then
292   /// replace / it with a pointer to the metaclass structure before finally
293   /// emitting the / module.
294   llvm::GlobalAlias *MetaClassPtrAlias;
295   /// All of the classes that have been generated for this compilation units.
296   std::vector<llvm::Constant*> Classes;
297   /// All of the categories that have been generated for this compilation units.
298   std::vector<llvm::Constant*> Categories;
299   /// All of the Objective-C constant strings that have been generated for this
300   /// compilation units.
301   std::vector<llvm::Constant*> ConstantStrings;
302   /// Map from string values to Objective-C constant strings in the output.
303   /// Used to prevent emitting Objective-C strings more than once.  This should
304   /// not be required at all - CodeGenModule should manage this list.
305   llvm::StringMap<llvm::Constant*> ObjCStrings;
306   /// All of the protocols that have been declared.
307   llvm::StringMap<llvm::Constant*> ExistingProtocols;
308   /// For each variant of a selector, we store the type encoding and a
309   /// placeholder value.  For an untyped selector, the type will be the empty
310   /// string.  Selector references are all done via the module's selector table,
311   /// so we create an alias as a placeholder and then replace it with the real
312   /// value later.
313   typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
314   /// Type of the selector map.  This is roughly equivalent to the structure
315   /// used in the GNUstep runtime, which maintains a list of all of the valid
316   /// types for a selector in a table.
317   typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
318     SelectorMap;
319   /// A map from selectors to selector types.  This allows us to emit all
320   /// selectors of the same name and type together.
321   SelectorMap SelectorTable;
322 
323   /// Selectors related to memory management.  When compiling in GC mode, we
324   /// omit these.
325   Selector RetainSel, ReleaseSel, AutoreleaseSel;
326   /// Runtime functions used for memory management in GC mode.  Note that clang
327   /// supports code generation for calling these functions, but neither GNU
328   /// runtime actually supports this API properly yet.
329   LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
330     WeakAssignFn, GlobalAssignFn;
331 
332   typedef std::pair<std::string, std::string> ClassAliasPair;
333   /// All classes that have aliases set for them.
334   std::vector<ClassAliasPair> ClassAliases;
335 
336 protected:
337   /// Function used for throwing Objective-C exceptions.
338   LazyRuntimeFunction ExceptionThrowFn;
339   /// Function used for rethrowing exceptions, used at the end of \@finally or
340   /// \@synchronize blocks.
341   LazyRuntimeFunction ExceptionReThrowFn;
342   /// Function called when entering a catch function.  This is required for
343   /// differentiating Objective-C exceptions and foreign exceptions.
344   LazyRuntimeFunction EnterCatchFn;
345   /// Function called when exiting from a catch block.  Used to do exception
346   /// cleanup.
347   LazyRuntimeFunction ExitCatchFn;
348   /// Function called when entering an \@synchronize block.  Acquires the lock.
349   LazyRuntimeFunction SyncEnterFn;
350   /// Function called when exiting an \@synchronize block.  Releases the lock.
351   LazyRuntimeFunction SyncExitFn;
352 
353 private:
354 
355   /// Function called if fast enumeration detects that the collection is
356   /// modified during the update.
357   LazyRuntimeFunction EnumerationMutationFn;
358   /// Function for implementing synthesized property getters that return an
359   /// object.
360   LazyRuntimeFunction GetPropertyFn;
361   /// Function for implementing synthesized property setters that return an
362   /// object.
363   LazyRuntimeFunction SetPropertyFn;
364   /// Function used for non-object declared property getters.
365   LazyRuntimeFunction GetStructPropertyFn;
366   /// Function used for non-object declared property setters.
367   LazyRuntimeFunction SetStructPropertyFn;
368 
369   /// The version of the runtime that this class targets.  Must match the
370   /// version in the runtime.
371   int RuntimeVersion;
372   /// The version of the protocol class.  Used to differentiate between ObjC1
373   /// and ObjC2 protocols.  Objective-C 1 protocols can not contain optional
374   /// components and can not contain declared properties.  We always emit
375   /// Objective-C 2 property structures, but we have to pretend that they're
376   /// Objective-C 1 property structures when targeting the GCC runtime or it
377   /// will abort.
378   const int ProtocolVersion;
379 private:
380   /// Generates an instance variable list structure.  This is a structure
381   /// containing a size and an array of structures containing instance variable
382   /// metadata.  This is used purely for introspection in the fragile ABI.  In
383   /// the non-fragile ABI, it's used for instance variable fixup.
384   llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
385                                    ArrayRef<llvm::Constant *> IvarTypes,
386                                    ArrayRef<llvm::Constant *> IvarOffsets);
387   /// Generates a method list structure.  This is a structure containing a size
388   /// and an array of structures containing method metadata.
389   ///
390   /// This structure is used by both classes and categories, and contains a next
391   /// pointer allowing them to be chained together in a linked list.
392   llvm::Constant *GenerateMethodList(StringRef ClassName,
393       StringRef CategoryName,
394       ArrayRef<Selector> MethodSels,
395       ArrayRef<llvm::Constant *> MethodTypes,
396       bool isClassMethodList);
397   /// Emits an empty protocol.  This is used for \@protocol() where no protocol
398   /// is found.  The runtime will (hopefully) fix up the pointer to refer to the
399   /// real protocol.
400   llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
401   /// Generates a list of property metadata structures.  This follows the same
402   /// pattern as method and instance variable metadata lists.
403   llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
404         SmallVectorImpl<Selector> &InstanceMethodSels,
405         SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
406   /// Generates a list of referenced protocols.  Classes, categories, and
407   /// protocols all use this structure.
408   llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
409   /// To ensure that all protocols are seen by the runtime, we add a category on
410   /// a class defined in the runtime, declaring no methods, but adopting the
411   /// protocols.  This is a horribly ugly hack, but it allows us to collect all
412   /// of the protocols without changing the ABI.
413   void GenerateProtocolHolderCategory();
414   /// Generates a class structure.
415   llvm::Constant *GenerateClassStructure(
416       llvm::Constant *MetaClass,
417       llvm::Constant *SuperClass,
418       unsigned info,
419       const char *Name,
420       llvm::Constant *Version,
421       llvm::Constant *InstanceSize,
422       llvm::Constant *IVars,
423       llvm::Constant *Methods,
424       llvm::Constant *Protocols,
425       llvm::Constant *IvarOffsets,
426       llvm::Constant *Properties,
427       llvm::Constant *StrongIvarBitmap,
428       llvm::Constant *WeakIvarBitmap,
429       bool isMeta=false);
430   /// Generates a method list.  This is used by protocols to define the required
431   /// and optional methods.
432   llvm::Constant *GenerateProtocolMethodList(
433       ArrayRef<llvm::Constant *> MethodNames,
434       ArrayRef<llvm::Constant *> MethodTypes);
435   /// Returns a selector with the specified type encoding.  An empty string is
436   /// used to return an untyped selector (with the types field set to NULL).
437   llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
438     const std::string &TypeEncoding, bool lval);
439   /// Returns the variable used to store the offset of an instance variable.
440   llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
441       const ObjCIvarDecl *Ivar);
442   /// Emits a reference to a class.  This allows the linker to object if there
443   /// is no class of the matching name.
444 protected:
445   void EmitClassRef(const std::string &className);
446   /// Emits a pointer to the named class
447   virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
448                                      const std::string &Name, bool isWeak);
449   /// Looks up the method for sending a message to the specified object.  This
450   /// mechanism differs between the GCC and GNU runtimes, so this method must be
451   /// overridden in subclasses.
452   virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
453                                  llvm::Value *&Receiver,
454                                  llvm::Value *cmd,
455                                  llvm::MDNode *node,
456                                  MessageSendInfo &MSI) = 0;
457   /// Looks up the method for sending a message to a superclass.  This
458   /// mechanism differs between the GCC and GNU runtimes, so this method must
459   /// be overridden in subclasses.
460   virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
461                                       llvm::Value *ObjCSuper,
462                                       llvm::Value *cmd,
463                                       MessageSendInfo &MSI) = 0;
464   /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
465   /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
466   /// bits set to their values, LSB first, while larger ones are stored in a
467   /// structure of this / form:
468   ///
469   /// struct { int32_t length; int32_t values[length]; };
470   ///
471   /// The values in the array are stored in host-endian format, with the least
472   /// significant bit being assumed to come first in the bitfield.  Therefore,
473   /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
474   /// while a bitfield / with the 63rd bit set will be 1<<64.
475   llvm::Constant *MakeBitField(ArrayRef<bool> bits);
476 public:
477   CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
478       unsigned protocolClassVersion);
479 
480   llvm::Constant *GenerateConstantString(const StringLiteral *) override;
481 
482   RValue
483   GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
484                       QualType ResultType, Selector Sel,
485                       llvm::Value *Receiver, const CallArgList &CallArgs,
486                       const ObjCInterfaceDecl *Class,
487                       const ObjCMethodDecl *Method) override;
488   RValue
489   GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
490                            QualType ResultType, Selector Sel,
491                            const ObjCInterfaceDecl *Class,
492                            bool isCategoryImpl, llvm::Value *Receiver,
493                            bool IsClassMessage, const CallArgList &CallArgs,
494                            const ObjCMethodDecl *Method) override;
495   llvm::Value *GetClass(CodeGenFunction &CGF,
496                         const ObjCInterfaceDecl *OID) override;
497   llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
498                            bool lval = false) override;
499   llvm::Value *GetSelector(CodeGenFunction &CGF,
500                            const ObjCMethodDecl *Method) override;
501   llvm::Constant *GetEHType(QualType T) override;
502 
503   llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
504                                  const ObjCContainerDecl *CD) override;
505   void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
506   void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
507   void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
508   llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
509                                    const ObjCProtocolDecl *PD) override;
510   void GenerateProtocol(const ObjCProtocolDecl *PD) override;
511   llvm::Function *ModuleInitFunction() override;
512   llvm::Constant *GetPropertyGetFunction() override;
513   llvm::Constant *GetPropertySetFunction() override;
514   llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
515                                                   bool copy) override;
516   llvm::Constant *GetSetStructFunction() override;
517   llvm::Constant *GetGetStructFunction() override;
518   llvm::Constant *GetCppAtomicObjectGetFunction() override;
519   llvm::Constant *GetCppAtomicObjectSetFunction() override;
520   llvm::Constant *EnumerationMutationFunction() override;
521 
522   void EmitTryStmt(CodeGenFunction &CGF,
523                    const ObjCAtTryStmt &S) override;
524   void EmitSynchronizedStmt(CodeGenFunction &CGF,
525                             const ObjCAtSynchronizedStmt &S) override;
526   void EmitThrowStmt(CodeGenFunction &CGF,
527                      const ObjCAtThrowStmt &S,
528                      bool ClearInsertionPoint=true) override;
529   llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
530                                  llvm::Value *AddrWeakObj) override;
531   void EmitObjCWeakAssign(CodeGenFunction &CGF,
532                           llvm::Value *src, llvm::Value *dst) override;
533   void EmitObjCGlobalAssign(CodeGenFunction &CGF,
534                             llvm::Value *src, llvm::Value *dest,
535                             bool threadlocal=false) override;
536   void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
537                           llvm::Value *dest, llvm::Value *ivarOffset) override;
538   void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
539                                 llvm::Value *src, llvm::Value *dest) override;
540   void EmitGCMemmoveCollectable(CodeGenFunction &CGF, llvm::Value *DestPtr,
541                                 llvm::Value *SrcPtr,
542                                 llvm::Value *Size) override;
543   LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
544                               llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
545                               unsigned CVRQualifiers) override;
546   llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
547                               const ObjCInterfaceDecl *Interface,
548                               const ObjCIvarDecl *Ivar) override;
549   llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
550   llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
551                                      const CGBlockInfo &blockInfo) override {
552     return NULLPtr;
553   }
554   llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
555                                      const CGBlockInfo &blockInfo) override {
556     return NULLPtr;
557   }
558 
559   llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
560     return NULLPtr;
561   }
562 
563   llvm::GlobalVariable *GetClassGlobal(const std::string &Name,
564                                        bool Weak = false) override {
565     return nullptr;
566   }
567 };
568 /// Class representing the legacy GCC Objective-C ABI.  This is the default when
569 /// -fobjc-nonfragile-abi is not specified.
570 ///
571 /// The GCC ABI target actually generates code that is approximately compatible
572 /// with the new GNUstep runtime ABI, but refrains from using any features that
573 /// would not work with the GCC runtime.  For example, clang always generates
574 /// the extended form of the class structure, and the extra fields are simply
575 /// ignored by GCC libobjc.
576 class CGObjCGCC : public CGObjCGNU {
577   /// The GCC ABI message lookup function.  Returns an IMP pointing to the
578   /// method implementation for this message.
579   LazyRuntimeFunction MsgLookupFn;
580   /// The GCC ABI superclass message lookup function.  Takes a pointer to a
581   /// structure describing the receiver and the class, and a selector as
582   /// arguments.  Returns the IMP for the corresponding method.
583   LazyRuntimeFunction MsgLookupSuperFn;
584 protected:
585   llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
586                          llvm::Value *cmd, llvm::MDNode *node,
587                          MessageSendInfo &MSI) override {
588     CGBuilderTy &Builder = CGF.Builder;
589     llvm::Value *args[] = {
590             EnforceType(Builder, Receiver, IdTy),
591             EnforceType(Builder, cmd, SelectorTy) };
592     llvm::CallSite imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
593     imp->setMetadata(msgSendMDKind, node);
594     return imp.getInstruction();
595   }
596   llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, llvm::Value *ObjCSuper,
597                               llvm::Value *cmd, MessageSendInfo &MSI) override {
598       CGBuilderTy &Builder = CGF.Builder;
599       llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
600           PtrToObjCSuperTy), cmd};
601       return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
602     }
603   public:
604     CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
605       // IMP objc_msg_lookup(id, SEL);
606       MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy,
607                        nullptr);
608       // IMP objc_msg_lookup_super(struct objc_super*, SEL);
609       MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
610               PtrToObjCSuperTy, SelectorTy, nullptr);
611     }
612 };
613 /// Class used when targeting the new GNUstep runtime ABI.
614 class CGObjCGNUstep : public CGObjCGNU {
615     /// The slot lookup function.  Returns a pointer to a cacheable structure
616     /// that contains (among other things) the IMP.
617     LazyRuntimeFunction SlotLookupFn;
618     /// The GNUstep ABI superclass message lookup function.  Takes a pointer to
619     /// a structure describing the receiver and the class, and a selector as
620     /// arguments.  Returns the slot for the corresponding method.  Superclass
621     /// message lookup rarely changes, so this is a good caching opportunity.
622     LazyRuntimeFunction SlotLookupSuperFn;
623     /// Specialised function for setting atomic retain properties
624     LazyRuntimeFunction SetPropertyAtomic;
625     /// Specialised function for setting atomic copy properties
626     LazyRuntimeFunction SetPropertyAtomicCopy;
627     /// Specialised function for setting nonatomic retain properties
628     LazyRuntimeFunction SetPropertyNonAtomic;
629     /// Specialised function for setting nonatomic copy properties
630     LazyRuntimeFunction SetPropertyNonAtomicCopy;
631     /// Function to perform atomic copies of C++ objects with nontrivial copy
632     /// constructors from Objective-C ivars.
633     LazyRuntimeFunction CxxAtomicObjectGetFn;
634     /// Function to perform atomic copies of C++ objects with nontrivial copy
635     /// constructors to Objective-C ivars.
636     LazyRuntimeFunction CxxAtomicObjectSetFn;
637     /// Type of an slot structure pointer.  This is returned by the various
638     /// lookup functions.
639     llvm::Type *SlotTy;
640   public:
641     llvm::Constant *GetEHType(QualType T) override;
642   protected:
643     llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
644                            llvm::Value *cmd, llvm::MDNode *node,
645                            MessageSendInfo &MSI) override {
646       CGBuilderTy &Builder = CGF.Builder;
647       llvm::Function *LookupFn = SlotLookupFn;
648 
649       // Store the receiver on the stack so that we can reload it later
650       llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
651       Builder.CreateStore(Receiver, ReceiverPtr);
652 
653       llvm::Value *self;
654 
655       if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
656         self = CGF.LoadObjCSelf();
657       } else {
658         self = llvm::ConstantPointerNull::get(IdTy);
659       }
660 
661       // The lookup function is guaranteed not to capture the receiver pointer.
662       LookupFn->setDoesNotCapture(1);
663 
664       llvm::Value *args[] = {
665               EnforceType(Builder, ReceiverPtr, PtrToIdTy),
666               EnforceType(Builder, cmd, SelectorTy),
667               EnforceType(Builder, self, IdTy) };
668       llvm::CallSite slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
669       slot.setOnlyReadsMemory();
670       slot->setMetadata(msgSendMDKind, node);
671 
672       // Load the imp from the slot
673       llvm::Value *imp = Builder.CreateLoad(
674           Builder.CreateStructGEP(nullptr, slot.getInstruction(), 4));
675 
676       // The lookup function may have changed the receiver, so make sure we use
677       // the new one.
678       Receiver = Builder.CreateLoad(ReceiverPtr, true);
679       return imp;
680     }
681     llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, llvm::Value *ObjCSuper,
682                                 llvm::Value *cmd,
683                                 MessageSendInfo &MSI) override {
684       CGBuilderTy &Builder = CGF.Builder;
685       llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
686 
687       llvm::CallInst *slot =
688         CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
689       slot->setOnlyReadsMemory();
690 
691       return Builder.CreateLoad(Builder.CreateStructGEP(nullptr, slot, 4));
692     }
693   public:
694     CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
695       const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
696 
697       llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
698           PtrTy, PtrTy, IntTy, IMPTy, nullptr);
699       SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
700       // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
701       SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
702           SelectorTy, IdTy, nullptr);
703       // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
704       SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
705               PtrToObjCSuperTy, SelectorTy, nullptr);
706       // If we're in ObjC++ mode, then we want to make
707       if (CGM.getLangOpts().CPlusPlus) {
708         llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
709         // void *__cxa_begin_catch(void *e)
710         EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, nullptr);
711         // void __cxa_end_catch(void)
712         ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, nullptr);
713         // void _Unwind_Resume_or_Rethrow(void*)
714         ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
715             PtrTy, nullptr);
716       } else if (R.getVersion() >= VersionTuple(1, 7)) {
717         llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
718         // id objc_begin_catch(void *e)
719         EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy, nullptr);
720         // void objc_end_catch(void)
721         ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy, nullptr);
722         // void _Unwind_Resume_or_Rethrow(void*)
723         ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy,
724             PtrTy, nullptr);
725       }
726       llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
727       SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
728           SelectorTy, IdTy, PtrDiffTy, nullptr);
729       SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
730           IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
731       SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
732           IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
733       SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
734           VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
735       // void objc_setCppObjectAtomic(void *dest, const void *src, void
736       // *helper);
737       CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
738           PtrTy, PtrTy, nullptr);
739       // void objc_getCppObjectAtomic(void *dest, const void *src, void
740       // *helper);
741       CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
742           PtrTy, PtrTy, nullptr);
743     }
744     llvm::Constant *GetCppAtomicObjectGetFunction() override {
745       // The optimised functions were added in version 1.7 of the GNUstep
746       // runtime.
747       assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
748           VersionTuple(1, 7));
749       return CxxAtomicObjectGetFn;
750     }
751     llvm::Constant *GetCppAtomicObjectSetFunction() override {
752       // The optimised functions were added in version 1.7 of the GNUstep
753       // runtime.
754       assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
755           VersionTuple(1, 7));
756       return CxxAtomicObjectSetFn;
757     }
758     llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
759                                                     bool copy) override {
760       // The optimised property functions omit the GC check, and so are not
761       // safe to use in GC mode.  The standard functions are fast in GC mode,
762       // so there is less advantage in using them.
763       assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
764       // The optimised functions were added in version 1.7 of the GNUstep
765       // runtime.
766       assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
767           VersionTuple(1, 7));
768 
769       if (atomic) {
770         if (copy) return SetPropertyAtomicCopy;
771         return SetPropertyAtomic;
772       }
773 
774       return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
775     }
776 };
777 
778 /// Support for the ObjFW runtime.
779 class CGObjCObjFW: public CGObjCGNU {
780 protected:
781   /// The GCC ABI message lookup function.  Returns an IMP pointing to the
782   /// method implementation for this message.
783   LazyRuntimeFunction MsgLookupFn;
784   /// stret lookup function.  While this does not seem to make sense at the
785   /// first look, this is required to call the correct forwarding function.
786   LazyRuntimeFunction MsgLookupFnSRet;
787   /// The GCC ABI superclass message lookup function.  Takes a pointer to a
788   /// structure describing the receiver and the class, and a selector as
789   /// arguments.  Returns the IMP for the corresponding method.
790   LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
791 
792   llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
793                          llvm::Value *cmd, llvm::MDNode *node,
794                          MessageSendInfo &MSI) override {
795     CGBuilderTy &Builder = CGF.Builder;
796     llvm::Value *args[] = {
797             EnforceType(Builder, Receiver, IdTy),
798             EnforceType(Builder, cmd, SelectorTy) };
799 
800     llvm::CallSite imp;
801     if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
802       imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
803     else
804       imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
805 
806     imp->setMetadata(msgSendMDKind, node);
807     return imp.getInstruction();
808   }
809 
810   llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, llvm::Value *ObjCSuper,
811                               llvm::Value *cmd, MessageSendInfo &MSI) override {
812       CGBuilderTy &Builder = CGF.Builder;
813       llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
814           PtrToObjCSuperTy), cmd};
815 
816       if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
817         return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
818       else
819         return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
820     }
821 
822   llvm::Value *GetClassNamed(CodeGenFunction &CGF,
823                              const std::string &Name, bool isWeak) override {
824     if (isWeak)
825       return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
826 
827     EmitClassRef(Name);
828 
829     std::string SymbolName = "_OBJC_CLASS_" + Name;
830 
831     llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
832 
833     if (!ClassSymbol)
834       ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
835                                              llvm::GlobalValue::ExternalLinkage,
836                                              nullptr, SymbolName);
837 
838     return ClassSymbol;
839   }
840 
841 public:
842   CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
843     // IMP objc_msg_lookup(id, SEL);
844     MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, nullptr);
845     MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
846                          SelectorTy, nullptr);
847     // IMP objc_msg_lookup_super(struct objc_super*, SEL);
848     MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
849                           PtrToObjCSuperTy, SelectorTy, nullptr);
850     MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
851                               PtrToObjCSuperTy, SelectorTy, nullptr);
852   }
853 };
854 } // end anonymous namespace
855 
856 
857 /// Emits a reference to a dummy variable which is emitted with each class.
858 /// This ensures that a linker error will be generated when trying to link
859 /// together modules where a referenced class is not defined.
860 void CGObjCGNU::EmitClassRef(const std::string &className) {
861   std::string symbolRef = "__objc_class_ref_" + className;
862   // Don't emit two copies of the same symbol
863   if (TheModule.getGlobalVariable(symbolRef))
864     return;
865   std::string symbolName = "__objc_class_name_" + className;
866   llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
867   if (!ClassSymbol) {
868     ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
869                                            llvm::GlobalValue::ExternalLinkage,
870                                            nullptr, symbolName);
871   }
872   new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
873     llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
874 }
875 
876 static std::string SymbolNameForMethod( StringRef ClassName,
877      StringRef CategoryName, const Selector MethodName,
878     bool isClassMethod) {
879   std::string MethodNameColonStripped = MethodName.getAsString();
880   std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
881       ':', '_');
882   return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
883     CategoryName + "_" + MethodNameColonStripped).str();
884 }
885 
886 CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
887                      unsigned protocolClassVersion)
888   : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
889     VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
890     MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
891     ProtocolVersion(protocolClassVersion) {
892 
893   msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
894 
895   CodeGenTypes &Types = CGM.getTypes();
896   IntTy = cast<llvm::IntegerType>(
897       Types.ConvertType(CGM.getContext().IntTy));
898   LongTy = cast<llvm::IntegerType>(
899       Types.ConvertType(CGM.getContext().LongTy));
900   SizeTy = cast<llvm::IntegerType>(
901       Types.ConvertType(CGM.getContext().getSizeType()));
902   PtrDiffTy = cast<llvm::IntegerType>(
903       Types.ConvertType(CGM.getContext().getPointerDiffType()));
904   BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
905 
906   Int8Ty = llvm::Type::getInt8Ty(VMContext);
907   // C string type.  Used in lots of places.
908   PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
909 
910   Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
911   Zeros[1] = Zeros[0];
912   NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
913   // Get the selector Type.
914   QualType selTy = CGM.getContext().getObjCSelType();
915   if (QualType() == selTy) {
916     SelectorTy = PtrToInt8Ty;
917   } else {
918     SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
919   }
920 
921   PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
922   PtrTy = PtrToInt8Ty;
923 
924   Int32Ty = llvm::Type::getInt32Ty(VMContext);
925   Int64Ty = llvm::Type::getInt64Ty(VMContext);
926 
927   IntPtrTy =
928       CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
929 
930   // Object type
931   QualType UnqualIdTy = CGM.getContext().getObjCIdType();
932   ASTIdTy = CanQualType();
933   if (UnqualIdTy != QualType()) {
934     ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
935     IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
936   } else {
937     IdTy = PtrToInt8Ty;
938   }
939   PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
940 
941   ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, nullptr);
942   PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
943 
944   llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
945 
946   // void objc_exception_throw(id);
947   ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, nullptr);
948   ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, nullptr);
949   // int objc_sync_enter(id);
950   SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, nullptr);
951   // int objc_sync_exit(id);
952   SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, nullptr);
953 
954   // void objc_enumerationMutation (id)
955   EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
956       IdTy, nullptr);
957 
958   // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
959   GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
960       PtrDiffTy, BoolTy, nullptr);
961   // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
962   SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
963       PtrDiffTy, IdTy, BoolTy, BoolTy, nullptr);
964   // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
965   GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
966       PtrDiffTy, BoolTy, BoolTy, nullptr);
967   // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
968   SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
969       PtrDiffTy, BoolTy, BoolTy, nullptr);
970 
971   // IMP type
972   llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
973   IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
974               true));
975 
976   const LangOptions &Opts = CGM.getLangOpts();
977   if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
978     RuntimeVersion = 10;
979 
980   // Don't bother initialising the GC stuff unless we're compiling in GC mode
981   if (Opts.getGC() != LangOptions::NonGC) {
982     // This is a bit of an hack.  We should sort this out by having a proper
983     // CGObjCGNUstep subclass for GC, but we may want to really support the old
984     // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
985     // Get selectors needed in GC mode
986     RetainSel = GetNullarySelector("retain", CGM.getContext());
987     ReleaseSel = GetNullarySelector("release", CGM.getContext());
988     AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
989 
990     // Get functions needed in GC mode
991 
992     // id objc_assign_ivar(id, id, ptrdiff_t);
993     IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
994         nullptr);
995     // id objc_assign_strongCast (id, id*)
996     StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
997         PtrToIdTy, nullptr);
998     // id objc_assign_global(id, id*);
999     GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
1000         nullptr);
1001     // id objc_assign_weak(id, id*);
1002     WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, nullptr);
1003     // id objc_read_weak(id*);
1004     WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, nullptr);
1005     // void *objc_memmove_collectable(void*, void *, size_t);
1006     MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
1007         SizeTy, nullptr);
1008   }
1009 }
1010 
1011 llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
1012                                       const std::string &Name,
1013                                       bool isWeak) {
1014   llvm::GlobalVariable *ClassNameGV = CGM.GetAddrOfConstantCString(Name);
1015   // With the incompatible ABI, this will need to be replaced with a direct
1016   // reference to the class symbol.  For the compatible nonfragile ABI we are
1017   // still performing this lookup at run time but emitting the symbol for the
1018   // class externally so that we can make the switch later.
1019   //
1020   // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
1021   // with memoized versions or with static references if it's safe to do so.
1022   if (!isWeak)
1023     EmitClassRef(Name);
1024   llvm::Value *ClassName =
1025       CGF.Builder.CreateStructGEP(ClassNameGV->getValueType(), ClassNameGV, 0);
1026 
1027   llvm::Constant *ClassLookupFn =
1028     CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
1029                               "objc_lookup_class");
1030   return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
1031 }
1032 
1033 // This has to perform the lookup every time, since posing and related
1034 // techniques can modify the name -> class mapping.
1035 llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
1036                                  const ObjCInterfaceDecl *OID) {
1037   return GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
1038 }
1039 llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
1040   return GetClassNamed(CGF, "NSAutoreleasePool", false);
1041 }
1042 
1043 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
1044     const std::string &TypeEncoding, bool lval) {
1045 
1046   SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
1047   llvm::GlobalAlias *SelValue = nullptr;
1048 
1049   for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
1050       e = Types.end() ; i!=e ; i++) {
1051     if (i->first == TypeEncoding) {
1052       SelValue = i->second;
1053       break;
1054     }
1055   }
1056   if (!SelValue) {
1057     SelValue = llvm::GlobalAlias::create(
1058         SelectorTy, llvm::GlobalValue::PrivateLinkage,
1059         ".objc_selector_" + Sel.getAsString(), &TheModule);
1060     Types.emplace_back(TypeEncoding, SelValue);
1061   }
1062 
1063   if (lval) {
1064     llvm::Value *tmp = CGF.CreateTempAlloca(SelValue->getType());
1065     CGF.Builder.CreateStore(SelValue, tmp);
1066     return tmp;
1067   }
1068   return SelValue;
1069 }
1070 
1071 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
1072                                     bool lval) {
1073   return GetSelector(CGF, Sel, std::string(), lval);
1074 }
1075 
1076 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
1077                                     const ObjCMethodDecl *Method) {
1078   std::string SelTypes;
1079   CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
1080   return GetSelector(CGF, Method->getSelector(), SelTypes, false);
1081 }
1082 
1083 llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
1084   if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
1085     // With the old ABI, there was only one kind of catchall, which broke
1086     // foreign exceptions.  With the new ABI, we use __objc_id_typeinfo as
1087     // a pointer indicating object catchalls, and NULL to indicate real
1088     // catchalls
1089     if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1090       return MakeConstantString("@id");
1091     } else {
1092       return nullptr;
1093     }
1094   }
1095 
1096   // All other types should be Objective-C interface pointer types.
1097   const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
1098   assert(OPT && "Invalid @catch type.");
1099   const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
1100   assert(IDecl && "Invalid @catch type.");
1101   return MakeConstantString(IDecl->getIdentifier()->getName());
1102 }
1103 
1104 llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
1105   if (!CGM.getLangOpts().CPlusPlus)
1106     return CGObjCGNU::GetEHType(T);
1107 
1108   // For Objective-C++, we want to provide the ability to catch both C++ and
1109   // Objective-C objects in the same function.
1110 
1111   // There's a particular fixed type info for 'id'.
1112   if (T->isObjCIdType() ||
1113       T->isObjCQualifiedIdType()) {
1114     llvm::Constant *IDEHType =
1115       CGM.getModule().getGlobalVariable("__objc_id_type_info");
1116     if (!IDEHType)
1117       IDEHType =
1118         new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
1119                                  false,
1120                                  llvm::GlobalValue::ExternalLinkage,
1121                                  nullptr, "__objc_id_type_info");
1122     return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
1123   }
1124 
1125   const ObjCObjectPointerType *PT =
1126     T->getAs<ObjCObjectPointerType>();
1127   assert(PT && "Invalid @catch type.");
1128   const ObjCInterfaceType *IT = PT->getInterfaceType();
1129   assert(IT && "Invalid @catch type.");
1130   std::string className = IT->getDecl()->getIdentifier()->getName();
1131 
1132   std::string typeinfoName = "__objc_eh_typeinfo_" + className;
1133 
1134   // Return the existing typeinfo if it exists
1135   llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
1136   if (typeinfo)
1137     return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
1138 
1139   // Otherwise create it.
1140 
1141   // vtable for gnustep::libobjc::__objc_class_type_info
1142   // It's quite ugly hard-coding this.  Ideally we'd generate it using the host
1143   // platform's name mangling.
1144   const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
1145   auto *Vtable = TheModule.getGlobalVariable(vtableName);
1146   if (!Vtable) {
1147     Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
1148                                       llvm::GlobalValue::ExternalLinkage,
1149                                       nullptr, vtableName);
1150   }
1151   llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
1152   auto *BVtable = llvm::ConstantExpr::getBitCast(
1153       llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
1154       PtrToInt8Ty);
1155 
1156   llvm::Constant *typeName =
1157     ExportUniqueString(className, "__objc_eh_typename_");
1158 
1159   std::vector<llvm::Constant*> fields;
1160   fields.push_back(BVtable);
1161   fields.push_back(typeName);
1162   llvm::Constant *TI =
1163       MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
1164               nullptr), fields, "__objc_eh_typeinfo_" + className,
1165           llvm::GlobalValue::LinkOnceODRLinkage);
1166   return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
1167 }
1168 
1169 /// Generate an NSConstantString object.
1170 llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
1171 
1172   std::string Str = SL->getString().str();
1173 
1174   // Look for an existing one
1175   llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
1176   if (old != ObjCStrings.end())
1177     return old->getValue();
1178 
1179   StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
1180 
1181   if (StringClass.empty()) StringClass = "NXConstantString";
1182 
1183   std::string Sym = "_OBJC_CLASS_";
1184   Sym += StringClass;
1185 
1186   llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1187 
1188   if (!isa)
1189     isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1190             llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
1191   else if (isa->getType() != PtrToIdTy)
1192     isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1193 
1194   std::vector<llvm::Constant*> Ivars;
1195   Ivars.push_back(isa);
1196   Ivars.push_back(MakeConstantString(Str));
1197   Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
1198   llvm::Constant *ObjCStr = MakeGlobal(
1199     llvm::StructType::get(PtrToIdTy, PtrToInt8Ty, IntTy, nullptr),
1200     Ivars, ".objc_str");
1201   ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
1202   ObjCStrings[Str] = ObjCStr;
1203   ConstantStrings.push_back(ObjCStr);
1204   return ObjCStr;
1205 }
1206 
1207 ///Generates a message send where the super is the receiver.  This is a message
1208 ///send to self with special delivery semantics indicating which class's method
1209 ///should be called.
1210 RValue
1211 CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
1212                                     ReturnValueSlot Return,
1213                                     QualType ResultType,
1214                                     Selector Sel,
1215                                     const ObjCInterfaceDecl *Class,
1216                                     bool isCategoryImpl,
1217                                     llvm::Value *Receiver,
1218                                     bool IsClassMessage,
1219                                     const CallArgList &CallArgs,
1220                                     const ObjCMethodDecl *Method) {
1221   CGBuilderTy &Builder = CGF.Builder;
1222   if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
1223     if (Sel == RetainSel || Sel == AutoreleaseSel) {
1224       return RValue::get(EnforceType(Builder, Receiver,
1225                   CGM.getTypes().ConvertType(ResultType)));
1226     }
1227     if (Sel == ReleaseSel) {
1228       return RValue::get(nullptr);
1229     }
1230   }
1231 
1232   llvm::Value *cmd = GetSelector(CGF, Sel);
1233 
1234 
1235   CallArgList ActualArgs;
1236 
1237   ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
1238   ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
1239   ActualArgs.addFrom(CallArgs);
1240 
1241   MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1242 
1243   llvm::Value *ReceiverClass = nullptr;
1244   if (isCategoryImpl) {
1245     llvm::Constant *classLookupFunction = nullptr;
1246     if (IsClassMessage)  {
1247       classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1248             IdTy, PtrTy, true), "objc_get_meta_class");
1249     } else {
1250       classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1251             IdTy, PtrTy, true), "objc_get_class");
1252     }
1253     ReceiverClass = Builder.CreateCall(classLookupFunction,
1254         MakeConstantString(Class->getNameAsString()));
1255   } else {
1256     // Set up global aliases for the metaclass or class pointer if they do not
1257     // already exist.  These will are forward-references which will be set to
1258     // pointers to the class and metaclass structure created for the runtime
1259     // load function.  To send a message to super, we look up the value of the
1260     // super_class pointer from either the class or metaclass structure.
1261     if (IsClassMessage)  {
1262       if (!MetaClassPtrAlias) {
1263         MetaClassPtrAlias = llvm::GlobalAlias::create(
1264             IdTy, llvm::GlobalValue::InternalLinkage,
1265             ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
1266       }
1267       ReceiverClass = MetaClassPtrAlias;
1268     } else {
1269       if (!ClassPtrAlias) {
1270         ClassPtrAlias = llvm::GlobalAlias::create(
1271             IdTy, llvm::GlobalValue::InternalLinkage,
1272             ".objc_class_ref" + Class->getNameAsString(), &TheModule);
1273       }
1274       ReceiverClass = ClassPtrAlias;
1275     }
1276   }
1277   // Cast the pointer to a simplified version of the class structure
1278   llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy, nullptr);
1279   ReceiverClass = Builder.CreateBitCast(ReceiverClass,
1280                                         llvm::PointerType::getUnqual(CastTy));
1281   // Get the superclass pointer
1282   ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
1283   // Load the superclass pointer
1284   ReceiverClass = Builder.CreateLoad(ReceiverClass);
1285   // Construct the structure used to look up the IMP
1286   llvm::StructType *ObjCSuperTy = llvm::StructType::get(
1287       Receiver->getType(), IdTy, nullptr);
1288   llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
1289 
1290   Builder.CreateStore(Receiver,
1291                       Builder.CreateStructGEP(ObjCSuperTy, ObjCSuper, 0));
1292   Builder.CreateStore(ReceiverClass,
1293                       Builder.CreateStructGEP(ObjCSuperTy, ObjCSuper, 1));
1294 
1295   ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
1296 
1297   // Get the IMP
1298   llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
1299   imp = EnforceType(Builder, imp, MSI.MessengerType);
1300 
1301   llvm::Metadata *impMD[] = {
1302       llvm::MDString::get(VMContext, Sel.getAsString()),
1303       llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1304       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1305           llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
1306   llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
1307 
1308   llvm::Instruction *call;
1309   RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, nullptr,
1310                                &call);
1311   call->setMetadata(msgSendMDKind, node);
1312   return msgRet;
1313 }
1314 
1315 /// Generate code for a message send expression.
1316 RValue
1317 CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
1318                                ReturnValueSlot Return,
1319                                QualType ResultType,
1320                                Selector Sel,
1321                                llvm::Value *Receiver,
1322                                const CallArgList &CallArgs,
1323                                const ObjCInterfaceDecl *Class,
1324                                const ObjCMethodDecl *Method) {
1325   CGBuilderTy &Builder = CGF.Builder;
1326 
1327   // Strip out message sends to retain / release in GC mode
1328   if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
1329     if (Sel == RetainSel || Sel == AutoreleaseSel) {
1330       return RValue::get(EnforceType(Builder, Receiver,
1331                   CGM.getTypes().ConvertType(ResultType)));
1332     }
1333     if (Sel == ReleaseSel) {
1334       return RValue::get(nullptr);
1335     }
1336   }
1337 
1338   // If the return type is something that goes in an integer register, the
1339   // runtime will handle 0 returns.  For other cases, we fill in the 0 value
1340   // ourselves.
1341   //
1342   // The language spec says the result of this kind of message send is
1343   // undefined, but lots of people seem to have forgotten to read that
1344   // paragraph and insist on sending messages to nil that have structure
1345   // returns.  With GCC, this generates a random return value (whatever happens
1346   // to be on the stack / in those registers at the time) on most platforms,
1347   // and generates an illegal instruction trap on SPARC.  With LLVM it corrupts
1348   // the stack.
1349   bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1350       ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
1351 
1352   llvm::BasicBlock *startBB = nullptr;
1353   llvm::BasicBlock *messageBB = nullptr;
1354   llvm::BasicBlock *continueBB = nullptr;
1355 
1356   if (!isPointerSizedReturn) {
1357     startBB = Builder.GetInsertBlock();
1358     messageBB = CGF.createBasicBlock("msgSend");
1359     continueBB = CGF.createBasicBlock("continue");
1360 
1361     llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1362             llvm::Constant::getNullValue(Receiver->getType()));
1363     Builder.CreateCondBr(isNil, continueBB, messageBB);
1364     CGF.EmitBlock(messageBB);
1365   }
1366 
1367   IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
1368   llvm::Value *cmd;
1369   if (Method)
1370     cmd = GetSelector(CGF, Method);
1371   else
1372     cmd = GetSelector(CGF, Sel);
1373   cmd = EnforceType(Builder, cmd, SelectorTy);
1374   Receiver = EnforceType(Builder, Receiver, IdTy);
1375 
1376   llvm::Metadata *impMD[] = {
1377       llvm::MDString::get(VMContext, Sel.getAsString()),
1378       llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
1379       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1380           llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
1381   llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
1382 
1383   CallArgList ActualArgs;
1384   ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1385   ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
1386   ActualArgs.addFrom(CallArgs);
1387 
1388   MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1389 
1390   // Get the IMP to call
1391   llvm::Value *imp;
1392 
1393   // If we have non-legacy dispatch specified, we try using the objc_msgSend()
1394   // functions.  These are not supported on all platforms (or all runtimes on a
1395   // given platform), so we
1396   switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
1397     case CodeGenOptions::Legacy:
1398       imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
1399       break;
1400     case CodeGenOptions::Mixed:
1401     case CodeGenOptions::NonLegacy:
1402       if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1403         imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1404                                   "objc_msgSend_fpret");
1405       } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
1406         // The actual types here don't matter - we're going to bitcast the
1407         // function anyway
1408         imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1409                                   "objc_msgSend_stret");
1410       } else {
1411         imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1412                                   "objc_msgSend");
1413       }
1414   }
1415 
1416   // Reset the receiver in case the lookup modified it
1417   ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
1418 
1419   imp = EnforceType(Builder, imp, MSI.MessengerType);
1420 
1421   llvm::Instruction *call;
1422   RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, nullptr,
1423                                &call);
1424   call->setMetadata(msgSendMDKind, node);
1425 
1426 
1427   if (!isPointerSizedReturn) {
1428     messageBB = CGF.Builder.GetInsertBlock();
1429     CGF.Builder.CreateBr(continueBB);
1430     CGF.EmitBlock(continueBB);
1431     if (msgRet.isScalar()) {
1432       llvm::Value *v = msgRet.getScalarVal();
1433       llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
1434       phi->addIncoming(v, messageBB);
1435       phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1436       msgRet = RValue::get(phi);
1437     } else if (msgRet.isAggregate()) {
1438       llvm::Value *v = msgRet.getAggregateAddr();
1439       llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
1440       llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
1441       llvm::AllocaInst *NullVal =
1442           CGF.CreateTempAlloca(RetTy->getElementType(), "null");
1443       CGF.InitTempAlloca(NullVal,
1444           llvm::Constant::getNullValue(RetTy->getElementType()));
1445       phi->addIncoming(v, messageBB);
1446       phi->addIncoming(NullVal, startBB);
1447       msgRet = RValue::getAggregate(phi);
1448     } else /* isComplex() */ {
1449       std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
1450       llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
1451       phi->addIncoming(v.first, messageBB);
1452       phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1453           startBB);
1454       llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
1455       phi2->addIncoming(v.second, messageBB);
1456       phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1457           startBB);
1458       msgRet = RValue::getComplex(phi, phi2);
1459     }
1460   }
1461   return msgRet;
1462 }
1463 
1464 /// Generates a MethodList.  Used in construction of a objc_class and
1465 /// objc_category structures.
1466 llvm::Constant *CGObjCGNU::
1467 GenerateMethodList(StringRef ClassName,
1468                    StringRef CategoryName,
1469                    ArrayRef<Selector> MethodSels,
1470                    ArrayRef<llvm::Constant *> MethodTypes,
1471                    bool isClassMethodList) {
1472   if (MethodSels.empty())
1473     return NULLPtr;
1474   // Get the method structure type.
1475   llvm::StructType *ObjCMethodTy = llvm::StructType::get(
1476     PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1477     PtrToInt8Ty, // Method types
1478     IMPTy, //Method pointer
1479     nullptr);
1480   std::vector<llvm::Constant*> Methods;
1481   std::vector<llvm::Constant*> Elements;
1482   for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1483     Elements.clear();
1484     llvm::Constant *Method =
1485       TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
1486                                                 MethodSels[i],
1487                                                 isClassMethodList));
1488     assert(Method && "Can't generate metadata for method that doesn't exist");
1489     llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1490     Elements.push_back(C);
1491     Elements.push_back(MethodTypes[i]);
1492     Method = llvm::ConstantExpr::getBitCast(Method,
1493         IMPTy);
1494     Elements.push_back(Method);
1495     Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
1496   }
1497 
1498   // Array of method structures
1499   llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
1500                                                             Methods.size());
1501   llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
1502                                                          Methods);
1503 
1504   // Structure containing list pointer, array and array count
1505   llvm::StructType *ObjCMethodListTy = llvm::StructType::create(VMContext);
1506   llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
1507   ObjCMethodListTy->setBody(
1508       NextPtrTy,
1509       IntTy,
1510       ObjCMethodArrayTy,
1511       nullptr);
1512 
1513   Methods.clear();
1514   Methods.push_back(llvm::ConstantPointerNull::get(
1515         llvm::PointerType::getUnqual(ObjCMethodListTy)));
1516   Methods.push_back(llvm::ConstantInt::get(Int32Ty, MethodTypes.size()));
1517   Methods.push_back(MethodArray);
1518 
1519   // Create an instance of the structure
1520   return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1521 }
1522 
1523 /// Generates an IvarList.  Used in construction of a objc_class.
1524 llvm::Constant *CGObjCGNU::
1525 GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1526                  ArrayRef<llvm::Constant *> IvarTypes,
1527                  ArrayRef<llvm::Constant *> IvarOffsets) {
1528   if (IvarNames.size() == 0)
1529     return NULLPtr;
1530   // Get the method structure type.
1531   llvm::StructType *ObjCIvarTy = llvm::StructType::get(
1532     PtrToInt8Ty,
1533     PtrToInt8Ty,
1534     IntTy,
1535     nullptr);
1536   std::vector<llvm::Constant*> Ivars;
1537   std::vector<llvm::Constant*> Elements;
1538   for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1539     Elements.clear();
1540     Elements.push_back(IvarNames[i]);
1541     Elements.push_back(IvarTypes[i]);
1542     Elements.push_back(IvarOffsets[i]);
1543     Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
1544   }
1545 
1546   // Array of method structures
1547   llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
1548       IvarNames.size());
1549 
1550 
1551   Elements.clear();
1552   Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
1553   Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
1554   // Structure containing array and array count
1555   llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
1556     ObjCIvarArrayTy,
1557     nullptr);
1558 
1559   // Create an instance of the structure
1560   return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1561 }
1562 
1563 /// Generate a class structure
1564 llvm::Constant *CGObjCGNU::GenerateClassStructure(
1565     llvm::Constant *MetaClass,
1566     llvm::Constant *SuperClass,
1567     unsigned info,
1568     const char *Name,
1569     llvm::Constant *Version,
1570     llvm::Constant *InstanceSize,
1571     llvm::Constant *IVars,
1572     llvm::Constant *Methods,
1573     llvm::Constant *Protocols,
1574     llvm::Constant *IvarOffsets,
1575     llvm::Constant *Properties,
1576     llvm::Constant *StrongIvarBitmap,
1577     llvm::Constant *WeakIvarBitmap,
1578     bool isMeta) {
1579   // Set up the class structure
1580   // Note:  Several of these are char*s when they should be ids.  This is
1581   // because the runtime performs this translation on load.
1582   //
1583   // Fields marked New ABI are part of the GNUstep runtime.  We emit them
1584   // anyway; the classes will still work with the GNU runtime, they will just
1585   // be ignored.
1586   llvm::StructType *ClassTy = llvm::StructType::get(
1587       PtrToInt8Ty,        // isa
1588       PtrToInt8Ty,        // super_class
1589       PtrToInt8Ty,        // name
1590       LongTy,             // version
1591       LongTy,             // info
1592       LongTy,             // instance_size
1593       IVars->getType(),   // ivars
1594       Methods->getType(), // methods
1595       // These are all filled in by the runtime, so we pretend
1596       PtrTy,              // dtable
1597       PtrTy,              // subclass_list
1598       PtrTy,              // sibling_class
1599       PtrTy,              // protocols
1600       PtrTy,              // gc_object_type
1601       // New ABI:
1602       LongTy,                 // abi_version
1603       IvarOffsets->getType(), // ivar_offsets
1604       Properties->getType(),  // properties
1605       IntPtrTy,               // strong_pointers
1606       IntPtrTy,               // weak_pointers
1607       nullptr);
1608   llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
1609   // Fill in the structure
1610   std::vector<llvm::Constant*> Elements;
1611   Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
1612   Elements.push_back(SuperClass);
1613   Elements.push_back(MakeConstantString(Name, ".class_name"));
1614   Elements.push_back(Zero);
1615   Elements.push_back(llvm::ConstantInt::get(LongTy, info));
1616   if (isMeta) {
1617     llvm::DataLayout td(&TheModule);
1618     Elements.push_back(
1619         llvm::ConstantInt::get(LongTy,
1620                                td.getTypeSizeInBits(ClassTy) /
1621                                  CGM.getContext().getCharWidth()));
1622   } else
1623     Elements.push_back(InstanceSize);
1624   Elements.push_back(IVars);
1625   Elements.push_back(Methods);
1626   Elements.push_back(NULLPtr);
1627   Elements.push_back(NULLPtr);
1628   Elements.push_back(NULLPtr);
1629   Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
1630   Elements.push_back(NULLPtr);
1631   Elements.push_back(llvm::ConstantInt::get(LongTy, 1));
1632   Elements.push_back(IvarOffsets);
1633   Elements.push_back(Properties);
1634   Elements.push_back(StrongIvarBitmap);
1635   Elements.push_back(WeakIvarBitmap);
1636   // Create an instance of the structure
1637   // This is now an externally visible symbol, so that we can speed up class
1638   // messages in the next ABI.  We may already have some weak references to
1639   // this, so check and fix them properly.
1640   std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
1641           std::string(Name));
1642   llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
1643   llvm::Constant *Class = MakeGlobal(ClassTy, Elements, ClassSym,
1644           llvm::GlobalValue::ExternalLinkage);
1645   if (ClassRef) {
1646       ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
1647                   ClassRef->getType()));
1648       ClassRef->removeFromParent();
1649       Class->setName(ClassSym);
1650   }
1651   return Class;
1652 }
1653 
1654 llvm::Constant *CGObjCGNU::
1655 GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
1656                            ArrayRef<llvm::Constant *> MethodTypes) {
1657   // Get the method structure type.
1658   llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
1659     PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1660     PtrToInt8Ty,
1661     nullptr);
1662   std::vector<llvm::Constant*> Methods;
1663   std::vector<llvm::Constant*> Elements;
1664   for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1665     Elements.clear();
1666     Elements.push_back(MethodNames[i]);
1667     Elements.push_back(MethodTypes[i]);
1668     Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
1669   }
1670   llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
1671       MethodNames.size());
1672   llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
1673                                                    Methods);
1674   llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
1675       IntTy, ObjCMethodArrayTy, nullptr);
1676   Methods.clear();
1677   Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
1678   Methods.push_back(Array);
1679   return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1680 }
1681 
1682 // Create the protocol list structure used in classes, categories and so on
1683 llvm::Constant *CGObjCGNU::GenerateProtocolList(ArrayRef<std::string>Protocols){
1684   llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
1685       Protocols.size());
1686   llvm::StructType *ProtocolListTy = llvm::StructType::get(
1687       PtrTy, //Should be a recurisve pointer, but it's always NULL here.
1688       SizeTy,
1689       ProtocolArrayTy,
1690       nullptr);
1691   std::vector<llvm::Constant*> Elements;
1692   for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1693       iter != endIter ; iter++) {
1694     llvm::Constant *protocol = nullptr;
1695     llvm::StringMap<llvm::Constant*>::iterator value =
1696       ExistingProtocols.find(*iter);
1697     if (value == ExistingProtocols.end()) {
1698       protocol = GenerateEmptyProtocol(*iter);
1699     } else {
1700       protocol = value->getValue();
1701     }
1702     llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
1703                                                            PtrToInt8Ty);
1704     Elements.push_back(Ptr);
1705   }
1706   llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1707       Elements);
1708   Elements.clear();
1709   Elements.push_back(NULLPtr);
1710   Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
1711   Elements.push_back(ProtocolArray);
1712   return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1713 }
1714 
1715 llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
1716                                             const ObjCProtocolDecl *PD) {
1717   llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
1718   llvm::Type *T =
1719     CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
1720   return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
1721 }
1722 
1723 llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1724   const std::string &ProtocolName) {
1725   SmallVector<std::string, 0> EmptyStringVector;
1726   SmallVector<llvm::Constant*, 0> EmptyConstantVector;
1727 
1728   llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
1729   llvm::Constant *MethodList =
1730     GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1731   // Protocols are objects containing lists of the methods implemented and
1732   // protocols adopted.
1733   llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
1734       PtrToInt8Ty,
1735       ProtocolList->getType(),
1736       MethodList->getType(),
1737       MethodList->getType(),
1738       MethodList->getType(),
1739       MethodList->getType(),
1740       nullptr);
1741   std::vector<llvm::Constant*> Elements;
1742   // The isa pointer must be set to a magic number so the runtime knows it's
1743   // the correct layout.
1744   Elements.push_back(llvm::ConstantExpr::getIntToPtr(
1745         llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1746   Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1747   Elements.push_back(ProtocolList);
1748   Elements.push_back(MethodList);
1749   Elements.push_back(MethodList);
1750   Elements.push_back(MethodList);
1751   Elements.push_back(MethodList);
1752   return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
1753 }
1754 
1755 void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1756   ASTContext &Context = CGM.getContext();
1757   std::string ProtocolName = PD->getNameAsString();
1758 
1759   // Use the protocol definition, if there is one.
1760   if (const ObjCProtocolDecl *Def = PD->getDefinition())
1761     PD = Def;
1762 
1763   SmallVector<std::string, 16> Protocols;
1764   for (const auto *PI : PD->protocols())
1765     Protocols.push_back(PI->getNameAsString());
1766   SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1767   SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1768   SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1769   SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
1770   for (const auto *I : PD->instance_methods()) {
1771     std::string TypeStr;
1772     Context.getObjCEncodingForMethodDecl(I, TypeStr);
1773     if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
1774       OptionalInstanceMethodNames.push_back(
1775           MakeConstantString(I->getSelector().getAsString()));
1776       OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1777     } else {
1778       InstanceMethodNames.push_back(
1779           MakeConstantString(I->getSelector().getAsString()));
1780       InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1781     }
1782   }
1783   // Collect information about class methods:
1784   SmallVector<llvm::Constant*, 16> ClassMethodNames;
1785   SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1786   SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1787   SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
1788   for (const auto *I : PD->class_methods()) {
1789     std::string TypeStr;
1790     Context.getObjCEncodingForMethodDecl(I,TypeStr);
1791     if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
1792       OptionalClassMethodNames.push_back(
1793           MakeConstantString(I->getSelector().getAsString()));
1794       OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1795     } else {
1796       ClassMethodNames.push_back(
1797           MakeConstantString(I->getSelector().getAsString()));
1798       ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1799     }
1800   }
1801 
1802   llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1803   llvm::Constant *InstanceMethodList =
1804     GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1805   llvm::Constant *ClassMethodList =
1806     GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
1807   llvm::Constant *OptionalInstanceMethodList =
1808     GenerateProtocolMethodList(OptionalInstanceMethodNames,
1809             OptionalInstanceMethodTypes);
1810   llvm::Constant *OptionalClassMethodList =
1811     GenerateProtocolMethodList(OptionalClassMethodNames,
1812             OptionalClassMethodTypes);
1813 
1814   // Property metadata: name, attributes, isSynthesized, setter name, setter
1815   // types, getter name, getter types.
1816   // The isSynthesized value is always set to 0 in a protocol.  It exists to
1817   // simplify the runtime library by allowing it to use the same data
1818   // structures for protocol metadata everywhere.
1819   llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
1820           PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
1821           PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, nullptr);
1822   std::vector<llvm::Constant*> Properties;
1823   std::vector<llvm::Constant*> OptionalProperties;
1824 
1825   // Add all of the property methods need adding to the method list and to the
1826   // property metadata list.
1827   for (auto *property : PD->properties()) {
1828     std::vector<llvm::Constant*> Fields;
1829 
1830     Fields.push_back(MakePropertyEncodingString(property, nullptr));
1831     PushPropertyAttributes(Fields, property);
1832 
1833     if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1834       std::string TypeStr;
1835       Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1836       llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1837       InstanceMethodTypes.push_back(TypeEncoding);
1838       Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1839       Fields.push_back(TypeEncoding);
1840     } else {
1841       Fields.push_back(NULLPtr);
1842       Fields.push_back(NULLPtr);
1843     }
1844     if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1845       std::string TypeStr;
1846       Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1847       llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1848       InstanceMethodTypes.push_back(TypeEncoding);
1849       Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1850       Fields.push_back(TypeEncoding);
1851     } else {
1852       Fields.push_back(NULLPtr);
1853       Fields.push_back(NULLPtr);
1854     }
1855     if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1856       OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1857     } else {
1858       Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1859     }
1860   }
1861   llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1862       llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1863   llvm::Constant* PropertyListInitFields[] =
1864     {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1865 
1866   llvm::Constant *PropertyListInit =
1867       llvm::ConstantStruct::getAnon(PropertyListInitFields);
1868   llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1869       PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1870       PropertyListInit, ".objc_property_list");
1871 
1872   llvm::Constant *OptionalPropertyArray =
1873       llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1874           OptionalProperties.size()) , OptionalProperties);
1875   llvm::Constant* OptionalPropertyListInitFields[] = {
1876       llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1877       OptionalPropertyArray };
1878 
1879   llvm::Constant *OptionalPropertyListInit =
1880       llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
1881   llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1882           OptionalPropertyListInit->getType(), false,
1883           llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1884           ".objc_property_list");
1885 
1886   // Protocols are objects containing lists of the methods implemented and
1887   // protocols adopted.
1888   llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
1889       PtrToInt8Ty,
1890       ProtocolList->getType(),
1891       InstanceMethodList->getType(),
1892       ClassMethodList->getType(),
1893       OptionalInstanceMethodList->getType(),
1894       OptionalClassMethodList->getType(),
1895       PropertyList->getType(),
1896       OptionalPropertyList->getType(),
1897       nullptr);
1898   std::vector<llvm::Constant*> Elements;
1899   // The isa pointer must be set to a magic number so the runtime knows it's
1900   // the correct layout.
1901   Elements.push_back(llvm::ConstantExpr::getIntToPtr(
1902         llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1903   Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1904   Elements.push_back(ProtocolList);
1905   Elements.push_back(InstanceMethodList);
1906   Elements.push_back(ClassMethodList);
1907   Elements.push_back(OptionalInstanceMethodList);
1908   Elements.push_back(OptionalClassMethodList);
1909   Elements.push_back(PropertyList);
1910   Elements.push_back(OptionalPropertyList);
1911   ExistingProtocols[ProtocolName] =
1912     llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
1913           ".objc_protocol"), IdTy);
1914 }
1915 void CGObjCGNU::GenerateProtocolHolderCategory() {
1916   // Collect information about instance methods
1917   SmallVector<Selector, 1> MethodSels;
1918   SmallVector<llvm::Constant*, 1> MethodTypes;
1919 
1920   std::vector<llvm::Constant*> Elements;
1921   const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1922   const std::string CategoryName = "AnotherHack";
1923   Elements.push_back(MakeConstantString(CategoryName));
1924   Elements.push_back(MakeConstantString(ClassName));
1925   // Instance method list
1926   Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1927           ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1928   // Class method list
1929   Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1930           ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1931   // Protocol list
1932   llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1933       ExistingProtocols.size());
1934   llvm::StructType *ProtocolListTy = llvm::StructType::get(
1935       PtrTy, //Should be a recurisve pointer, but it's always NULL here.
1936       SizeTy,
1937       ProtocolArrayTy,
1938       nullptr);
1939   std::vector<llvm::Constant*> ProtocolElements;
1940   for (llvm::StringMapIterator<llvm::Constant*> iter =
1941        ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1942        iter != endIter ; iter++) {
1943     llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1944             PtrTy);
1945     ProtocolElements.push_back(Ptr);
1946   }
1947   llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1948       ProtocolElements);
1949   ProtocolElements.clear();
1950   ProtocolElements.push_back(NULLPtr);
1951   ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1952               ExistingProtocols.size()));
1953   ProtocolElements.push_back(ProtocolArray);
1954   Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1955                   ProtocolElements, ".objc_protocol_list"), PtrTy));
1956   Categories.push_back(llvm::ConstantExpr::getBitCast(
1957         MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
1958             PtrTy, PtrTy, PtrTy, nullptr), Elements), PtrTy));
1959 }
1960 
1961 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
1962 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
1963 /// bits set to their values, LSB first, while larger ones are stored in a
1964 /// structure of this / form:
1965 ///
1966 /// struct { int32_t length; int32_t values[length]; };
1967 ///
1968 /// The values in the array are stored in host-endian format, with the least
1969 /// significant bit being assumed to come first in the bitfield.  Therefore, a
1970 /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
1971 /// bitfield / with the 63rd bit set will be 1<<64.
1972 llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
1973   int bitCount = bits.size();
1974   int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
1975   if (bitCount < ptrBits) {
1976     uint64_t val = 1;
1977     for (int i=0 ; i<bitCount ; ++i) {
1978       if (bits[i]) val |= 1ULL<<(i+1);
1979     }
1980     return llvm::ConstantInt::get(IntPtrTy, val);
1981   }
1982   SmallVector<llvm::Constant *, 8> values;
1983   int v=0;
1984   while (v < bitCount) {
1985     int32_t word = 0;
1986     for (int i=0 ; (i<32) && (v<bitCount)  ; ++i) {
1987       if (bits[v]) word |= 1<<i;
1988       v++;
1989     }
1990     values.push_back(llvm::ConstantInt::get(Int32Ty, word));
1991   }
1992   llvm::ArrayType *arrayTy = llvm::ArrayType::get(Int32Ty, values.size());
1993   llvm::Constant *array = llvm::ConstantArray::get(arrayTy, values);
1994   llvm::Constant *fields[2] = {
1995       llvm::ConstantInt::get(Int32Ty, values.size()),
1996       array };
1997   llvm::Constant *GS = MakeGlobal(llvm::StructType::get(Int32Ty, arrayTy,
1998         nullptr), fields);
1999   llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
2000   return ptr;
2001 }
2002 
2003 void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
2004   std::string ClassName = OCD->getClassInterface()->getNameAsString();
2005   std::string CategoryName = OCD->getNameAsString();
2006   // Collect information about instance methods
2007   SmallVector<Selector, 16> InstanceMethodSels;
2008   SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
2009   for (const auto *I : OCD->instance_methods()) {
2010     InstanceMethodSels.push_back(I->getSelector());
2011     std::string TypeStr;
2012     CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr);
2013     InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
2014   }
2015 
2016   // Collect information about class methods
2017   SmallVector<Selector, 16> ClassMethodSels;
2018   SmallVector<llvm::Constant*, 16> ClassMethodTypes;
2019   for (const auto *I : OCD->class_methods()) {
2020     ClassMethodSels.push_back(I->getSelector());
2021     std::string TypeStr;
2022     CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr);
2023     ClassMethodTypes.push_back(MakeConstantString(TypeStr));
2024   }
2025 
2026   // Collect the names of referenced protocols
2027   SmallVector<std::string, 16> Protocols;
2028   const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
2029   const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
2030   for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
2031        E = Protos.end(); I != E; ++I)
2032     Protocols.push_back((*I)->getNameAsString());
2033 
2034   std::vector<llvm::Constant*> Elements;
2035   Elements.push_back(MakeConstantString(CategoryName));
2036   Elements.push_back(MakeConstantString(ClassName));
2037   // Instance method list
2038   Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
2039           ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
2040           false), PtrTy));
2041   // Class method list
2042   Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
2043           ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
2044         PtrTy));
2045   // Protocol list
2046   Elements.push_back(llvm::ConstantExpr::getBitCast(
2047         GenerateProtocolList(Protocols), PtrTy));
2048   Categories.push_back(llvm::ConstantExpr::getBitCast(
2049         MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
2050             PtrTy, PtrTy, PtrTy, nullptr), Elements), PtrTy));
2051 }
2052 
2053 llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
2054         SmallVectorImpl<Selector> &InstanceMethodSels,
2055         SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
2056   ASTContext &Context = CGM.getContext();
2057   // Property metadata: name, attributes, attributes2, padding1, padding2,
2058   // setter name, setter types, getter name, getter types.
2059   llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
2060           PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
2061           PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, nullptr);
2062   std::vector<llvm::Constant*> Properties;
2063 
2064   // Add all of the property methods need adding to the method list and to the
2065   // property metadata list.
2066   for (auto *propertyImpl : OID->property_impls()) {
2067     std::vector<llvm::Constant*> Fields;
2068     ObjCPropertyDecl *property = propertyImpl->getPropertyDecl();
2069     bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
2070         ObjCPropertyImplDecl::Synthesize);
2071     bool isDynamic = (propertyImpl->getPropertyImplementation() ==
2072         ObjCPropertyImplDecl::Dynamic);
2073 
2074     Fields.push_back(MakePropertyEncodingString(property, OID));
2075     PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
2076     if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
2077       std::string TypeStr;
2078       Context.getObjCEncodingForMethodDecl(getter,TypeStr);
2079       llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
2080       if (isSynthesized) {
2081         InstanceMethodTypes.push_back(TypeEncoding);
2082         InstanceMethodSels.push_back(getter->getSelector());
2083       }
2084       Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
2085       Fields.push_back(TypeEncoding);
2086     } else {
2087       Fields.push_back(NULLPtr);
2088       Fields.push_back(NULLPtr);
2089     }
2090     if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
2091       std::string TypeStr;
2092       Context.getObjCEncodingForMethodDecl(setter,TypeStr);
2093       llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
2094       if (isSynthesized) {
2095         InstanceMethodTypes.push_back(TypeEncoding);
2096         InstanceMethodSels.push_back(setter->getSelector());
2097       }
2098       Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
2099       Fields.push_back(TypeEncoding);
2100     } else {
2101       Fields.push_back(NULLPtr);
2102       Fields.push_back(NULLPtr);
2103     }
2104     Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
2105   }
2106   llvm::ArrayType *PropertyArrayTy =
2107       llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
2108   llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
2109           Properties);
2110   llvm::Constant* PropertyListInitFields[] =
2111     {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
2112 
2113   llvm::Constant *PropertyListInit =
2114       llvm::ConstantStruct::getAnon(PropertyListInitFields);
2115   return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
2116           llvm::GlobalValue::InternalLinkage, PropertyListInit,
2117           ".objc_property_list");
2118 }
2119 
2120 void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
2121   // Get the class declaration for which the alias is specified.
2122   ObjCInterfaceDecl *ClassDecl =
2123     const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
2124   ClassAliases.emplace_back(ClassDecl->getNameAsString(),
2125                             OAD->getNameAsString());
2126 }
2127 
2128 void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
2129   ASTContext &Context = CGM.getContext();
2130 
2131   // Get the superclass name.
2132   const ObjCInterfaceDecl * SuperClassDecl =
2133     OID->getClassInterface()->getSuperClass();
2134   std::string SuperClassName;
2135   if (SuperClassDecl) {
2136     SuperClassName = SuperClassDecl->getNameAsString();
2137     EmitClassRef(SuperClassName);
2138   }
2139 
2140   // Get the class name
2141   ObjCInterfaceDecl *ClassDecl =
2142     const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
2143   std::string ClassName = ClassDecl->getNameAsString();
2144   // Emit the symbol that is used to generate linker errors if this class is
2145   // referenced in other modules but not declared.
2146   std::string classSymbolName = "__objc_class_name_" + ClassName;
2147   if (llvm::GlobalVariable *symbol =
2148       TheModule.getGlobalVariable(classSymbolName)) {
2149     symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
2150   } else {
2151     new llvm::GlobalVariable(TheModule, LongTy, false,
2152     llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
2153     classSymbolName);
2154   }
2155 
2156   // Get the size of instances.
2157   int instanceSize =
2158     Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
2159 
2160   // Collect information about instance variables.
2161   SmallVector<llvm::Constant*, 16> IvarNames;
2162   SmallVector<llvm::Constant*, 16> IvarTypes;
2163   SmallVector<llvm::Constant*, 16> IvarOffsets;
2164 
2165   std::vector<llvm::Constant*> IvarOffsetValues;
2166   SmallVector<bool, 16> WeakIvars;
2167   SmallVector<bool, 16> StrongIvars;
2168 
2169   int superInstanceSize = !SuperClassDecl ? 0 :
2170     Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
2171   // For non-fragile ivars, set the instance size to 0 - {the size of just this
2172   // class}.  The runtime will then set this to the correct value on load.
2173   if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2174     instanceSize = 0 - (instanceSize - superInstanceSize);
2175   }
2176 
2177   for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2178        IVD = IVD->getNextIvar()) {
2179       // Store the name
2180       IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
2181       // Get the type encoding for this ivar
2182       std::string TypeStr;
2183       Context.getObjCEncodingForType(IVD->getType(), TypeStr);
2184       IvarTypes.push_back(MakeConstantString(TypeStr));
2185       // Get the offset
2186       uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
2187       uint64_t Offset = BaseOffset;
2188       if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2189         Offset = BaseOffset - superInstanceSize;
2190       }
2191       llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
2192       // Create the direct offset value
2193       std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
2194           IVD->getNameAsString();
2195       llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
2196       if (OffsetVar) {
2197         OffsetVar->setInitializer(OffsetValue);
2198         // If this is the real definition, change its linkage type so that
2199         // different modules will use this one, rather than their private
2200         // copy.
2201         OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
2202       } else
2203         OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
2204           false, llvm::GlobalValue::ExternalLinkage,
2205           OffsetValue,
2206           "__objc_ivar_offset_value_" + ClassName +"." +
2207           IVD->getNameAsString());
2208       IvarOffsets.push_back(OffsetValue);
2209       IvarOffsetValues.push_back(OffsetVar);
2210       Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
2211       switch (lt) {
2212         case Qualifiers::OCL_Strong:
2213           StrongIvars.push_back(true);
2214           WeakIvars.push_back(false);
2215           break;
2216         case Qualifiers::OCL_Weak:
2217           StrongIvars.push_back(false);
2218           WeakIvars.push_back(true);
2219           break;
2220         default:
2221           StrongIvars.push_back(false);
2222           WeakIvars.push_back(false);
2223       }
2224   }
2225   llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
2226   llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
2227   llvm::GlobalVariable *IvarOffsetArray =
2228     MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
2229 
2230 
2231   // Collect information about instance methods
2232   SmallVector<Selector, 16> InstanceMethodSels;
2233   SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
2234   for (const auto *I : OID->instance_methods()) {
2235     InstanceMethodSels.push_back(I->getSelector());
2236     std::string TypeStr;
2237     Context.getObjCEncodingForMethodDecl(I,TypeStr);
2238     InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
2239   }
2240 
2241   llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2242           InstanceMethodTypes);
2243 
2244 
2245   // Collect information about class methods
2246   SmallVector<Selector, 16> ClassMethodSels;
2247   SmallVector<llvm::Constant*, 16> ClassMethodTypes;
2248   for (const auto *I : OID->class_methods()) {
2249     ClassMethodSels.push_back(I->getSelector());
2250     std::string TypeStr;
2251     Context.getObjCEncodingForMethodDecl(I,TypeStr);
2252     ClassMethodTypes.push_back(MakeConstantString(TypeStr));
2253   }
2254   // Collect the names of referenced protocols
2255   SmallVector<std::string, 16> Protocols;
2256   for (const auto *I : ClassDecl->protocols())
2257     Protocols.push_back(I->getNameAsString());
2258 
2259   // Get the superclass pointer.
2260   llvm::Constant *SuperClass;
2261   if (!SuperClassName.empty()) {
2262     SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2263   } else {
2264     SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
2265   }
2266   // Empty vector used to construct empty method lists
2267   SmallVector<llvm::Constant*, 1>  empty;
2268   // Generate the method and instance variable lists
2269   llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
2270       InstanceMethodSels, InstanceMethodTypes, false);
2271   llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
2272       ClassMethodSels, ClassMethodTypes, true);
2273   llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2274       IvarOffsets);
2275   // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
2276   // we emit a symbol containing the offset for each ivar in the class.  This
2277   // allows code compiled for the non-Fragile ABI to inherit from code compiled
2278   // for the legacy ABI, without causing problems.  The converse is also
2279   // possible, but causes all ivar accesses to be fragile.
2280 
2281   // Offset pointer for getting at the correct field in the ivar list when
2282   // setting up the alias.  These are: The base address for the global, the
2283   // ivar array (second field), the ivar in this list (set for each ivar), and
2284   // the offset (third field in ivar structure)
2285   llvm::Type *IndexTy = Int32Ty;
2286   llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
2287       llvm::ConstantInt::get(IndexTy, 1), nullptr,
2288       llvm::ConstantInt::get(IndexTy, 2) };
2289 
2290   unsigned ivarIndex = 0;
2291   for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2292        IVD = IVD->getNextIvar()) {
2293       const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
2294           + IVD->getNameAsString();
2295       offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
2296       // Get the correct ivar field
2297       llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
2298           cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
2299           offsetPointerIndexes);
2300       // Get the existing variable, if one exists.
2301       llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2302       if (offset) {
2303         offset->setInitializer(offsetValue);
2304         // If this is the real definition, change its linkage type so that
2305         // different modules will use this one, rather than their private
2306         // copy.
2307         offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
2308       } else {
2309         // Add a new alias if there isn't one already.
2310         offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2311                 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2312         (void) offset; // Silence dead store warning.
2313       }
2314       ++ivarIndex;
2315   }
2316   llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
2317   //Generate metaclass for class methods
2318   llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
2319       NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0], GenerateIvarList(
2320         empty, empty, empty), ClassMethodList, NULLPtr,
2321       NULLPtr, NULLPtr, ZeroPtr, ZeroPtr, true);
2322 
2323   // Generate the class structure
2324   llvm::Constant *ClassStruct =
2325     GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
2326                            ClassName.c_str(), nullptr,
2327       llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
2328       MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
2329       Properties, StrongIvarBitmap, WeakIvarBitmap);
2330 
2331   // Resolve the class aliases, if they exist.
2332   if (ClassPtrAlias) {
2333     ClassPtrAlias->replaceAllUsesWith(
2334         llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
2335     ClassPtrAlias->eraseFromParent();
2336     ClassPtrAlias = nullptr;
2337   }
2338   if (MetaClassPtrAlias) {
2339     MetaClassPtrAlias->replaceAllUsesWith(
2340         llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
2341     MetaClassPtrAlias->eraseFromParent();
2342     MetaClassPtrAlias = nullptr;
2343   }
2344 
2345   // Add class structure to list to be added to the symtab later
2346   ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
2347   Classes.push_back(ClassStruct);
2348 }
2349 
2350 
2351 llvm::Function *CGObjCGNU::ModuleInitFunction() {
2352   // Only emit an ObjC load function if no Objective-C stuff has been called
2353   if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
2354       ExistingProtocols.empty() && SelectorTable.empty())
2355     return nullptr;
2356 
2357   // Add all referenced protocols to a category.
2358   GenerateProtocolHolderCategory();
2359 
2360   llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
2361           SelectorTy->getElementType());
2362   llvm::Type *SelStructPtrTy = SelectorTy;
2363   if (!SelStructTy) {
2364     SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, nullptr);
2365     SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
2366   }
2367 
2368   std::vector<llvm::Constant*> Elements;
2369   llvm::Constant *Statics = NULLPtr;
2370   // Generate statics list:
2371   if (!ConstantStrings.empty()) {
2372     llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
2373         ConstantStrings.size() + 1);
2374     ConstantStrings.push_back(NULLPtr);
2375 
2376     StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
2377 
2378     if (StringClass.empty()) StringClass = "NXConstantString";
2379 
2380     Elements.push_back(MakeConstantString(StringClass,
2381                 ".objc_static_class_name"));
2382     Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
2383        ConstantStrings));
2384     llvm::StructType *StaticsListTy =
2385       llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, nullptr);
2386     llvm::Type *StaticsListPtrTy =
2387       llvm::PointerType::getUnqual(StaticsListTy);
2388     Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
2389     llvm::ArrayType *StaticsListArrayTy =
2390       llvm::ArrayType::get(StaticsListPtrTy, 2);
2391     Elements.clear();
2392     Elements.push_back(Statics);
2393     Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
2394     Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
2395     Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
2396   }
2397   // Array of classes, categories, and constant objects
2398   llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
2399       Classes.size() + Categories.size()  + 2);
2400   llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
2401                                                      llvm::Type::getInt16Ty(VMContext),
2402                                                      llvm::Type::getInt16Ty(VMContext),
2403                                                      ClassListTy, nullptr);
2404 
2405   Elements.clear();
2406   // Pointer to an array of selectors used in this module.
2407   std::vector<llvm::Constant*> Selectors;
2408   std::vector<llvm::GlobalAlias*> SelectorAliases;
2409   for (SelectorMap::iterator iter = SelectorTable.begin(),
2410       iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2411 
2412     std::string SelNameStr = iter->first.getAsString();
2413     llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2414 
2415     SmallVectorImpl<TypedSelector> &Types = iter->second;
2416     for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
2417         e = Types.end() ; i!=e ; i++) {
2418 
2419       llvm::Constant *SelectorTypeEncoding = NULLPtr;
2420       if (!i->first.empty())
2421         SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2422 
2423       Elements.push_back(SelName);
2424       Elements.push_back(SelectorTypeEncoding);
2425       Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2426       Elements.clear();
2427 
2428       // Store the selector alias for later replacement
2429       SelectorAliases.push_back(i->second);
2430     }
2431   }
2432   unsigned SelectorCount = Selectors.size();
2433   // NULL-terminate the selector list.  This should not actually be required,
2434   // because the selector list has a length field.  Unfortunately, the GCC
2435   // runtime decides to ignore the length field and expects a NULL terminator,
2436   // and GCC cooperates with this by always setting the length to 0.
2437   Elements.push_back(NULLPtr);
2438   Elements.push_back(NULLPtr);
2439   Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2440   Elements.clear();
2441 
2442   // Number of static selectors
2443   Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2444   llvm::GlobalVariable *SelectorList =
2445       MakeGlobalArray(SelStructTy, Selectors, ".objc_selector_list");
2446   Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
2447     SelStructPtrTy));
2448 
2449   // Now that all of the static selectors exist, create pointers to them.
2450   for (unsigned int i=0 ; i<SelectorCount ; i++) {
2451 
2452     llvm::Constant *Idxs[] = {Zeros[0],
2453       llvm::ConstantInt::get(Int32Ty, i), Zeros[0]};
2454     // FIXME: We're generating redundant loads and stores here!
2455     llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(
2456         SelectorList->getValueType(), SelectorList, makeArrayRef(Idxs, 2));
2457     // If selectors are defined as an opaque type, cast the pointer to this
2458     // type.
2459     SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
2460     SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2461     SelectorAliases[i]->eraseFromParent();
2462   }
2463 
2464   // Number of classes defined.
2465   Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
2466         Classes.size()));
2467   // Number of categories defined
2468   Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
2469         Categories.size()));
2470   // Create an array of classes, then categories, then static object instances
2471   Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2472   //  NULL-terminated list of static object instances (mainly constant strings)
2473   Classes.push_back(Statics);
2474   Classes.push_back(NULLPtr);
2475   llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
2476   Elements.push_back(ClassList);
2477   // Construct the symbol table
2478   llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2479 
2480   // The symbol table is contained in a module which has some version-checking
2481   // constants
2482   llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
2483       PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
2484       (RuntimeVersion >= 10) ? IntTy : nullptr, nullptr);
2485   Elements.clear();
2486   // Runtime version, used for ABI compatibility checking.
2487   Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
2488   // sizeof(ModuleTy)
2489   llvm::DataLayout td(&TheModule);
2490   Elements.push_back(
2491     llvm::ConstantInt::get(LongTy,
2492                            td.getTypeSizeInBits(ModuleTy) /
2493                              CGM.getContext().getCharWidth()));
2494 
2495   // The path to the source file where this module was declared
2496   SourceManager &SM = CGM.getContext().getSourceManager();
2497   const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2498   std::string path =
2499     std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2500   Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
2501   Elements.push_back(SymTab);
2502 
2503   if (RuntimeVersion >= 10)
2504     switch (CGM.getLangOpts().getGC()) {
2505       case LangOptions::GCOnly:
2506         Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
2507         break;
2508       case LangOptions::NonGC:
2509         if (CGM.getLangOpts().ObjCAutoRefCount)
2510           Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2511         else
2512           Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
2513         break;
2514       case LangOptions::HybridGC:
2515           Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2516         break;
2517     }
2518 
2519   llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2520 
2521   // Create the load function calling the runtime entry point with the module
2522   // structure
2523   llvm::Function * LoadFunction = llvm::Function::Create(
2524       llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
2525       llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2526       &TheModule);
2527   llvm::BasicBlock *EntryBB =
2528       llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
2529   CGBuilderTy Builder(VMContext);
2530   Builder.SetInsertPoint(EntryBB);
2531 
2532   llvm::FunctionType *FT =
2533     llvm::FunctionType::get(Builder.getVoidTy(),
2534                             llvm::PointerType::getUnqual(ModuleTy), true);
2535   llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
2536   Builder.CreateCall(Register, Module);
2537 
2538   if (!ClassAliases.empty()) {
2539     llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
2540     llvm::FunctionType *RegisterAliasTy =
2541       llvm::FunctionType::get(Builder.getVoidTy(),
2542                               ArgTypes, false);
2543     llvm::Function *RegisterAlias = llvm::Function::Create(
2544       RegisterAliasTy,
2545       llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
2546       &TheModule);
2547     llvm::BasicBlock *AliasBB =
2548       llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
2549     llvm::BasicBlock *NoAliasBB =
2550       llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
2551 
2552     // Branch based on whether the runtime provided class_registerAlias_np()
2553     llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
2554             llvm::Constant::getNullValue(RegisterAlias->getType()));
2555     Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
2556 
2557     // The true branch (has alias registration function):
2558     Builder.SetInsertPoint(AliasBB);
2559     // Emit alias registration calls:
2560     for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
2561        iter != ClassAliases.end(); ++iter) {
2562        llvm::Constant *TheClass =
2563          TheModule.getGlobalVariable(("_OBJC_CLASS_" + iter->first).c_str(),
2564             true);
2565        if (TheClass) {
2566          TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
2567          Builder.CreateCall(RegisterAlias,
2568                             {TheClass, MakeConstantString(iter->second)});
2569        }
2570     }
2571     // Jump to end:
2572     Builder.CreateBr(NoAliasBB);
2573 
2574     // Missing alias registration function, just return from the function:
2575     Builder.SetInsertPoint(NoAliasBB);
2576   }
2577   Builder.CreateRetVoid();
2578 
2579   return LoadFunction;
2580 }
2581 
2582 llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
2583                                           const ObjCContainerDecl *CD) {
2584   const ObjCCategoryImplDecl *OCD =
2585     dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
2586   StringRef CategoryName = OCD ? OCD->getName() : "";
2587   StringRef ClassName = CD->getName();
2588   Selector MethodName = OMD->getSelector();
2589   bool isClassMethod = !OMD->isInstanceMethod();
2590 
2591   CodeGenTypes &Types = CGM.getTypes();
2592   llvm::FunctionType *MethodTy =
2593     Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
2594   std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2595       MethodName, isClassMethod);
2596 
2597   llvm::Function *Method
2598     = llvm::Function::Create(MethodTy,
2599                              llvm::GlobalValue::InternalLinkage,
2600                              FunctionName,
2601                              &TheModule);
2602   return Method;
2603 }
2604 
2605 llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
2606   return GetPropertyFn;
2607 }
2608 
2609 llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
2610   return SetPropertyFn;
2611 }
2612 
2613 llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
2614                                                            bool copy) {
2615   return nullptr;
2616 }
2617 
2618 llvm::Constant *CGObjCGNU::GetGetStructFunction() {
2619   return GetStructPropertyFn;
2620 }
2621 llvm::Constant *CGObjCGNU::GetSetStructFunction() {
2622   return SetStructPropertyFn;
2623 }
2624 llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
2625   return nullptr;
2626 }
2627 llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
2628   return nullptr;
2629 }
2630 
2631 llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
2632   return EnumerationMutationFn;
2633 }
2634 
2635 void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
2636                                      const ObjCAtSynchronizedStmt &S) {
2637   EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
2638 }
2639 
2640 
2641 void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
2642                             const ObjCAtTryStmt &S) {
2643   // Unlike the Apple non-fragile runtimes, which also uses
2644   // unwind-based zero cost exceptions, the GNU Objective C runtime's
2645   // EH support isn't a veneer over C++ EH.  Instead, exception
2646   // objects are created by objc_exception_throw and destroyed by
2647   // the personality function; this avoids the need for bracketing
2648   // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2649   // (or even _Unwind_DeleteException), but probably doesn't
2650   // interoperate very well with foreign exceptions.
2651   //
2652   // In Objective-C++ mode, we actually emit something equivalent to the C++
2653   // exception handler.
2654   EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2655   return ;
2656 }
2657 
2658 void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
2659                               const ObjCAtThrowStmt &S,
2660                               bool ClearInsertionPoint) {
2661   llvm::Value *ExceptionAsObject;
2662 
2663   if (const Expr *ThrowExpr = S.getThrowExpr()) {
2664     llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
2665     ExceptionAsObject = Exception;
2666   } else {
2667     assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
2668            "Unexpected rethrow outside @catch block.");
2669     ExceptionAsObject = CGF.ObjCEHValueStack.back();
2670   }
2671   ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
2672   llvm::CallSite Throw =
2673       CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
2674   Throw.setDoesNotReturn();
2675   CGF.Builder.CreateUnreachable();
2676   if (ClearInsertionPoint)
2677     CGF.Builder.ClearInsertionPoint();
2678 }
2679 
2680 llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
2681                                           llvm::Value *AddrWeakObj) {
2682   CGBuilderTy &B = CGF.Builder;
2683   AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
2684   return B.CreateCall(WeakReadFn.getType(), WeakReadFn, AddrWeakObj);
2685 }
2686 
2687 void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
2688                                    llvm::Value *src, llvm::Value *dst) {
2689   CGBuilderTy &B = CGF.Builder;
2690   src = EnforceType(B, src, IdTy);
2691   dst = EnforceType(B, dst, PtrToIdTy);
2692   B.CreateCall(WeakAssignFn.getType(), WeakAssignFn, {src, dst});
2693 }
2694 
2695 void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
2696                                      llvm::Value *src, llvm::Value *dst,
2697                                      bool threadlocal) {
2698   CGBuilderTy &B = CGF.Builder;
2699   src = EnforceType(B, src, IdTy);
2700   dst = EnforceType(B, dst, PtrToIdTy);
2701   // FIXME. Add threadloca assign API
2702   assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
2703   B.CreateCall(GlobalAssignFn.getType(), GlobalAssignFn, {src, dst});
2704 }
2705 
2706 void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
2707                                    llvm::Value *src, llvm::Value *dst,
2708                                    llvm::Value *ivarOffset) {
2709   CGBuilderTy &B = CGF.Builder;
2710   src = EnforceType(B, src, IdTy);
2711   dst = EnforceType(B, dst, IdTy);
2712   B.CreateCall(IvarAssignFn.getType(), IvarAssignFn, {src, dst, ivarOffset});
2713 }
2714 
2715 void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
2716                                          llvm::Value *src, llvm::Value *dst) {
2717   CGBuilderTy &B = CGF.Builder;
2718   src = EnforceType(B, src, IdTy);
2719   dst = EnforceType(B, dst, PtrToIdTy);
2720   B.CreateCall(StrongCastAssignFn.getType(), StrongCastAssignFn, {src, dst});
2721 }
2722 
2723 void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
2724                                          llvm::Value *DestPtr,
2725                                          llvm::Value *SrcPtr,
2726                                          llvm::Value *Size) {
2727   CGBuilderTy &B = CGF.Builder;
2728   DestPtr = EnforceType(B, DestPtr, PtrTy);
2729   SrcPtr = EnforceType(B, SrcPtr, PtrTy);
2730 
2731   B.CreateCall(MemMoveFn.getType(), MemMoveFn, {DestPtr, SrcPtr, Size});
2732 }
2733 
2734 llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2735                               const ObjCInterfaceDecl *ID,
2736                               const ObjCIvarDecl *Ivar) {
2737   const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2738     + '.' + Ivar->getNameAsString();
2739   // Emit the variable and initialize it with what we think the correct value
2740   // is.  This allows code compiled with non-fragile ivars to work correctly
2741   // when linked against code which isn't (most of the time).
2742   llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2743   if (!IvarOffsetPointer) {
2744     // This will cause a run-time crash if we accidentally use it.  A value of
2745     // 0 would seem more sensible, but will silently overwrite the isa pointer
2746     // causing a great deal of confusion.
2747     uint64_t Offset = -1;
2748     // We can't call ComputeIvarBaseOffset() here if we have the
2749     // implementation, because it will create an invalid ASTRecordLayout object
2750     // that we are then stuck with forever, so we only initialize the ivar
2751     // offset variable with a guess if we only have the interface.  The
2752     // initializer will be reset later anyway, when we are generating the class
2753     // description.
2754     if (!CGM.getContext().getObjCImplementation(
2755               const_cast<ObjCInterfaceDecl *>(ID)))
2756       Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2757 
2758     llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
2759                              /*isSigned*/true);
2760     // Don't emit the guess in non-PIC code because the linker will not be able
2761     // to replace it with the real version for a library.  In non-PIC code you
2762     // must compile with the fragile ABI if you want to use ivars from a
2763     // GCC-compiled class.
2764     if (CGM.getLangOpts().PICLevel || CGM.getLangOpts().PIELevel) {
2765       llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2766             Int32Ty, false,
2767             llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2768       IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2769             IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2770             IvarOffsetGV, Name);
2771     } else {
2772       IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2773               llvm::Type::getInt32PtrTy(VMContext), false,
2774               llvm::GlobalValue::ExternalLinkage, nullptr, Name);
2775     }
2776   }
2777   return IvarOffsetPointer;
2778 }
2779 
2780 LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
2781                                        QualType ObjectTy,
2782                                        llvm::Value *BaseValue,
2783                                        const ObjCIvarDecl *Ivar,
2784                                        unsigned CVRQualifiers) {
2785   const ObjCInterfaceDecl *ID =
2786     ObjectTy->getAs<ObjCObjectType>()->getInterface();
2787   return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2788                                   EmitIvarOffset(CGF, ID, Ivar));
2789 }
2790 
2791 static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2792                                                   const ObjCInterfaceDecl *OID,
2793                                                   const ObjCIvarDecl *OIVD) {
2794   for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2795        next = next->getNextIvar()) {
2796     if (OIVD == next)
2797       return OID;
2798   }
2799 
2800   // Otherwise check in the super class.
2801   if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2802     return FindIvarInterface(Context, Super, OIVD);
2803 
2804   return nullptr;
2805 }
2806 
2807 llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
2808                          const ObjCInterfaceDecl *Interface,
2809                          const ObjCIvarDecl *Ivar) {
2810   if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2811     Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
2812     if (RuntimeVersion < 10)
2813       return CGF.Builder.CreateZExtOrBitCast(
2814           CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2815                   ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2816           PtrDiffTy);
2817     std::string name = "__objc_ivar_offset_value_" +
2818       Interface->getNameAsString() +"." + Ivar->getNameAsString();
2819     llvm::Value *Offset = TheModule.getGlobalVariable(name);
2820     if (!Offset)
2821       Offset = new llvm::GlobalVariable(TheModule, IntTy,
2822           false, llvm::GlobalValue::LinkOnceAnyLinkage,
2823           llvm::Constant::getNullValue(IntTy), name);
2824     Offset = CGF.Builder.CreateLoad(Offset);
2825     if (Offset->getType() != PtrDiffTy)
2826       Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
2827     return Offset;
2828   }
2829   uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
2830   return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
2831 }
2832 
2833 CGObjCRuntime *
2834 clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2835   switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
2836   case ObjCRuntime::GNUstep:
2837     return new CGObjCGNUstep(CGM);
2838 
2839   case ObjCRuntime::GCC:
2840     return new CGObjCGCC(CGM);
2841 
2842   case ObjCRuntime::ObjFW:
2843     return new CGObjCObjFW(CGM);
2844 
2845   case ObjCRuntime::FragileMacOSX:
2846   case ObjCRuntime::MacOSX:
2847   case ObjCRuntime::iOS:
2848     llvm_unreachable("these runtimes are not GNU runtimes");
2849   }
2850   llvm_unreachable("bad runtime");
2851 }
2852