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