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