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