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