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