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