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