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