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