]> granicus.if.org Git - clang/blob - lib/CodeGen/CGObjCGNU.cpp
Update for llvm api change.
[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 = llvm::GlobalAlias::create(
1057         SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
1058         ".objc_selector_" + Sel.getAsString(), &TheModule);
1059     Types.push_back(TypedSelector(TypeEncoding, SelValue));
1060   }
1061
1062   if (lval) {
1063     llvm::Value *tmp = CGF.CreateTempAlloca(SelValue->getType());
1064     CGF.Builder.CreateStore(SelValue, tmp);
1065     return tmp;
1066   }
1067   return SelValue;
1068 }
1069
1070 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
1071                                     bool lval) {
1072   return GetSelector(CGF, Sel, std::string(), lval);
1073 }
1074
1075 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
1076                                     const ObjCMethodDecl *Method) {
1077   std::string SelTypes;
1078   CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
1079   return GetSelector(CGF, Method->getSelector(), SelTypes, false);
1080 }
1081
1082 llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
1083   if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
1084     // With the old ABI, there was only one kind of catchall, which broke
1085     // foreign exceptions.  With the new ABI, we use __objc_id_typeinfo as
1086     // a pointer indicating object catchalls, and NULL to indicate real
1087     // catchalls
1088     if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1089       return MakeConstantString("@id");
1090     } else {
1091       return 0;
1092     }
1093   }
1094
1095   // All other types should be Objective-C interface pointer types.
1096   const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
1097   assert(OPT && "Invalid @catch type.");
1098   const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
1099   assert(IDecl && "Invalid @catch type.");
1100   return MakeConstantString(IDecl->getIdentifier()->getName());
1101 }
1102
1103 llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
1104   if (!CGM.getLangOpts().CPlusPlus)
1105     return CGObjCGNU::GetEHType(T);
1106
1107   // For Objective-C++, we want to provide the ability to catch both C++ and
1108   // Objective-C objects in the same function.
1109
1110   // There's a particular fixed type info for 'id'.
1111   if (T->isObjCIdType() ||
1112       T->isObjCQualifiedIdType()) {
1113     llvm::Constant *IDEHType =
1114       CGM.getModule().getGlobalVariable("__objc_id_type_info");
1115     if (!IDEHType)
1116       IDEHType =
1117         new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
1118                                  false,
1119                                  llvm::GlobalValue::ExternalLinkage,
1120                                  0, "__objc_id_type_info");
1121     return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
1122   }
1123
1124   const ObjCObjectPointerType *PT =
1125     T->getAs<ObjCObjectPointerType>();
1126   assert(PT && "Invalid @catch type.");
1127   const ObjCInterfaceType *IT = PT->getInterfaceType();
1128   assert(IT && "Invalid @catch type.");
1129   std::string className = IT->getDecl()->getIdentifier()->getName();
1130
1131   std::string typeinfoName = "__objc_eh_typeinfo_" + className;
1132
1133   // Return the existing typeinfo if it exists
1134   llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
1135   if (typeinfo)
1136     return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
1137
1138   // Otherwise create it.
1139
1140   // vtable for gnustep::libobjc::__objc_class_type_info
1141   // It's quite ugly hard-coding this.  Ideally we'd generate it using the host
1142   // platform's name mangling.
1143   const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
1144   llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
1145   if (!Vtable) {
1146     Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
1147             llvm::GlobalValue::ExternalLinkage, 0, vtableName);
1148   }
1149   llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
1150   Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, Two);
1151   Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
1152
1153   llvm::Constant *typeName =
1154     ExportUniqueString(className, "__objc_eh_typename_");
1155
1156   std::vector<llvm::Constant*> fields;
1157   fields.push_back(Vtable);
1158   fields.push_back(typeName);
1159   llvm::Constant *TI = 
1160       MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
1161               NULL), fields, "__objc_eh_typeinfo_" + className,
1162           llvm::GlobalValue::LinkOnceODRLinkage);
1163   return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
1164 }
1165
1166 /// Generate an NSConstantString object.
1167 llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
1168
1169   std::string Str = SL->getString().str();
1170
1171   // Look for an existing one
1172   llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
1173   if (old != ObjCStrings.end())
1174     return old->getValue();
1175
1176   StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
1177
1178   if (StringClass.empty()) StringClass = "NXConstantString";
1179
1180   std::string Sym = "_OBJC_CLASS_";
1181   Sym += StringClass;
1182
1183   llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1184
1185   if (!isa)
1186     isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1187             llvm::GlobalValue::ExternalWeakLinkage, 0, Sym);
1188   else if (isa->getType() != PtrToIdTy)
1189     isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1190
1191   std::vector<llvm::Constant*> Ivars;
1192   Ivars.push_back(isa);
1193   Ivars.push_back(MakeConstantString(Str));
1194   Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
1195   llvm::Constant *ObjCStr = MakeGlobal(
1196     llvm::StructType::get(PtrToIdTy, PtrToInt8Ty, IntTy, NULL),
1197     Ivars, ".objc_str");
1198   ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
1199   ObjCStrings[Str] = ObjCStr;
1200   ConstantStrings.push_back(ObjCStr);
1201   return ObjCStr;
1202 }
1203
1204 ///Generates a message send where the super is the receiver.  This is a message
1205 ///send to self with special delivery semantics indicating which class's method
1206 ///should be called.
1207 RValue
1208 CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
1209                                     ReturnValueSlot Return,
1210                                     QualType ResultType,
1211                                     Selector Sel,
1212                                     const ObjCInterfaceDecl *Class,
1213                                     bool isCategoryImpl,
1214                                     llvm::Value *Receiver,
1215                                     bool IsClassMessage,
1216                                     const CallArgList &CallArgs,
1217                                     const ObjCMethodDecl *Method) {
1218   CGBuilderTy &Builder = CGF.Builder;
1219   if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
1220     if (Sel == RetainSel || Sel == AutoreleaseSel) {
1221       return RValue::get(EnforceType(Builder, Receiver,
1222                   CGM.getTypes().ConvertType(ResultType)));
1223     }
1224     if (Sel == ReleaseSel) {
1225       return RValue::get(0);
1226     }
1227   }
1228
1229   llvm::Value *cmd = GetSelector(CGF, Sel);
1230
1231
1232   CallArgList ActualArgs;
1233
1234   ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
1235   ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
1236   ActualArgs.addFrom(CallArgs);
1237
1238   MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1239
1240   llvm::Value *ReceiverClass = 0;
1241   if (isCategoryImpl) {
1242     llvm::Constant *classLookupFunction = 0;
1243     if (IsClassMessage)  {
1244       classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1245             IdTy, PtrTy, true), "objc_get_meta_class");
1246     } else {
1247       classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1248             IdTy, PtrTy, true), "objc_get_class");
1249     }
1250     ReceiverClass = Builder.CreateCall(classLookupFunction,
1251         MakeConstantString(Class->getNameAsString()));
1252   } else {
1253     // Set up global aliases for the metaclass or class pointer if they do not
1254     // already exist.  These will are forward-references which will be set to
1255     // pointers to the class and metaclass structure created for the runtime
1256     // load function.  To send a message to super, we look up the value of the
1257     // super_class pointer from either the class or metaclass structure.
1258     if (IsClassMessage)  {
1259       if (!MetaClassPtrAlias) {
1260         MetaClassPtrAlias = llvm::GlobalAlias::create(
1261             IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
1262             ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
1263       }
1264       ReceiverClass = MetaClassPtrAlias;
1265     } else {
1266       if (!ClassPtrAlias) {
1267         ClassPtrAlias = llvm::GlobalAlias::create(
1268             IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
1269             ".objc_class_ref" + Class->getNameAsString(), &TheModule);
1270       }
1271       ReceiverClass = ClassPtrAlias;
1272     }
1273   }
1274   // Cast the pointer to a simplified version of the class structure
1275   ReceiverClass = Builder.CreateBitCast(ReceiverClass,
1276       llvm::PointerType::getUnqual(
1277         llvm::StructType::get(IdTy, IdTy, NULL)));
1278   // Get the superclass pointer
1279   ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
1280   // Load the superclass pointer
1281   ReceiverClass = Builder.CreateLoad(ReceiverClass);
1282   // Construct the structure used to look up the IMP
1283   llvm::StructType *ObjCSuperTy = llvm::StructType::get(
1284       Receiver->getType(), IdTy, NULL);
1285   llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
1286
1287   Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
1288   Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
1289
1290   ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
1291
1292   // Get the IMP
1293   llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
1294   imp = EnforceType(Builder, imp, MSI.MessengerType);
1295
1296   llvm::Value *impMD[] = {
1297       llvm::MDString::get(VMContext, Sel.getAsString()),
1298       llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1299       llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
1300    };
1301   llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
1302
1303   llvm::Instruction *call;
1304   RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, 0, &call);
1305   call->setMetadata(msgSendMDKind, node);
1306   return msgRet;
1307 }
1308
1309 /// Generate code for a message send expression.
1310 RValue
1311 CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
1312                                ReturnValueSlot Return,
1313                                QualType ResultType,
1314                                Selector Sel,
1315                                llvm::Value *Receiver,
1316                                const CallArgList &CallArgs,
1317                                const ObjCInterfaceDecl *Class,
1318                                const ObjCMethodDecl *Method) {
1319   CGBuilderTy &Builder = CGF.Builder;
1320
1321   // Strip out message sends to retain / release in GC mode
1322   if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
1323     if (Sel == RetainSel || Sel == AutoreleaseSel) {
1324       return RValue::get(EnforceType(Builder, Receiver,
1325                   CGM.getTypes().ConvertType(ResultType)));
1326     }
1327     if (Sel == ReleaseSel) {
1328       return RValue::get(0);
1329     }
1330   }
1331
1332   // If the return type is something that goes in an integer register, the
1333   // runtime will handle 0 returns.  For other cases, we fill in the 0 value
1334   // ourselves.
1335   //
1336   // The language spec says the result of this kind of message send is
1337   // undefined, but lots of people seem to have forgotten to read that
1338   // paragraph and insist on sending messages to nil that have structure
1339   // returns.  With GCC, this generates a random return value (whatever happens
1340   // to be on the stack / in those registers at the time) on most platforms,
1341   // and generates an illegal instruction trap on SPARC.  With LLVM it corrupts
1342   // the stack.  
1343   bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1344       ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
1345
1346   llvm::BasicBlock *startBB = 0;
1347   llvm::BasicBlock *messageBB = 0;
1348   llvm::BasicBlock *continueBB = 0;
1349
1350   if (!isPointerSizedReturn) {
1351     startBB = Builder.GetInsertBlock();
1352     messageBB = CGF.createBasicBlock("msgSend");
1353     continueBB = CGF.createBasicBlock("continue");
1354
1355     llvm::Value *isNil = Builder.CreateICmpEQ(Receiver, 
1356             llvm::Constant::getNullValue(Receiver->getType()));
1357     Builder.CreateCondBr(isNil, continueBB, messageBB);
1358     CGF.EmitBlock(messageBB);
1359   }
1360
1361   IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
1362   llvm::Value *cmd;
1363   if (Method)
1364     cmd = GetSelector(CGF, Method);
1365   else
1366     cmd = GetSelector(CGF, Sel);
1367   cmd = EnforceType(Builder, cmd, SelectorTy);
1368   Receiver = EnforceType(Builder, Receiver, IdTy);
1369
1370   llvm::Value *impMD[] = {
1371         llvm::MDString::get(VMContext, Sel.getAsString()),
1372         llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
1373         llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
1374    };
1375   llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
1376
1377   CallArgList ActualArgs;
1378   ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1379   ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
1380   ActualArgs.addFrom(CallArgs);
1381
1382   MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1383
1384   // Get the IMP to call
1385   llvm::Value *imp;
1386
1387   // If we have non-legacy dispatch specified, we try using the objc_msgSend()
1388   // functions.  These are not supported on all platforms (or all runtimes on a
1389   // given platform), so we 
1390   switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
1391     case CodeGenOptions::Legacy:
1392       imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
1393       break;
1394     case CodeGenOptions::Mixed:
1395     case CodeGenOptions::NonLegacy:
1396       if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1397         imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1398                                   "objc_msgSend_fpret");
1399       } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
1400         // The actual types here don't matter - we're going to bitcast the
1401         // function anyway
1402         imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1403                                   "objc_msgSend_stret");
1404       } else {
1405         imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1406                                   "objc_msgSend");
1407       }
1408   }
1409
1410   // Reset the receiver in case the lookup modified it
1411   ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
1412
1413   imp = EnforceType(Builder, imp, MSI.MessengerType);
1414
1415   llvm::Instruction *call;
1416   RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, 0, &call);
1417   call->setMetadata(msgSendMDKind, node);
1418
1419
1420   if (!isPointerSizedReturn) {
1421     messageBB = CGF.Builder.GetInsertBlock();
1422     CGF.Builder.CreateBr(continueBB);
1423     CGF.EmitBlock(continueBB);
1424     if (msgRet.isScalar()) {
1425       llvm::Value *v = msgRet.getScalarVal();
1426       llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
1427       phi->addIncoming(v, messageBB);
1428       phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1429       msgRet = RValue::get(phi);
1430     } else if (msgRet.isAggregate()) {
1431       llvm::Value *v = msgRet.getAggregateAddr();
1432       llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
1433       llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
1434       llvm::AllocaInst *NullVal = 
1435           CGF.CreateTempAlloca(RetTy->getElementType(), "null");
1436       CGF.InitTempAlloca(NullVal,
1437           llvm::Constant::getNullValue(RetTy->getElementType()));
1438       phi->addIncoming(v, messageBB);
1439       phi->addIncoming(NullVal, startBB);
1440       msgRet = RValue::getAggregate(phi);
1441     } else /* isComplex() */ {
1442       std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
1443       llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
1444       phi->addIncoming(v.first, messageBB);
1445       phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1446           startBB);
1447       llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
1448       phi2->addIncoming(v.second, messageBB);
1449       phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1450           startBB);
1451       msgRet = RValue::getComplex(phi, phi2);
1452     }
1453   }
1454   return msgRet;
1455 }
1456
1457 /// Generates a MethodList.  Used in construction of a objc_class and
1458 /// objc_category structures.
1459 llvm::Constant *CGObjCGNU::
1460 GenerateMethodList(const StringRef &ClassName,
1461                    const StringRef &CategoryName,
1462                    ArrayRef<Selector> MethodSels,
1463                    ArrayRef<llvm::Constant *> MethodTypes,
1464                    bool isClassMethodList) {
1465   if (MethodSels.empty())
1466     return NULLPtr;
1467   // Get the method structure type.
1468   llvm::StructType *ObjCMethodTy = llvm::StructType::get(
1469     PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1470     PtrToInt8Ty, // Method types
1471     IMPTy, //Method pointer
1472     NULL);
1473   std::vector<llvm::Constant*> Methods;
1474   std::vector<llvm::Constant*> Elements;
1475   for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1476     Elements.clear();
1477     llvm::Constant *Method =
1478       TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
1479                                                 MethodSels[i],
1480                                                 isClassMethodList));
1481     assert(Method && "Can't generate metadata for method that doesn't exist");
1482     llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1483     Elements.push_back(C);
1484     Elements.push_back(MethodTypes[i]);
1485     Method = llvm::ConstantExpr::getBitCast(Method,
1486         IMPTy);
1487     Elements.push_back(Method);
1488     Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
1489   }
1490
1491   // Array of method structures
1492   llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
1493                                                             Methods.size());
1494   llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
1495                                                          Methods);
1496
1497   // Structure containing list pointer, array and array count
1498   llvm::StructType *ObjCMethodListTy = llvm::StructType::create(VMContext);
1499   llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
1500   ObjCMethodListTy->setBody(
1501       NextPtrTy,
1502       IntTy,
1503       ObjCMethodArrayTy,
1504       NULL);
1505
1506   Methods.clear();
1507   Methods.push_back(llvm::ConstantPointerNull::get(
1508         llvm::PointerType::getUnqual(ObjCMethodListTy)));
1509   Methods.push_back(llvm::ConstantInt::get(Int32Ty, MethodTypes.size()));
1510   Methods.push_back(MethodArray);
1511
1512   // Create an instance of the structure
1513   return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1514 }
1515
1516 /// Generates an IvarList.  Used in construction of a objc_class.
1517 llvm::Constant *CGObjCGNU::
1518 GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1519                  ArrayRef<llvm::Constant *> IvarTypes,
1520                  ArrayRef<llvm::Constant *> IvarOffsets) {
1521   if (IvarNames.size() == 0)
1522     return NULLPtr;
1523   // Get the method structure type.
1524   llvm::StructType *ObjCIvarTy = llvm::StructType::get(
1525     PtrToInt8Ty,
1526     PtrToInt8Ty,
1527     IntTy,
1528     NULL);
1529   std::vector<llvm::Constant*> Ivars;
1530   std::vector<llvm::Constant*> Elements;
1531   for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1532     Elements.clear();
1533     Elements.push_back(IvarNames[i]);
1534     Elements.push_back(IvarTypes[i]);
1535     Elements.push_back(IvarOffsets[i]);
1536     Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
1537   }
1538
1539   // Array of method structures
1540   llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
1541       IvarNames.size());
1542
1543
1544   Elements.clear();
1545   Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
1546   Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
1547   // Structure containing array and array count
1548   llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
1549     ObjCIvarArrayTy,
1550     NULL);
1551
1552   // Create an instance of the structure
1553   return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1554 }
1555
1556 /// Generate a class structure
1557 llvm::Constant *CGObjCGNU::GenerateClassStructure(
1558     llvm::Constant *MetaClass,
1559     llvm::Constant *SuperClass,
1560     unsigned info,
1561     const char *Name,
1562     llvm::Constant *Version,
1563     llvm::Constant *InstanceSize,
1564     llvm::Constant *IVars,
1565     llvm::Constant *Methods,
1566     llvm::Constant *Protocols,
1567     llvm::Constant *IvarOffsets,
1568     llvm::Constant *Properties,
1569     llvm::Constant *StrongIvarBitmap,
1570     llvm::Constant *WeakIvarBitmap,
1571     bool isMeta) {
1572   // Set up the class structure
1573   // Note:  Several of these are char*s when they should be ids.  This is
1574   // because the runtime performs this translation on load.
1575   //
1576   // Fields marked New ABI are part of the GNUstep runtime.  We emit them
1577   // anyway; the classes will still work with the GNU runtime, they will just
1578   // be ignored.
1579   llvm::StructType *ClassTy = llvm::StructType::get(
1580       PtrToInt8Ty,        // isa 
1581       PtrToInt8Ty,        // super_class
1582       PtrToInt8Ty,        // name
1583       LongTy,             // version
1584       LongTy,             // info
1585       LongTy,             // instance_size
1586       IVars->getType(),   // ivars
1587       Methods->getType(), // methods
1588       // These are all filled in by the runtime, so we pretend
1589       PtrTy,              // dtable
1590       PtrTy,              // subclass_list
1591       PtrTy,              // sibling_class
1592       PtrTy,              // protocols
1593       PtrTy,              // gc_object_type
1594       // New ABI:
1595       LongTy,                 // abi_version
1596       IvarOffsets->getType(), // ivar_offsets
1597       Properties->getType(),  // properties
1598       IntPtrTy,               // strong_pointers
1599       IntPtrTy,               // weak_pointers
1600       NULL);
1601   llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
1602   // Fill in the structure
1603   std::vector<llvm::Constant*> Elements;
1604   Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
1605   Elements.push_back(SuperClass);
1606   Elements.push_back(MakeConstantString(Name, ".class_name"));
1607   Elements.push_back(Zero);
1608   Elements.push_back(llvm::ConstantInt::get(LongTy, info));
1609   if (isMeta) {
1610     llvm::DataLayout td(&TheModule);
1611     Elements.push_back(
1612         llvm::ConstantInt::get(LongTy,
1613                                td.getTypeSizeInBits(ClassTy) /
1614                                  CGM.getContext().getCharWidth()));
1615   } else
1616     Elements.push_back(InstanceSize);
1617   Elements.push_back(IVars);
1618   Elements.push_back(Methods);
1619   Elements.push_back(NULLPtr);
1620   Elements.push_back(NULLPtr);
1621   Elements.push_back(NULLPtr);
1622   Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
1623   Elements.push_back(NULLPtr);
1624   Elements.push_back(llvm::ConstantInt::get(LongTy, 1));
1625   Elements.push_back(IvarOffsets);
1626   Elements.push_back(Properties);
1627   Elements.push_back(StrongIvarBitmap);
1628   Elements.push_back(WeakIvarBitmap);
1629   // Create an instance of the structure
1630   // This is now an externally visible symbol, so that we can speed up class
1631   // messages in the next ABI.  We may already have some weak references to
1632   // this, so check and fix them properly.
1633   std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
1634           std::string(Name));
1635   llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
1636   llvm::Constant *Class = MakeGlobal(ClassTy, Elements, ClassSym,
1637           llvm::GlobalValue::ExternalLinkage);
1638   if (ClassRef) {
1639       ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
1640                   ClassRef->getType()));
1641       ClassRef->removeFromParent();
1642       Class->setName(ClassSym);
1643   }
1644   return Class;
1645 }
1646
1647 llvm::Constant *CGObjCGNU::
1648 GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
1649                            ArrayRef<llvm::Constant *> MethodTypes) {
1650   // Get the method structure type.
1651   llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
1652     PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1653     PtrToInt8Ty,
1654     NULL);
1655   std::vector<llvm::Constant*> Methods;
1656   std::vector<llvm::Constant*> Elements;
1657   for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1658     Elements.clear();
1659     Elements.push_back(MethodNames[i]);
1660     Elements.push_back(MethodTypes[i]);
1661     Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
1662   }
1663   llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
1664       MethodNames.size());
1665   llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
1666                                                    Methods);
1667   llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
1668       IntTy, ObjCMethodArrayTy, NULL);
1669   Methods.clear();
1670   Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
1671   Methods.push_back(Array);
1672   return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1673 }
1674
1675 // Create the protocol list structure used in classes, categories and so on
1676 llvm::Constant *CGObjCGNU::GenerateProtocolList(ArrayRef<std::string>Protocols){
1677   llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
1678       Protocols.size());
1679   llvm::StructType *ProtocolListTy = llvm::StructType::get(
1680       PtrTy, //Should be a recurisve pointer, but it's always NULL here.
1681       SizeTy,
1682       ProtocolArrayTy,
1683       NULL);
1684   std::vector<llvm::Constant*> Elements;
1685   for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1686       iter != endIter ; iter++) {
1687     llvm::Constant *protocol = 0;
1688     llvm::StringMap<llvm::Constant*>::iterator value =
1689       ExistingProtocols.find(*iter);
1690     if (value == ExistingProtocols.end()) {
1691       protocol = GenerateEmptyProtocol(*iter);
1692     } else {
1693       protocol = value->getValue();
1694     }
1695     llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
1696                                                            PtrToInt8Ty);
1697     Elements.push_back(Ptr);
1698   }
1699   llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1700       Elements);
1701   Elements.clear();
1702   Elements.push_back(NULLPtr);
1703   Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
1704   Elements.push_back(ProtocolArray);
1705   return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1706 }
1707
1708 llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
1709                                             const ObjCProtocolDecl *PD) {
1710   llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
1711   llvm::Type *T =
1712     CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
1713   return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
1714 }
1715
1716 llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1717   const std::string &ProtocolName) {
1718   SmallVector<std::string, 0> EmptyStringVector;
1719   SmallVector<llvm::Constant*, 0> EmptyConstantVector;
1720
1721   llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
1722   llvm::Constant *MethodList =
1723     GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1724   // Protocols are objects containing lists of the methods implemented and
1725   // protocols adopted.
1726   llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
1727       PtrToInt8Ty,
1728       ProtocolList->getType(),
1729       MethodList->getType(),
1730       MethodList->getType(),
1731       MethodList->getType(),
1732       MethodList->getType(),
1733       NULL);
1734   std::vector<llvm::Constant*> Elements;
1735   // The isa pointer must be set to a magic number so the runtime knows it's
1736   // the correct layout.
1737   Elements.push_back(llvm::ConstantExpr::getIntToPtr(
1738         llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1739   Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1740   Elements.push_back(ProtocolList);
1741   Elements.push_back(MethodList);
1742   Elements.push_back(MethodList);
1743   Elements.push_back(MethodList);
1744   Elements.push_back(MethodList);
1745   return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
1746 }
1747
1748 void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1749   ASTContext &Context = CGM.getContext();
1750   std::string ProtocolName = PD->getNameAsString();
1751   
1752   // Use the protocol definition, if there is one.
1753   if (const ObjCProtocolDecl *Def = PD->getDefinition())
1754     PD = Def;
1755
1756   SmallVector<std::string, 16> Protocols;
1757   for (const auto *PI : PD->protocols())
1758     Protocols.push_back(PI->getNameAsString());
1759   SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1760   SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1761   SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1762   SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
1763   for (const auto *I : PD->instance_methods()) {
1764     std::string TypeStr;
1765     Context.getObjCEncodingForMethodDecl(I, TypeStr);
1766     if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
1767       OptionalInstanceMethodNames.push_back(
1768           MakeConstantString(I->getSelector().getAsString()));
1769       OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1770     } else {
1771       InstanceMethodNames.push_back(
1772           MakeConstantString(I->getSelector().getAsString()));
1773       InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1774     }
1775   }
1776   // Collect information about class methods:
1777   SmallVector<llvm::Constant*, 16> ClassMethodNames;
1778   SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1779   SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1780   SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
1781   for (const auto *I : PD->class_methods()) {
1782     std::string TypeStr;
1783     Context.getObjCEncodingForMethodDecl(I,TypeStr);
1784     if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
1785       OptionalClassMethodNames.push_back(
1786           MakeConstantString(I->getSelector().getAsString()));
1787       OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1788     } else {
1789       ClassMethodNames.push_back(
1790           MakeConstantString(I->getSelector().getAsString()));
1791       ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1792     }
1793   }
1794
1795   llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1796   llvm::Constant *InstanceMethodList =
1797     GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1798   llvm::Constant *ClassMethodList =
1799     GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
1800   llvm::Constant *OptionalInstanceMethodList =
1801     GenerateProtocolMethodList(OptionalInstanceMethodNames,
1802             OptionalInstanceMethodTypes);
1803   llvm::Constant *OptionalClassMethodList =
1804     GenerateProtocolMethodList(OptionalClassMethodNames,
1805             OptionalClassMethodTypes);
1806
1807   // Property metadata: name, attributes, isSynthesized, setter name, setter
1808   // types, getter name, getter types.
1809   // The isSynthesized value is always set to 0 in a protocol.  It exists to
1810   // simplify the runtime library by allowing it to use the same data
1811   // structures for protocol metadata everywhere.
1812   llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
1813           PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
1814           PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, NULL);
1815   std::vector<llvm::Constant*> Properties;
1816   std::vector<llvm::Constant*> OptionalProperties;
1817
1818   // Add all of the property methods need adding to the method list and to the
1819   // property metadata list.
1820   for (auto *property : PD->properties()) {
1821     std::vector<llvm::Constant*> Fields;
1822
1823     Fields.push_back(MakePropertyEncodingString(property, 0));
1824     PushPropertyAttributes(Fields, property);
1825
1826     if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1827       std::string TypeStr;
1828       Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1829       llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1830       InstanceMethodTypes.push_back(TypeEncoding);
1831       Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1832       Fields.push_back(TypeEncoding);
1833     } else {
1834       Fields.push_back(NULLPtr);
1835       Fields.push_back(NULLPtr);
1836     }
1837     if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1838       std::string TypeStr;
1839       Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1840       llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1841       InstanceMethodTypes.push_back(TypeEncoding);
1842       Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1843       Fields.push_back(TypeEncoding);
1844     } else {
1845       Fields.push_back(NULLPtr);
1846       Fields.push_back(NULLPtr);
1847     }
1848     if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1849       OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1850     } else {
1851       Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1852     }
1853   }
1854   llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1855       llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1856   llvm::Constant* PropertyListInitFields[] =
1857     {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1858
1859   llvm::Constant *PropertyListInit =
1860       llvm::ConstantStruct::getAnon(PropertyListInitFields);
1861   llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1862       PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1863       PropertyListInit, ".objc_property_list");
1864
1865   llvm::Constant *OptionalPropertyArray =
1866       llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1867           OptionalProperties.size()) , OptionalProperties);
1868   llvm::Constant* OptionalPropertyListInitFields[] = {
1869       llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1870       OptionalPropertyArray };
1871
1872   llvm::Constant *OptionalPropertyListInit =
1873       llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
1874   llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1875           OptionalPropertyListInit->getType(), false,
1876           llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1877           ".objc_property_list");
1878
1879   // Protocols are objects containing lists of the methods implemented and
1880   // protocols adopted.
1881   llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
1882       PtrToInt8Ty,
1883       ProtocolList->getType(),
1884       InstanceMethodList->getType(),
1885       ClassMethodList->getType(),
1886       OptionalInstanceMethodList->getType(),
1887       OptionalClassMethodList->getType(),
1888       PropertyList->getType(),
1889       OptionalPropertyList->getType(),
1890       NULL);
1891   std::vector<llvm::Constant*> Elements;
1892   // The isa pointer must be set to a magic number so the runtime knows it's
1893   // the correct layout.
1894   Elements.push_back(llvm::ConstantExpr::getIntToPtr(
1895         llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1896   Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1897   Elements.push_back(ProtocolList);
1898   Elements.push_back(InstanceMethodList);
1899   Elements.push_back(ClassMethodList);
1900   Elements.push_back(OptionalInstanceMethodList);
1901   Elements.push_back(OptionalClassMethodList);
1902   Elements.push_back(PropertyList);
1903   Elements.push_back(OptionalPropertyList);
1904   ExistingProtocols[ProtocolName] =
1905     llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
1906           ".objc_protocol"), IdTy);
1907 }
1908 void CGObjCGNU::GenerateProtocolHolderCategory() {
1909   // Collect information about instance methods
1910   SmallVector<Selector, 1> MethodSels;
1911   SmallVector<llvm::Constant*, 1> MethodTypes;
1912
1913   std::vector<llvm::Constant*> Elements;
1914   const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1915   const std::string CategoryName = "AnotherHack";
1916   Elements.push_back(MakeConstantString(CategoryName));
1917   Elements.push_back(MakeConstantString(ClassName));
1918   // Instance method list
1919   Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1920           ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1921   // Class method list
1922   Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1923           ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1924   // Protocol list
1925   llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1926       ExistingProtocols.size());
1927   llvm::StructType *ProtocolListTy = llvm::StructType::get(
1928       PtrTy, //Should be a recurisve pointer, but it's always NULL here.
1929       SizeTy,
1930       ProtocolArrayTy,
1931       NULL);
1932   std::vector<llvm::Constant*> ProtocolElements;
1933   for (llvm::StringMapIterator<llvm::Constant*> iter =
1934        ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1935        iter != endIter ; iter++) {
1936     llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1937             PtrTy);
1938     ProtocolElements.push_back(Ptr);
1939   }
1940   llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1941       ProtocolElements);
1942   ProtocolElements.clear();
1943   ProtocolElements.push_back(NULLPtr);
1944   ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1945               ExistingProtocols.size()));
1946   ProtocolElements.push_back(ProtocolArray);
1947   Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1948                   ProtocolElements, ".objc_protocol_list"), PtrTy));
1949   Categories.push_back(llvm::ConstantExpr::getBitCast(
1950         MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
1951             PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1952 }
1953
1954 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
1955 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
1956 /// bits set to their values, LSB first, while larger ones are stored in a
1957 /// structure of this / form:
1958 /// 
1959 /// struct { int32_t length; int32_t values[length]; };
1960 ///
1961 /// The values in the array are stored in host-endian format, with the least
1962 /// significant bit being assumed to come first in the bitfield.  Therefore, a
1963 /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
1964 /// bitfield / with the 63rd bit set will be 1<<64.
1965 llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
1966   int bitCount = bits.size();
1967   int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
1968   if (bitCount < ptrBits) {
1969     uint64_t val = 1;
1970     for (int i=0 ; i<bitCount ; ++i) {
1971       if (bits[i]) val |= 1ULL<<(i+1);
1972     }
1973     return llvm::ConstantInt::get(IntPtrTy, val);
1974   }
1975   SmallVector<llvm::Constant *, 8> values;
1976   int v=0;
1977   while (v < bitCount) {
1978     int32_t word = 0;
1979     for (int i=0 ; (i<32) && (v<bitCount)  ; ++i) {
1980       if (bits[v]) word |= 1<<i;
1981       v++;
1982     }
1983     values.push_back(llvm::ConstantInt::get(Int32Ty, word));
1984   }
1985   llvm::ArrayType *arrayTy = llvm::ArrayType::get(Int32Ty, values.size());
1986   llvm::Constant *array = llvm::ConstantArray::get(arrayTy, values);
1987   llvm::Constant *fields[2] = {
1988       llvm::ConstantInt::get(Int32Ty, values.size()),
1989       array };
1990   llvm::Constant *GS = MakeGlobal(llvm::StructType::get(Int32Ty, arrayTy,
1991         NULL), fields);
1992   llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
1993   return ptr;
1994 }
1995
1996 void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
1997   std::string ClassName = OCD->getClassInterface()->getNameAsString();
1998   std::string CategoryName = OCD->getNameAsString();
1999   // Collect information about instance methods
2000   SmallVector<Selector, 16> InstanceMethodSels;
2001   SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
2002   for (const auto *I : OCD->instance_methods()) {
2003     InstanceMethodSels.push_back(I->getSelector());
2004     std::string TypeStr;
2005     CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr);
2006     InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
2007   }
2008
2009   // Collect information about class methods
2010   SmallVector<Selector, 16> ClassMethodSels;
2011   SmallVector<llvm::Constant*, 16> ClassMethodTypes;
2012   for (const auto *I : OCD->class_methods()) {
2013     ClassMethodSels.push_back(I->getSelector());
2014     std::string TypeStr;
2015     CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr);
2016     ClassMethodTypes.push_back(MakeConstantString(TypeStr));
2017   }
2018
2019   // Collect the names of referenced protocols
2020   SmallVector<std::string, 16> Protocols;
2021   const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
2022   const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
2023   for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
2024        E = Protos.end(); I != E; ++I)
2025     Protocols.push_back((*I)->getNameAsString());
2026
2027   std::vector<llvm::Constant*> Elements;
2028   Elements.push_back(MakeConstantString(CategoryName));
2029   Elements.push_back(MakeConstantString(ClassName));
2030   // Instance method list
2031   Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
2032           ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
2033           false), PtrTy));
2034   // Class method list
2035   Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
2036           ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
2037         PtrTy));
2038   // Protocol list
2039   Elements.push_back(llvm::ConstantExpr::getBitCast(
2040         GenerateProtocolList(Protocols), PtrTy));
2041   Categories.push_back(llvm::ConstantExpr::getBitCast(
2042         MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
2043             PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
2044 }
2045
2046 llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
2047         SmallVectorImpl<Selector> &InstanceMethodSels,
2048         SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
2049   ASTContext &Context = CGM.getContext();
2050   // Property metadata: name, attributes, attributes2, padding1, padding2,
2051   // setter name, setter types, getter name, getter types.
2052   llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
2053           PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
2054           PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, NULL);
2055   std::vector<llvm::Constant*> Properties;
2056
2057   // Add all of the property methods need adding to the method list and to the
2058   // property metadata list.
2059   for (auto *propertyImpl : OID->property_impls()) {
2060     std::vector<llvm::Constant*> Fields;
2061     ObjCPropertyDecl *property = propertyImpl->getPropertyDecl();
2062     bool isSynthesized = (propertyImpl->getPropertyImplementation() == 
2063         ObjCPropertyImplDecl::Synthesize);
2064     bool isDynamic = (propertyImpl->getPropertyImplementation() == 
2065         ObjCPropertyImplDecl::Dynamic);
2066
2067     Fields.push_back(MakePropertyEncodingString(property, OID));
2068     PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
2069     if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
2070       std::string TypeStr;
2071       Context.getObjCEncodingForMethodDecl(getter,TypeStr);
2072       llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
2073       if (isSynthesized) {
2074         InstanceMethodTypes.push_back(TypeEncoding);
2075         InstanceMethodSels.push_back(getter->getSelector());
2076       }
2077       Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
2078       Fields.push_back(TypeEncoding);
2079     } else {
2080       Fields.push_back(NULLPtr);
2081       Fields.push_back(NULLPtr);
2082     }
2083     if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
2084       std::string TypeStr;
2085       Context.getObjCEncodingForMethodDecl(setter,TypeStr);
2086       llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
2087       if (isSynthesized) {
2088         InstanceMethodTypes.push_back(TypeEncoding);
2089         InstanceMethodSels.push_back(setter->getSelector());
2090       }
2091       Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
2092       Fields.push_back(TypeEncoding);
2093     } else {
2094       Fields.push_back(NULLPtr);
2095       Fields.push_back(NULLPtr);
2096     }
2097     Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
2098   }
2099   llvm::ArrayType *PropertyArrayTy =
2100       llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
2101   llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
2102           Properties);
2103   llvm::Constant* PropertyListInitFields[] =
2104     {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
2105
2106   llvm::Constant *PropertyListInit =
2107       llvm::ConstantStruct::getAnon(PropertyListInitFields);
2108   return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
2109           llvm::GlobalValue::InternalLinkage, PropertyListInit,
2110           ".objc_property_list");
2111 }
2112
2113 void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
2114   // Get the class declaration for which the alias is specified.
2115   ObjCInterfaceDecl *ClassDecl =
2116     const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
2117   std::string ClassName = ClassDecl->getNameAsString();
2118   std::string AliasName = OAD->getNameAsString();
2119   ClassAliases.push_back(ClassAliasPair(ClassName,AliasName));
2120 }
2121
2122 void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
2123   ASTContext &Context = CGM.getContext();
2124
2125   // Get the superclass name.
2126   const ObjCInterfaceDecl * SuperClassDecl =
2127     OID->getClassInterface()->getSuperClass();
2128   std::string SuperClassName;
2129   if (SuperClassDecl) {
2130     SuperClassName = SuperClassDecl->getNameAsString();
2131     EmitClassRef(SuperClassName);
2132   }
2133
2134   // Get the class name
2135   ObjCInterfaceDecl *ClassDecl =
2136     const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
2137   std::string ClassName = ClassDecl->getNameAsString();
2138   // Emit the symbol that is used to generate linker errors if this class is
2139   // referenced in other modules but not declared.
2140   std::string classSymbolName = "__objc_class_name_" + ClassName;
2141   if (llvm::GlobalVariable *symbol =
2142       TheModule.getGlobalVariable(classSymbolName)) {
2143     symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
2144   } else {
2145     new llvm::GlobalVariable(TheModule, LongTy, false,
2146     llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
2147     classSymbolName);
2148   }
2149
2150   // Get the size of instances.
2151   int instanceSize = 
2152     Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
2153
2154   // Collect information about instance variables.
2155   SmallVector<llvm::Constant*, 16> IvarNames;
2156   SmallVector<llvm::Constant*, 16> IvarTypes;
2157   SmallVector<llvm::Constant*, 16> IvarOffsets;
2158
2159   std::vector<llvm::Constant*> IvarOffsetValues;
2160   SmallVector<bool, 16> WeakIvars;
2161   SmallVector<bool, 16> StrongIvars;
2162
2163   int superInstanceSize = !SuperClassDecl ? 0 :
2164     Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
2165   // For non-fragile ivars, set the instance size to 0 - {the size of just this
2166   // class}.  The runtime will then set this to the correct value on load.
2167   if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2168     instanceSize = 0 - (instanceSize - superInstanceSize);
2169   }
2170
2171   for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2172        IVD = IVD->getNextIvar()) {
2173       // Store the name
2174       IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
2175       // Get the type encoding for this ivar
2176       std::string TypeStr;
2177       Context.getObjCEncodingForType(IVD->getType(), TypeStr);
2178       IvarTypes.push_back(MakeConstantString(TypeStr));
2179       // Get the offset
2180       uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
2181       uint64_t Offset = BaseOffset;
2182       if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2183         Offset = BaseOffset - superInstanceSize;
2184       }
2185       llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
2186       // Create the direct offset value
2187       std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
2188           IVD->getNameAsString();
2189       llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
2190       if (OffsetVar) {
2191         OffsetVar->setInitializer(OffsetValue);
2192         // If this is the real definition, change its linkage type so that
2193         // different modules will use this one, rather than their private
2194         // copy.
2195         OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
2196       } else
2197         OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
2198           false, llvm::GlobalValue::ExternalLinkage,
2199           OffsetValue,
2200           "__objc_ivar_offset_value_" + ClassName +"." +
2201           IVD->getNameAsString());
2202       IvarOffsets.push_back(OffsetValue);
2203       IvarOffsetValues.push_back(OffsetVar);
2204       Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
2205       switch (lt) {
2206         case Qualifiers::OCL_Strong:
2207           StrongIvars.push_back(true);
2208           WeakIvars.push_back(false);
2209           break;
2210         case Qualifiers::OCL_Weak:
2211           StrongIvars.push_back(false);
2212           WeakIvars.push_back(true);
2213           break;
2214         default:
2215           StrongIvars.push_back(false);
2216           WeakIvars.push_back(false);
2217       }
2218   }
2219   llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
2220   llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
2221   llvm::GlobalVariable *IvarOffsetArray =
2222     MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
2223
2224
2225   // Collect information about instance methods
2226   SmallVector<Selector, 16> InstanceMethodSels;
2227   SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
2228   for (const auto *I : OID->instance_methods()) {
2229     InstanceMethodSels.push_back(I->getSelector());
2230     std::string TypeStr;
2231     Context.getObjCEncodingForMethodDecl(I,TypeStr);
2232     InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
2233   }
2234
2235   llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2236           InstanceMethodTypes);
2237
2238
2239   // Collect information about class methods
2240   SmallVector<Selector, 16> ClassMethodSels;
2241   SmallVector<llvm::Constant*, 16> ClassMethodTypes;
2242   for (const auto *I : OID->class_methods()) {
2243     ClassMethodSels.push_back(I->getSelector());
2244     std::string TypeStr;
2245     Context.getObjCEncodingForMethodDecl(I,TypeStr);
2246     ClassMethodTypes.push_back(MakeConstantString(TypeStr));
2247   }
2248   // Collect the names of referenced protocols
2249   SmallVector<std::string, 16> Protocols;
2250   for (const auto *I : ClassDecl->protocols())
2251     Protocols.push_back(I->getNameAsString());
2252
2253   // Get the superclass pointer.
2254   llvm::Constant *SuperClass;
2255   if (!SuperClassName.empty()) {
2256     SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2257   } else {
2258     SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
2259   }
2260   // Empty vector used to construct empty method lists
2261   SmallVector<llvm::Constant*, 1>  empty;
2262   // Generate the method and instance variable lists
2263   llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
2264       InstanceMethodSels, InstanceMethodTypes, false);
2265   llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
2266       ClassMethodSels, ClassMethodTypes, true);
2267   llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2268       IvarOffsets);
2269   // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
2270   // we emit a symbol containing the offset for each ivar in the class.  This
2271   // allows code compiled for the non-Fragile ABI to inherit from code compiled
2272   // for the legacy ABI, without causing problems.  The converse is also
2273   // possible, but causes all ivar accesses to be fragile.
2274
2275   // Offset pointer for getting at the correct field in the ivar list when
2276   // setting up the alias.  These are: The base address for the global, the
2277   // ivar array (second field), the ivar in this list (set for each ivar), and
2278   // the offset (third field in ivar structure)
2279   llvm::Type *IndexTy = Int32Ty;
2280   llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
2281       llvm::ConstantInt::get(IndexTy, 1), 0,
2282       llvm::ConstantInt::get(IndexTy, 2) };
2283
2284   unsigned ivarIndex = 0;
2285   for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2286        IVD = IVD->getNextIvar()) {
2287       const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
2288           + IVD->getNameAsString();
2289       offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
2290       // Get the correct ivar field
2291       llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
2292               IvarList, offsetPointerIndexes);
2293       // Get the existing variable, if one exists.
2294       llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2295       if (offset) {
2296         offset->setInitializer(offsetValue);
2297         // If this is the real definition, change its linkage type so that
2298         // different modules will use this one, rather than their private
2299         // copy.
2300         offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
2301       } else {
2302         // Add a new alias if there isn't one already.
2303         offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2304                 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2305         (void) offset; // Silence dead store warning.
2306       }
2307       ++ivarIndex;
2308   }
2309   llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
2310   //Generate metaclass for class methods
2311   llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
2312       NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
2313         empty, empty, empty), ClassMethodList, NULLPtr,
2314       NULLPtr, NULLPtr, ZeroPtr, ZeroPtr, true);
2315
2316   // Generate the class structure
2317   llvm::Constant *ClassStruct =
2318     GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
2319                            ClassName.c_str(), 0,
2320       llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
2321       MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
2322       Properties, StrongIvarBitmap, WeakIvarBitmap);
2323
2324   // Resolve the class aliases, if they exist.
2325   if (ClassPtrAlias) {
2326     ClassPtrAlias->replaceAllUsesWith(
2327         llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
2328     ClassPtrAlias->eraseFromParent();
2329     ClassPtrAlias = 0;
2330   }
2331   if (MetaClassPtrAlias) {
2332     MetaClassPtrAlias->replaceAllUsesWith(
2333         llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
2334     MetaClassPtrAlias->eraseFromParent();
2335     MetaClassPtrAlias = 0;
2336   }
2337
2338   // Add class structure to list to be added to the symtab later
2339   ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
2340   Classes.push_back(ClassStruct);
2341 }
2342
2343
2344 llvm::Function *CGObjCGNU::ModuleInitFunction() {
2345   // Only emit an ObjC load function if no Objective-C stuff has been called
2346   if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
2347       ExistingProtocols.empty() && SelectorTable.empty())
2348     return NULL;
2349
2350   // Add all referenced protocols to a category.
2351   GenerateProtocolHolderCategory();
2352
2353   llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
2354           SelectorTy->getElementType());
2355   llvm::Type *SelStructPtrTy = SelectorTy;
2356   if (SelStructTy == 0) {
2357     SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, NULL);
2358     SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
2359   }
2360
2361   std::vector<llvm::Constant*> Elements;
2362   llvm::Constant *Statics = NULLPtr;
2363   // Generate statics list:
2364   if (ConstantStrings.size()) {
2365     llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
2366         ConstantStrings.size() + 1);
2367     ConstantStrings.push_back(NULLPtr);
2368
2369     StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
2370
2371     if (StringClass.empty()) StringClass = "NXConstantString";
2372
2373     Elements.push_back(MakeConstantString(StringClass,
2374                 ".objc_static_class_name"));
2375     Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
2376        ConstantStrings));
2377     llvm::StructType *StaticsListTy =
2378       llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
2379     llvm::Type *StaticsListPtrTy =
2380       llvm::PointerType::getUnqual(StaticsListTy);
2381     Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
2382     llvm::ArrayType *StaticsListArrayTy =
2383       llvm::ArrayType::get(StaticsListPtrTy, 2);
2384     Elements.clear();
2385     Elements.push_back(Statics);
2386     Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
2387     Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
2388     Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
2389   }
2390   // Array of classes, categories, and constant objects
2391   llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
2392       Classes.size() + Categories.size()  + 2);
2393   llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
2394                                                      llvm::Type::getInt16Ty(VMContext),
2395                                                      llvm::Type::getInt16Ty(VMContext),
2396                                                      ClassListTy, NULL);
2397
2398   Elements.clear();
2399   // Pointer to an array of selectors used in this module.
2400   std::vector<llvm::Constant*> Selectors;
2401   std::vector<llvm::GlobalAlias*> SelectorAliases;
2402   for (SelectorMap::iterator iter = SelectorTable.begin(),
2403       iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2404
2405     std::string SelNameStr = iter->first.getAsString();
2406     llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2407
2408     SmallVectorImpl<TypedSelector> &Types = iter->second;
2409     for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
2410         e = Types.end() ; i!=e ; i++) {
2411
2412       llvm::Constant *SelectorTypeEncoding = NULLPtr;
2413       if (!i->first.empty())
2414         SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2415
2416       Elements.push_back(SelName);
2417       Elements.push_back(SelectorTypeEncoding);
2418       Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2419       Elements.clear();
2420
2421       // Store the selector alias for later replacement
2422       SelectorAliases.push_back(i->second);
2423     }
2424   }
2425   unsigned SelectorCount = Selectors.size();
2426   // NULL-terminate the selector list.  This should not actually be required,
2427   // because the selector list has a length field.  Unfortunately, the GCC
2428   // runtime decides to ignore the length field and expects a NULL terminator,
2429   // and GCC cooperates with this by always setting the length to 0.
2430   Elements.push_back(NULLPtr);
2431   Elements.push_back(NULLPtr);
2432   Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2433   Elements.clear();
2434
2435   // Number of static selectors
2436   Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2437   llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
2438           ".objc_selector_list");
2439   Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
2440     SelStructPtrTy));
2441
2442   // Now that all of the static selectors exist, create pointers to them.
2443   for (unsigned int i=0 ; i<SelectorCount ; i++) {
2444
2445     llvm::Constant *Idxs[] = {Zeros[0],
2446       llvm::ConstantInt::get(Int32Ty, i), Zeros[0]};
2447     // FIXME: We're generating redundant loads and stores here!
2448     llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
2449         makeArrayRef(Idxs, 2));
2450     // If selectors are defined as an opaque type, cast the pointer to this
2451     // type.
2452     SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
2453     SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2454     SelectorAliases[i]->eraseFromParent();
2455   }
2456
2457   // Number of classes defined.
2458   Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
2459         Classes.size()));
2460   // Number of categories defined
2461   Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
2462         Categories.size()));
2463   // Create an array of classes, then categories, then static object instances
2464   Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2465   //  NULL-terminated list of static object instances (mainly constant strings)
2466   Classes.push_back(Statics);
2467   Classes.push_back(NULLPtr);
2468   llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
2469   Elements.push_back(ClassList);
2470   // Construct the symbol table
2471   llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2472
2473   // The symbol table is contained in a module which has some version-checking
2474   // constants
2475   llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
2476       PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), 
2477       (RuntimeVersion >= 10) ? IntTy : NULL, NULL);
2478   Elements.clear();
2479   // Runtime version, used for ABI compatibility checking.
2480   Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
2481   // sizeof(ModuleTy)
2482   llvm::DataLayout td(&TheModule);
2483   Elements.push_back(
2484     llvm::ConstantInt::get(LongTy,
2485                            td.getTypeSizeInBits(ModuleTy) /
2486                              CGM.getContext().getCharWidth()));
2487
2488   // The path to the source file where this module was declared
2489   SourceManager &SM = CGM.getContext().getSourceManager();
2490   const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2491   std::string path =
2492     std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2493   Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
2494   Elements.push_back(SymTab);
2495
2496   if (RuntimeVersion >= 10)
2497     switch (CGM.getLangOpts().getGC()) {
2498       case LangOptions::GCOnly:
2499         Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
2500         break;
2501       case LangOptions::NonGC:
2502         if (CGM.getLangOpts().ObjCAutoRefCount)
2503           Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2504         else
2505           Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
2506         break;
2507       case LangOptions::HybridGC:
2508           Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2509         break;
2510     }
2511
2512   llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2513
2514   // Create the load function calling the runtime entry point with the module
2515   // structure
2516   llvm::Function * LoadFunction = llvm::Function::Create(
2517       llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
2518       llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2519       &TheModule);
2520   llvm::BasicBlock *EntryBB =
2521       llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
2522   CGBuilderTy Builder(VMContext);
2523   Builder.SetInsertPoint(EntryBB);
2524
2525   llvm::FunctionType *FT =
2526     llvm::FunctionType::get(Builder.getVoidTy(),
2527                             llvm::PointerType::getUnqual(ModuleTy), true);
2528   llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
2529   Builder.CreateCall(Register, Module);
2530
2531   if (!ClassAliases.empty()) {
2532     llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
2533     llvm::FunctionType *RegisterAliasTy =
2534       llvm::FunctionType::get(Builder.getVoidTy(),
2535                               ArgTypes, false);
2536     llvm::Function *RegisterAlias = llvm::Function::Create(
2537       RegisterAliasTy,
2538       llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
2539       &TheModule);
2540     llvm::BasicBlock *AliasBB =
2541       llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
2542     llvm::BasicBlock *NoAliasBB =
2543       llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
2544
2545     // Branch based on whether the runtime provided class_registerAlias_np()
2546     llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
2547             llvm::Constant::getNullValue(RegisterAlias->getType()));
2548     Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
2549
2550     // The true branch (has alias registration function):
2551     Builder.SetInsertPoint(AliasBB);
2552     // Emit alias registration calls:
2553     for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
2554        iter != ClassAliases.end(); ++iter) {
2555        llvm::Constant *TheClass =
2556          TheModule.getGlobalVariable(("_OBJC_CLASS_" + iter->first).c_str(),
2557             true);
2558        if (0 != TheClass) {
2559          TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
2560          Builder.CreateCall2(RegisterAlias, TheClass,
2561             MakeConstantString(iter->second));
2562        }
2563     }
2564     // Jump to end:
2565     Builder.CreateBr(NoAliasBB);
2566
2567     // Missing alias registration function, just return from the function:
2568     Builder.SetInsertPoint(NoAliasBB);
2569   }
2570   Builder.CreateRetVoid();
2571
2572   return LoadFunction;
2573 }
2574
2575 llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
2576                                           const ObjCContainerDecl *CD) {
2577   const ObjCCategoryImplDecl *OCD =
2578     dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
2579   StringRef CategoryName = OCD ? OCD->getName() : "";
2580   StringRef ClassName = CD->getName();
2581   Selector MethodName = OMD->getSelector();
2582   bool isClassMethod = !OMD->isInstanceMethod();
2583
2584   CodeGenTypes &Types = CGM.getTypes();
2585   llvm::FunctionType *MethodTy =
2586     Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
2587   std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2588       MethodName, isClassMethod);
2589
2590   llvm::Function *Method
2591     = llvm::Function::Create(MethodTy,
2592                              llvm::GlobalValue::InternalLinkage,
2593                              FunctionName,
2594                              &TheModule);
2595   return Method;
2596 }
2597
2598 llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
2599   return GetPropertyFn;
2600 }
2601
2602 llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
2603   return SetPropertyFn;
2604 }
2605
2606 llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
2607                                                            bool copy) {
2608   return 0;
2609 }
2610
2611 llvm::Constant *CGObjCGNU::GetGetStructFunction() {
2612   return GetStructPropertyFn;
2613 }
2614 llvm::Constant *CGObjCGNU::GetSetStructFunction() {
2615   return SetStructPropertyFn;
2616 }
2617 llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
2618   return 0;
2619 }
2620 llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
2621   return 0;
2622 }
2623
2624 llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
2625   return EnumerationMutationFn;
2626 }
2627
2628 void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
2629                                      const ObjCAtSynchronizedStmt &S) {
2630   EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
2631 }
2632
2633
2634 void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
2635                             const ObjCAtTryStmt &S) {
2636   // Unlike the Apple non-fragile runtimes, which also uses
2637   // unwind-based zero cost exceptions, the GNU Objective C runtime's
2638   // EH support isn't a veneer over C++ EH.  Instead, exception
2639   // objects are created by objc_exception_throw and destroyed by
2640   // the personality function; this avoids the need for bracketing
2641   // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2642   // (or even _Unwind_DeleteException), but probably doesn't
2643   // interoperate very well with foreign exceptions.
2644   //
2645   // In Objective-C++ mode, we actually emit something equivalent to the C++
2646   // exception handler. 
2647   EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2648   return ;
2649 }
2650
2651 void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
2652                               const ObjCAtThrowStmt &S,
2653                               bool ClearInsertionPoint) {
2654   llvm::Value *ExceptionAsObject;
2655
2656   if (const Expr *ThrowExpr = S.getThrowExpr()) {
2657     llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
2658     ExceptionAsObject = Exception;
2659   } else {
2660     assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
2661            "Unexpected rethrow outside @catch block.");
2662     ExceptionAsObject = CGF.ObjCEHValueStack.back();
2663   }
2664   ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
2665   llvm::CallSite Throw =
2666       CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
2667   Throw.setDoesNotReturn();
2668   CGF.Builder.CreateUnreachable();
2669   if (ClearInsertionPoint)
2670     CGF.Builder.ClearInsertionPoint();
2671 }
2672
2673 llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
2674                                           llvm::Value *AddrWeakObj) {
2675   CGBuilderTy &B = CGF.Builder;
2676   AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
2677   return B.CreateCall(WeakReadFn, AddrWeakObj);
2678 }
2679
2680 void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
2681                                    llvm::Value *src, llvm::Value *dst) {
2682   CGBuilderTy &B = CGF.Builder;
2683   src = EnforceType(B, src, IdTy);
2684   dst = EnforceType(B, dst, PtrToIdTy);
2685   B.CreateCall2(WeakAssignFn, src, dst);
2686 }
2687
2688 void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
2689                                      llvm::Value *src, llvm::Value *dst,
2690                                      bool threadlocal) {
2691   CGBuilderTy &B = CGF.Builder;
2692   src = EnforceType(B, src, IdTy);
2693   dst = EnforceType(B, dst, PtrToIdTy);
2694   if (!threadlocal)
2695     B.CreateCall2(GlobalAssignFn, src, dst);
2696   else
2697     // FIXME. Add threadloca assign API
2698     llvm_unreachable("EmitObjCGlobalAssign - Threal Local API NYI");
2699 }
2700
2701 void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
2702                                    llvm::Value *src, llvm::Value *dst,
2703                                    llvm::Value *ivarOffset) {
2704   CGBuilderTy &B = CGF.Builder;
2705   src = EnforceType(B, src, IdTy);
2706   dst = EnforceType(B, dst, IdTy);
2707   B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
2708 }
2709
2710 void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
2711                                          llvm::Value *src, llvm::Value *dst) {
2712   CGBuilderTy &B = CGF.Builder;
2713   src = EnforceType(B, src, IdTy);
2714   dst = EnforceType(B, dst, PtrToIdTy);
2715   B.CreateCall2(StrongCastAssignFn, src, dst);
2716 }
2717
2718 void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
2719                                          llvm::Value *DestPtr,
2720                                          llvm::Value *SrcPtr,
2721                                          llvm::Value *Size) {
2722   CGBuilderTy &B = CGF.Builder;
2723   DestPtr = EnforceType(B, DestPtr, PtrTy);
2724   SrcPtr = EnforceType(B, SrcPtr, PtrTy);
2725
2726   B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
2727 }
2728
2729 llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2730                               const ObjCInterfaceDecl *ID,
2731                               const ObjCIvarDecl *Ivar) {
2732   const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2733     + '.' + Ivar->getNameAsString();
2734   // Emit the variable and initialize it with what we think the correct value
2735   // is.  This allows code compiled with non-fragile ivars to work correctly
2736   // when linked against code which isn't (most of the time).
2737   llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2738   if (!IvarOffsetPointer) {
2739     // This will cause a run-time crash if we accidentally use it.  A value of
2740     // 0 would seem more sensible, but will silently overwrite the isa pointer
2741     // causing a great deal of confusion.
2742     uint64_t Offset = -1;
2743     // We can't call ComputeIvarBaseOffset() here if we have the
2744     // implementation, because it will create an invalid ASTRecordLayout object
2745     // that we are then stuck with forever, so we only initialize the ivar
2746     // offset variable with a guess if we only have the interface.  The
2747     // initializer will be reset later anyway, when we are generating the class
2748     // description.
2749     if (!CGM.getContext().getObjCImplementation(
2750               const_cast<ObjCInterfaceDecl *>(ID)))
2751       Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2752
2753     llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
2754                              /*isSigned*/true);
2755     // Don't emit the guess in non-PIC code because the linker will not be able
2756     // to replace it with the real version for a library.  In non-PIC code you
2757     // must compile with the fragile ABI if you want to use ivars from a
2758     // GCC-compiled class.
2759     if (CGM.getLangOpts().PICLevel || CGM.getLangOpts().PIELevel) {
2760       llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2761             Int32Ty, false,
2762             llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2763       IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2764             IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2765             IvarOffsetGV, Name);
2766     } else {
2767       IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2768               llvm::Type::getInt32PtrTy(VMContext), false,
2769               llvm::GlobalValue::ExternalLinkage, 0, Name);
2770     }
2771   }
2772   return IvarOffsetPointer;
2773 }
2774
2775 LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
2776                                        QualType ObjectTy,
2777                                        llvm::Value *BaseValue,
2778                                        const ObjCIvarDecl *Ivar,
2779                                        unsigned CVRQualifiers) {
2780   const ObjCInterfaceDecl *ID =
2781     ObjectTy->getAs<ObjCObjectType>()->getInterface();
2782   return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2783                                   EmitIvarOffset(CGF, ID, Ivar));
2784 }
2785
2786 static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2787                                                   const ObjCInterfaceDecl *OID,
2788                                                   const ObjCIvarDecl *OIVD) {
2789   for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2790        next = next->getNextIvar()) {
2791     if (OIVD == next)
2792       return OID;
2793   }
2794
2795   // Otherwise check in the super class.
2796   if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2797     return FindIvarInterface(Context, Super, OIVD);
2798
2799   return 0;
2800 }
2801
2802 llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
2803                          const ObjCInterfaceDecl *Interface,
2804                          const ObjCIvarDecl *Ivar) {
2805   if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2806     Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
2807     if (RuntimeVersion < 10)
2808       return CGF.Builder.CreateZExtOrBitCast(
2809           CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2810                   ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2811           PtrDiffTy);
2812     std::string name = "__objc_ivar_offset_value_" +
2813       Interface->getNameAsString() +"." + Ivar->getNameAsString();
2814     llvm::Value *Offset = TheModule.getGlobalVariable(name);
2815     if (!Offset)
2816       Offset = new llvm::GlobalVariable(TheModule, IntTy,
2817           false, llvm::GlobalValue::LinkOnceAnyLinkage,
2818           llvm::Constant::getNullValue(IntTy), name);
2819     Offset = CGF.Builder.CreateLoad(Offset);
2820     if (Offset->getType() != PtrDiffTy)
2821       Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
2822     return Offset;
2823   }
2824   uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
2825   return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
2826 }
2827
2828 CGObjCRuntime *
2829 clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2830   switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
2831   case ObjCRuntime::GNUstep:
2832     return new CGObjCGNUstep(CGM);
2833
2834   case ObjCRuntime::GCC:
2835     return new CGObjCGCC(CGM);
2836
2837   case ObjCRuntime::ObjFW:
2838     return new CGObjCObjFW(CGM);
2839
2840   case ObjCRuntime::FragileMacOSX:
2841   case ObjCRuntime::MacOSX:
2842   case ObjCRuntime::iOS:
2843     llvm_unreachable("these runtimes are not GNU runtimes");
2844   }
2845   llvm_unreachable("bad runtime");
2846 }