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