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