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