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 targetting 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 
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/RecordLayout.h"
25 #include "clang/AST/StmtObjC.h"
26 
27 #include "llvm/Intrinsics.h"
28 #include "llvm/Module.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringMap.h"
31 #include "llvm/Support/Compiler.h"
32 #include "llvm/Target/TargetData.h"
33 
34 #include <map>
35 
36 
37 using namespace clang;
38 using namespace CodeGen;
39 using llvm::dyn_cast;
40 
41 // The version of the runtime that this class targets.  Must match the version
42 // in the runtime.
43 static const int RuntimeVersion = 8;
44 static const int NonFragileRuntimeVersion = 9;
45 static const int ProtocolVersion = 2;
46 
47 namespace {
48 class CGObjCGNU : public CodeGen::CGObjCRuntime {
49 private:
50   CodeGen::CodeGenModule &CGM;
51   llvm::Module &TheModule;
52   const llvm::PointerType *SelectorTy;
53   const llvm::PointerType *PtrToInt8Ty;
54   const llvm::FunctionType *IMPTy;
55   const llvm::PointerType *IdTy;
56   const llvm::IntegerType *IntTy;
57   const llvm::PointerType *PtrTy;
58   const llvm::IntegerType *LongTy;
59   const llvm::PointerType *PtrToIntTy;
60   llvm::GlobalAlias *ClassPtrAlias;
61   llvm::GlobalAlias *MetaClassPtrAlias;
62   std::vector<llvm::Constant*> Classes;
63   std::vector<llvm::Constant*> Categories;
64   std::vector<llvm::Constant*> ConstantStrings;
65   llvm::Function *LoadFunction;
66   llvm::StringMap<llvm::Constant*> ExistingProtocols;
67   typedef std::pair<std::string, std::string> TypedSelector;
68   std::map<TypedSelector, llvm::GlobalAlias*> TypedSelectors;
69   llvm::StringMap<llvm::GlobalAlias*> UntypedSelectors;
70   // Some zeros used for GEPs in lots of places.
71   llvm::Constant *Zeros[2];
72   llvm::Constant *NULLPtr;
73 private:
74   llvm::Constant *GenerateIvarList(
75       const llvm::SmallVectorImpl<llvm::Constant *>  &IvarNames,
76       const llvm::SmallVectorImpl<llvm::Constant *>  &IvarTypes,
77       const llvm::SmallVectorImpl<llvm::Constant *>  &IvarOffsets);
78   llvm::Constant *GenerateMethodList(const std::string &ClassName,
79       const std::string &CategoryName,
80       const llvm::SmallVectorImpl<Selector>  &MethodSels,
81       const llvm::SmallVectorImpl<llvm::Constant *>  &MethodTypes,
82       bool isClassMethodList);
83   llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
84   llvm::Constant *GenerateProtocolList(
85       const llvm::SmallVectorImpl<std::string> &Protocols);
86   llvm::Constant *GenerateClassStructure(
87       llvm::Constant *MetaClass,
88       llvm::Constant *SuperClass,
89       unsigned info,
90       const char *Name,
91       llvm::Constant *Version,
92       llvm::Constant *InstanceSize,
93       llvm::Constant *IVars,
94       llvm::Constant *Methods,
95       llvm::Constant *Protocols);
96   llvm::Constant *GenerateProtocolMethodList(
97       const llvm::SmallVectorImpl<llvm::Constant *>  &MethodNames,
98       const llvm::SmallVectorImpl<llvm::Constant *>  &MethodTypes);
99   llvm::Constant *MakeConstantString(const std::string &Str, const std::string
100       &Name="");
101   llvm::Constant *MakeGlobal(const llvm::StructType *Ty,
102       std::vector<llvm::Constant*> &V, const std::string &Name="");
103   llvm::Constant *MakeGlobal(const llvm::ArrayType *Ty,
104       std::vector<llvm::Constant*> &V, const std::string &Name="");
105   llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
106       const ObjCIvarDecl *Ivar);
107   void EmitClassRef(const std::string &className);
108 public:
109   CGObjCGNU(CodeGen::CodeGenModule &cgm);
110   virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *);
111   virtual CodeGen::RValue
112   GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
113                       QualType ResultType,
114                       Selector Sel,
115                       llvm::Value *Receiver,
116                       bool IsClassMessage,
117                       const CallArgList &CallArgs,
118                       const ObjCMethodDecl *Method);
119   virtual CodeGen::RValue
120   GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
121                            QualType ResultType,
122                            Selector Sel,
123                            const ObjCInterfaceDecl *Class,
124                            bool isCategoryImpl,
125                            llvm::Value *Receiver,
126                            bool IsClassMessage,
127                            const CallArgList &CallArgs);
128   virtual llvm::Value *GetClass(CGBuilderTy &Builder,
129                                 const ObjCInterfaceDecl *OID);
130   virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
131   virtual llvm::Value *GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
132       *Method);
133 
134   virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
135                                          const ObjCContainerDecl *CD);
136   virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
137   virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
138   virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
139                                            const ObjCProtocolDecl *PD);
140   virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
141   virtual llvm::Function *ModuleInitFunction();
142   virtual void MergeMetadataGlobals(std::vector<llvm::Constant*> &UsedArray);
143   virtual llvm::Function *GetPropertyGetFunction();
144   virtual llvm::Function *GetPropertySetFunction();
145   virtual llvm::Function *EnumerationMutationFunction();
146 
147   virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
148                                          const Stmt &S);
149   virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
150                              const ObjCAtThrowStmt &S);
151   virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
152                                          llvm::Value *AddrWeakObj);
153   virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
154                                   llvm::Value *src, llvm::Value *dst);
155   virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
156                                     llvm::Value *src, llvm::Value *dest);
157   virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
158                                     llvm::Value *src, llvm::Value *dest);
159   virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
160                                         llvm::Value *src, llvm::Value *dest);
161   virtual void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
162                                         llvm::Value *DestPtr,
163                                         llvm::Value *SrcPtr,
164                                         unsigned long size);
165   virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
166                                       QualType ObjectTy,
167                                       llvm::Value *BaseValue,
168                                       const ObjCIvarDecl *Ivar,
169                                       unsigned CVRQualifiers);
170   virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
171                                       const ObjCInterfaceDecl *Interface,
172                                       const ObjCIvarDecl *Ivar);
173 };
174 } // end anonymous namespace
175 
176 
177 /// Emits a reference to a dummy variable which is emitted with each class.
178 /// This ensures that a linker error will be generated when trying to link
179 /// together modules where a referenced class is not defined.
180 void CGObjCGNU::EmitClassRef(const std::string &className){
181   std::string symbolRef = "__objc_class_ref_" + className;
182   // Don't emit two copies of the same symbol
183   if (TheModule.getGlobalVariable(symbolRef)) return;
184   std::string symbolName = "__objc_class_name_" + className;
185   llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
186   if (!ClassSymbol) {
187     ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
188         llvm::GlobalValue::ExternalLinkage, 0, symbolName);
189   }
190   new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
191     llvm::GlobalValue::CommonLinkage, ClassSymbol, symbolRef);
192 }
193 
194 static std::string SymbolNameForClass(const std::string &ClassName) {
195   return "_OBJC_CLASS_" + ClassName;
196 }
197 
198 static std::string SymbolNameForMethod(const std::string &ClassName, const
199   std::string &CategoryName, const std::string &MethodName, bool isClassMethod)
200 {
201   return "_OBJC_METHOD_" + ClassName + "("+CategoryName+")"+
202             (isClassMethod ? "+" : "-") + MethodName;
203 }
204 
205 CGObjCGNU::CGObjCGNU(CodeGen::CodeGenModule &cgm)
206   : CGM(cgm), TheModule(CGM.getModule()), ClassPtrAlias(0),
207     MetaClassPtrAlias(0) {
208   IntTy = cast<llvm::IntegerType>(
209       CGM.getTypes().ConvertType(CGM.getContext().IntTy));
210   LongTy = cast<llvm::IntegerType>(
211       CGM.getTypes().ConvertType(CGM.getContext().LongTy));
212 
213   Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
214   Zeros[1] = Zeros[0];
215   NULLPtr = llvm::ConstantPointerNull::get(
216     llvm::PointerType::getUnqual(llvm::Type::Int8Ty));
217   // C string type.  Used in lots of places.
218   PtrToInt8Ty =
219     llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
220   // Get the selector Type.
221   SelectorTy = cast<llvm::PointerType>(
222     CGM.getTypes().ConvertType(CGM.getContext().getObjCSelType()));
223 
224   PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
225   PtrTy = PtrToInt8Ty;
226 
227   // Object type
228   IdTy = cast<llvm::PointerType>(
229 		  CGM.getTypes().ConvertType(CGM.getContext().getObjCIdType()));
230 
231   // IMP type
232   std::vector<const llvm::Type*> IMPArgs;
233   IMPArgs.push_back(IdTy);
234   IMPArgs.push_back(SelectorTy);
235   IMPTy = llvm::FunctionType::get(IdTy, IMPArgs, true);
236 }
237 // This has to perform the lookup every time, since posing and related
238 // techniques can modify the name -> class mapping.
239 llvm::Value *CGObjCGNU::GetClass(CGBuilderTy &Builder,
240                                  const ObjCInterfaceDecl *OID) {
241   llvm::Value *ClassName = CGM.GetAddrOfConstantCString(OID->getNameAsString());
242   EmitClassRef(OID->getNameAsString());
243   ClassName = Builder.CreateStructGEP(ClassName, 0);
244 
245   std::vector<const llvm::Type*> Params(1, PtrToInt8Ty);
246   llvm::Constant *ClassLookupFn =
247     CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy,
248                                                       Params,
249                                                       true),
250                               "objc_lookup_class");
251   return Builder.CreateCall(ClassLookupFn, ClassName);
252 }
253 
254 llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, Selector Sel) {
255   llvm::GlobalAlias *&US = UntypedSelectors[Sel.getAsString()];
256   if (US == 0)
257     US = new llvm::GlobalAlias(llvm::PointerType::getUnqual(SelectorTy),
258                                llvm::GlobalValue::InternalLinkage,
259                                ".objc_untyped_selector_alias",
260                                NULL, &TheModule);
261 
262   return Builder.CreateLoad(US);
263 }
264 
265 llvm::Value *CGObjCGNU::GetSelector(CGBuilderTy &Builder, const ObjCMethodDecl
266     *Method) {
267 
268   std::string SelName = Method->getSelector().getAsString();
269   std::string SelTypes;
270   CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
271   // Typed selectors
272   TypedSelector Selector = TypedSelector(SelName,
273           SelTypes);
274 
275   // If it's already cached, return it.
276   if (TypedSelectors[Selector])
277   {
278       return Builder.CreateLoad(TypedSelectors[Selector]);
279   }
280 
281   // If it isn't, cache it.
282   llvm::GlobalAlias *Sel = new llvm::GlobalAlias(
283           llvm::PointerType::getUnqual(SelectorTy),
284           llvm::GlobalValue::InternalLinkage, SelName,
285           NULL, &TheModule);
286   TypedSelectors[Selector] = Sel;
287 
288   return Builder.CreateLoad(Sel);
289 }
290 
291 llvm::Constant *CGObjCGNU::MakeConstantString(const std::string &Str,
292                                               const std::string &Name) {
293   llvm::Constant * ConstStr = llvm::ConstantArray::get(Str);
294   ConstStr = new llvm::GlobalVariable(TheModule, ConstStr->getType(), true,
295                                llvm::GlobalValue::InternalLinkage,
296                                ConstStr, Name);
297   return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros, 2);
298 }
299 llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::StructType *Ty,
300     std::vector<llvm::Constant*> &V, const std::string &Name) {
301   llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
302   return new llvm::GlobalVariable(TheModule, Ty, false,
303       llvm::GlobalValue::InternalLinkage, C, Name);
304 }
305 llvm::Constant *CGObjCGNU::MakeGlobal(const llvm::ArrayType *Ty,
306     std::vector<llvm::Constant*> &V, const std::string &Name) {
307   llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
308   return new llvm::GlobalVariable(TheModule, Ty, false,
309       llvm::GlobalValue::InternalLinkage, C, Name);
310 }
311 
312 /// Generate an NSConstantString object.
313 //TODO: In case there are any crazy people still using the GNU runtime without
314 //an OpenStep implementation, this should let them select their own class for
315 //constant strings.
316 llvm::Constant *CGObjCGNU::GenerateConstantString(const ObjCStringLiteral *SL) {
317   std::string Str(SL->getString()->getStrData(),
318                   SL->getString()->getByteLength());
319   std::vector<llvm::Constant*> Ivars;
320   Ivars.push_back(NULLPtr);
321   Ivars.push_back(MakeConstantString(Str));
322   Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
323   llvm::Constant *ObjCStr = MakeGlobal(
324     llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy, NULL),
325     Ivars, ".objc_str");
326   ConstantStrings.push_back(
327       llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty));
328   return ObjCStr;
329 }
330 
331 ///Generates a message send where the super is the receiver.  This is a message
332 ///send to self with special delivery semantics indicating which class's method
333 ///should be called.
334 CodeGen::RValue
335 CGObjCGNU::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
336                                     QualType ResultType,
337                                     Selector Sel,
338                                     const ObjCInterfaceDecl *Class,
339                                     bool isCategoryImpl,
340                                     llvm::Value *Receiver,
341                                     bool IsClassMessage,
342                                     const CallArgList &CallArgs) {
343   llvm::Value *cmd = GetSelector(CGF.Builder, Sel);
344 
345   CallArgList ActualArgs;
346 
347   ActualArgs.push_back(
348 	  std::make_pair(RValue::get(CGF.Builder.CreateBitCast(Receiver, IdTy)),
349 	  CGF.getContext().getObjCIdType()));
350   ActualArgs.push_back(std::make_pair(RValue::get(cmd),
351                                       CGF.getContext().getObjCSelType()));
352   ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
353 
354   CodeGenTypes &Types = CGM.getTypes();
355   const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
356   const llvm::FunctionType *impType = Types.GetFunctionType(FnInfo, false);
357 
358   llvm::Value *ReceiverClass = 0;
359   if (isCategoryImpl) {
360     llvm::Constant *classLookupFunction = 0;
361     std::vector<const llvm::Type*> Params;
362     Params.push_back(PtrTy);
363     if (IsClassMessage)  {
364       classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
365             IdTy, Params, true), "objc_get_meta_class");
366     } else {
367       classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
368             IdTy, Params, true), "objc_get_class");
369     }
370     ReceiverClass = CGF.Builder.CreateCall(classLookupFunction,
371         MakeConstantString(Class->getNameAsString()));
372   } else {
373     // Set up global aliases for the metaclass or class pointer if they do not
374     // already exist.  These will are forward-references which will be set to
375     // pointers to the class and metaclass structure created for the runtime load
376     // function.  To send a message to super, we look up the value of the
377     // super_class pointer from either the class or metaclass structure.
378     if (IsClassMessage)  {
379       if (!MetaClassPtrAlias) {
380         MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
381             llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
382             Class->getNameAsString(), NULL, &TheModule);
383       }
384       ReceiverClass = MetaClassPtrAlias;
385     } else {
386       if (!ClassPtrAlias) {
387         ClassPtrAlias = new llvm::GlobalAlias(IdTy,
388             llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
389             Class->getNameAsString(), NULL, &TheModule);
390       }
391       ReceiverClass = ClassPtrAlias;
392     }
393   }
394   // Cast the pointer to a simplified version of the class structure
395   ReceiverClass = CGF.Builder.CreateBitCast(ReceiverClass,
396       llvm::PointerType::getUnqual(llvm::StructType::get(IdTy, IdTy, NULL)));
397   // Get the superclass pointer
398   ReceiverClass = CGF.Builder.CreateStructGEP(ReceiverClass, 1);
399   // Load the superclass pointer
400   ReceiverClass = CGF.Builder.CreateLoad(ReceiverClass);
401   // Construct the structure used to look up the IMP
402   llvm::StructType *ObjCSuperTy = llvm::StructType::get(Receiver->getType(),
403       IdTy, NULL);
404   llvm::Value *ObjCSuper = CGF.Builder.CreateAlloca(ObjCSuperTy);
405 
406   CGF.Builder.CreateStore(Receiver, CGF.Builder.CreateStructGEP(ObjCSuper, 0));
407   CGF.Builder.CreateStore(ReceiverClass,
408       CGF.Builder.CreateStructGEP(ObjCSuper, 1));
409 
410   // Get the IMP
411   std::vector<const llvm::Type*> Params;
412   Params.push_back(llvm::PointerType::getUnqual(ObjCSuperTy));
413   Params.push_back(SelectorTy);
414   llvm::Constant *lookupFunction =
415     CGM.CreateRuntimeFunction(llvm::FunctionType::get(
416           llvm::PointerType::getUnqual(impType), Params, true),
417         "objc_msg_lookup_super");
418 
419   llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
420   llvm::Value *imp = CGF.Builder.CreateCall(lookupFunction, lookupArgs,
421       lookupArgs+2);
422 
423   return CGF.EmitCall(FnInfo, imp, ActualArgs);
424 }
425 
426 /// Generate code for a message send expression.
427 CodeGen::RValue
428 CGObjCGNU::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
429                                QualType ResultType,
430                                Selector Sel,
431                                llvm::Value *Receiver,
432                                bool IsClassMessage,
433                                const CallArgList &CallArgs,
434                                const ObjCMethodDecl *Method) {
435   llvm::Value *cmd;
436   if (Method)
437     cmd = GetSelector(CGF.Builder, Method);
438   else
439     cmd = GetSelector(CGF.Builder, Sel);
440   CallArgList ActualArgs;
441 
442   ActualArgs.push_back(
443     std::make_pair(RValue::get(CGF.Builder.CreateBitCast(Receiver, IdTy)),
444     CGF.getContext().getObjCIdType()));
445   ActualArgs.push_back(std::make_pair(RValue::get(cmd),
446                                       CGF.getContext().getObjCSelType()));
447   ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
448 
449   CodeGenTypes &Types = CGM.getTypes();
450   const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
451   const llvm::FunctionType *impType = Types.GetFunctionType(FnInfo, false);
452 
453   llvm::Value *imp;
454   std::vector<const llvm::Type*> Params;
455   Params.push_back(Receiver->getType());
456   Params.push_back(SelectorTy);
457   // For sender-aware dispatch, we pass the sender as the third argument to a
458   // lookup function.  When sending messages from C code, the sender is nil.
459   // objc_msg_lookup_sender(id receiver, SEL selector, id sender);
460   if (CGM.getContext().getLangOptions().ObjCSenderDispatch) {
461     llvm::Value *self;
462 
463     if (isa<ObjCMethodDecl>(CGF.CurFuncDecl)) {
464       self = CGF.LoadObjCSelf();
465     } else {
466       self = llvm::ConstantPointerNull::get(IdTy);
467     }
468     Params.push_back(self->getType());
469     llvm::Constant *lookupFunction =
470       CGM.CreateRuntimeFunction(llvm::FunctionType::get(
471           llvm::PointerType::getUnqual(impType), Params, true),
472         "objc_msg_lookup_sender");
473 
474     imp = CGF.Builder.CreateCall3(lookupFunction, Receiver, cmd, self);
475   } else {
476     llvm::Constant *lookupFunction =
477     CGM.CreateRuntimeFunction(llvm::FunctionType::get(
478         llvm::PointerType::getUnqual(impType), Params, true),
479       "objc_msg_lookup");
480 
481     imp = CGF.Builder.CreateCall2(lookupFunction, Receiver, cmd);
482   }
483 
484   return CGF.EmitCall(FnInfo, imp, ActualArgs);
485 }
486 
487 /// Generates a MethodList.  Used in construction of a objc_class and
488 /// objc_category structures.
489 llvm::Constant *CGObjCGNU::GenerateMethodList(const std::string &ClassName,
490                                               const std::string &CategoryName,
491     const llvm::SmallVectorImpl<Selector> &MethodSels,
492     const llvm::SmallVectorImpl<llvm::Constant *> &MethodTypes,
493     bool isClassMethodList) {
494   // Get the method structure type.
495   llvm::StructType *ObjCMethodTy = llvm::StructType::get(
496     PtrToInt8Ty, // Really a selector, but the runtime creates it us.
497     PtrToInt8Ty, // Method types
498     llvm::PointerType::getUnqual(IMPTy), //Method pointer
499     NULL);
500   std::vector<llvm::Constant*> Methods;
501   std::vector<llvm::Constant*> Elements;
502   for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
503     Elements.clear();
504     if (llvm::Constant *Method =
505       TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
506                                                 MethodSels[i].getAsString(),
507                                                 isClassMethodList))) {
508       llvm::Constant *C =
509         CGM.GetAddrOfConstantCString(MethodSels[i].getAsString());
510       Elements.push_back(llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2));
511       Elements.push_back(
512             llvm::ConstantExpr::getGetElementPtr(MethodTypes[i], Zeros, 2));
513       Method = llvm::ConstantExpr::getBitCast(Method,
514           llvm::PointerType::getUnqual(IMPTy));
515       Elements.push_back(Method);
516       Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
517     }
518   }
519 
520   // Array of method structures
521   llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
522                                                             Methods.size());
523   llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
524                                                          Methods);
525 
526   // Structure containing list pointer, array and array count
527   llvm::SmallVector<const llvm::Type*, 16> ObjCMethodListFields;
528   llvm::PATypeHolder OpaqueNextTy = llvm::OpaqueType::get();
529   llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(OpaqueNextTy);
530   llvm::StructType *ObjCMethodListTy = llvm::StructType::get(NextPtrTy,
531       IntTy,
532       ObjCMethodArrayTy,
533       NULL);
534   // Refine next pointer type to concrete type
535   llvm::cast<llvm::OpaqueType>(
536       OpaqueNextTy.get())->refineAbstractTypeTo(ObjCMethodListTy);
537   ObjCMethodListTy = llvm::cast<llvm::StructType>(OpaqueNextTy.get());
538 
539   Methods.clear();
540   Methods.push_back(llvm::ConstantPointerNull::get(
541         llvm::PointerType::getUnqual(ObjCMethodListTy)));
542   Methods.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
543         MethodTypes.size()));
544   Methods.push_back(MethodArray);
545 
546   // Create an instance of the structure
547   return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
548 }
549 
550 /// Generates an IvarList.  Used in construction of a objc_class.
551 llvm::Constant *CGObjCGNU::GenerateIvarList(
552     const llvm::SmallVectorImpl<llvm::Constant *>  &IvarNames,
553     const llvm::SmallVectorImpl<llvm::Constant *>  &IvarTypes,
554     const llvm::SmallVectorImpl<llvm::Constant *>  &IvarOffsets) {
555   // Get the method structure type.
556   llvm::StructType *ObjCIvarTy = llvm::StructType::get(
557     PtrToInt8Ty,
558     PtrToInt8Ty,
559     IntTy,
560     NULL);
561   std::vector<llvm::Constant*> Ivars;
562   std::vector<llvm::Constant*> Elements;
563   for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
564     Elements.clear();
565     Elements.push_back( llvm::ConstantExpr::getGetElementPtr(IvarNames[i],
566           Zeros, 2));
567     Elements.push_back( llvm::ConstantExpr::getGetElementPtr(IvarTypes[i],
568           Zeros, 2));
569     Elements.push_back(IvarOffsets[i]);
570     Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
571   }
572 
573   // Array of method structures
574   llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
575       IvarNames.size());
576 
577 
578   Elements.clear();
579   Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
580   Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
581   // Structure containing array and array count
582   llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
583     ObjCIvarArrayTy,
584     NULL);
585 
586   // Create an instance of the structure
587   return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
588 }
589 
590 /// Generate a class structure
591 llvm::Constant *CGObjCGNU::GenerateClassStructure(
592     llvm::Constant *MetaClass,
593     llvm::Constant *SuperClass,
594     unsigned info,
595     const char *Name,
596     llvm::Constant *Version,
597     llvm::Constant *InstanceSize,
598     llvm::Constant *IVars,
599     llvm::Constant *Methods,
600     llvm::Constant *Protocols) {
601   // Set up the class structure
602   // Note:  Several of these are char*s when they should be ids.  This is
603   // because the runtime performs this translation on load.
604   llvm::StructType *ClassTy = llvm::StructType::get(
605       PtrToInt8Ty,        // class_pointer
606       PtrToInt8Ty,        // super_class
607       PtrToInt8Ty,        // name
608       LongTy,             // version
609       LongTy,             // info
610       LongTy,             // instance_size
611       IVars->getType(),   // ivars
612       Methods->getType(), // methods
613       // These are all filled in by the runtime, so we pretend
614       PtrTy,              // dtable
615       PtrTy,              // subclass_list
616       PtrTy,              // sibling_class
617       PtrTy,              // protocols
618       PtrTy,              // gc_object_type
619       NULL);
620   llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
621   llvm::Constant *NullP =
622     llvm::ConstantPointerNull::get(PtrTy);
623   // Fill in the structure
624   std::vector<llvm::Constant*> Elements;
625   Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
626   Elements.push_back(SuperClass);
627   Elements.push_back(MakeConstantString(Name, ".class_name"));
628   Elements.push_back(Zero);
629   Elements.push_back(llvm::ConstantInt::get(LongTy, info));
630   Elements.push_back(InstanceSize);
631   Elements.push_back(IVars);
632   Elements.push_back(Methods);
633   Elements.push_back(NullP);
634   Elements.push_back(NullP);
635   Elements.push_back(NullP);
636   Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
637   Elements.push_back(NullP);
638   // Create an instance of the structure
639   return MakeGlobal(ClassTy, Elements, SymbolNameForClass(Name));
640 }
641 
642 llvm::Constant *CGObjCGNU::GenerateProtocolMethodList(
643     const llvm::SmallVectorImpl<llvm::Constant *>  &MethodNames,
644     const llvm::SmallVectorImpl<llvm::Constant *>  &MethodTypes) {
645   // Get the method structure type.
646   llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
647     PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
648     PtrToInt8Ty,
649     NULL);
650   std::vector<llvm::Constant*> Methods;
651   std::vector<llvm::Constant*> Elements;
652   for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
653     Elements.clear();
654     Elements.push_back( llvm::ConstantExpr::getGetElementPtr(MethodNames[i],
655           Zeros, 2));
656     Elements.push_back(
657           llvm::ConstantExpr::getGetElementPtr(MethodTypes[i], Zeros, 2));
658     Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
659   }
660   llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
661       MethodNames.size());
662   llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy, Methods);
663   llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
664       IntTy, ObjCMethodArrayTy, NULL);
665   Methods.clear();
666   Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
667   Methods.push_back(Array);
668   return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
669 }
670 // Create the protocol list structure used in classes, categories and so on
671 llvm::Constant *CGObjCGNU::GenerateProtocolList(
672     const llvm::SmallVectorImpl<std::string> &Protocols) {
673   llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
674       Protocols.size());
675   llvm::StructType *ProtocolListTy = llvm::StructType::get(
676       PtrTy, //Should be a recurisve pointer, but it's always NULL here.
677       LongTy,//FIXME: Should be size_t
678       ProtocolArrayTy,
679       NULL);
680   std::vector<llvm::Constant*> Elements;
681   for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
682       iter != endIter ; iter++) {
683     llvm::Constant *protocol = ExistingProtocols[*iter];
684     if (!protocol)
685       protocol = GenerateEmptyProtocol(*iter);
686     llvm::Constant *Ptr =
687       llvm::ConstantExpr::getBitCast(protocol, PtrToInt8Ty);
688     Elements.push_back(Ptr);
689   }
690   llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
691       Elements);
692   Elements.clear();
693   Elements.push_back(NULLPtr);
694   Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
695   Elements.push_back(ProtocolArray);
696   return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
697 }
698 
699 llvm::Value *CGObjCGNU::GenerateProtocolRef(CGBuilderTy &Builder,
700                                             const ObjCProtocolDecl *PD) {
701   llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
702   const llvm::Type *T =
703     CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
704   return Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
705 }
706 
707 llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
708   const std::string &ProtocolName) {
709   llvm::SmallVector<std::string, 0> EmptyStringVector;
710   llvm::SmallVector<llvm::Constant*, 0> EmptyConstantVector;
711 
712   llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
713   llvm::Constant *InstanceMethodList =
714     GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
715   llvm::Constant *ClassMethodList =
716     GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
717   // Protocols are objects containing lists of the methods implemented and
718   // protocols adopted.
719   llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
720       PtrToInt8Ty,
721       ProtocolList->getType(),
722       InstanceMethodList->getType(),
723       ClassMethodList->getType(),
724       NULL);
725   std::vector<llvm::Constant*> Elements;
726   // The isa pointer must be set to a magic number so the runtime knows it's
727   // the correct layout.
728   Elements.push_back(llvm::ConstantExpr::getIntToPtr(
729         llvm::ConstantInt::get(llvm::Type::Int32Ty, ProtocolVersion), IdTy));
730   Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
731   Elements.push_back(ProtocolList);
732   Elements.push_back(InstanceMethodList);
733   Elements.push_back(ClassMethodList);
734   return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
735 }
736 
737 void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
738   ASTContext &Context = CGM.getContext();
739   std::string ProtocolName = PD->getNameAsString();
740   llvm::SmallVector<std::string, 16> Protocols;
741   for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
742        E = PD->protocol_end(); PI != E; ++PI)
743     Protocols.push_back((*PI)->getNameAsString());
744   llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
745   llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
746   for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
747        E = PD->instmeth_end(); iter != E; iter++) {
748     std::string TypeStr;
749     Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
750     InstanceMethodNames.push_back(
751         CGM.GetAddrOfConstantCString((*iter)->getSelector().getAsString()));
752     InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
753   }
754   // Collect information about class methods:
755   llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
756   llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
757   for (ObjCProtocolDecl::classmeth_iterator
758          iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
759        iter != endIter ; iter++) {
760     std::string TypeStr;
761     Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
762     ClassMethodNames.push_back(
763         CGM.GetAddrOfConstantCString((*iter)->getSelector().getAsString()));
764     ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
765   }
766 
767   llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
768   llvm::Constant *InstanceMethodList =
769     GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
770   llvm::Constant *ClassMethodList =
771     GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
772   // Protocols are objects containing lists of the methods implemented and
773   // protocols adopted.
774   llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
775       PtrToInt8Ty,
776       ProtocolList->getType(),
777       InstanceMethodList->getType(),
778       ClassMethodList->getType(),
779       NULL);
780   std::vector<llvm::Constant*> Elements;
781   // The isa pointer must be set to a magic number so the runtime knows it's
782   // the correct layout.
783   Elements.push_back(llvm::ConstantExpr::getIntToPtr(
784         llvm::ConstantInt::get(llvm::Type::Int32Ty, ProtocolVersion), IdTy));
785   Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
786   Elements.push_back(ProtocolList);
787   Elements.push_back(InstanceMethodList);
788   Elements.push_back(ClassMethodList);
789   ExistingProtocols[ProtocolName] =
790     llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
791           ".objc_protocol"), IdTy);
792 }
793 
794 void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
795   std::string ClassName = OCD->getClassInterface()->getNameAsString();
796   std::string CategoryName = OCD->getNameAsString();
797   // Collect information about instance methods
798   llvm::SmallVector<Selector, 16> InstanceMethodSels;
799   llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
800   for (ObjCCategoryImplDecl::instmeth_iterator
801          iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
802        iter != endIter ; iter++) {
803     InstanceMethodSels.push_back((*iter)->getSelector());
804     std::string TypeStr;
805     CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
806     InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
807   }
808 
809   // Collect information about class methods
810   llvm::SmallVector<Selector, 16> ClassMethodSels;
811   llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
812   for (ObjCCategoryImplDecl::classmeth_iterator
813          iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
814        iter != endIter ; iter++) {
815     ClassMethodSels.push_back((*iter)->getSelector());
816     std::string TypeStr;
817     CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
818     ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
819   }
820 
821   // Collect the names of referenced protocols
822   llvm::SmallVector<std::string, 16> Protocols;
823   const ObjCInterfaceDecl *ClassDecl = OCD->getClassInterface();
824   const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
825   for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
826        E = Protos.end(); I != E; ++I)
827     Protocols.push_back((*I)->getNameAsString());
828 
829   std::vector<llvm::Constant*> Elements;
830   Elements.push_back(MakeConstantString(CategoryName));
831   Elements.push_back(MakeConstantString(ClassName));
832   // Instance method list
833   Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
834           ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
835           false), PtrTy));
836   // Class method list
837   Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
838           ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
839         PtrTy));
840   // Protocol list
841   Elements.push_back(llvm::ConstantExpr::getBitCast(
842         GenerateProtocolList(Protocols), PtrTy));
843   Categories.push_back(llvm::ConstantExpr::getBitCast(
844         MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, PtrTy,
845             PtrTy, PtrTy, NULL), Elements), PtrTy));
846 }
847 
848 void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
849   ASTContext &Context = CGM.getContext();
850 
851   // Get the superclass name.
852   const ObjCInterfaceDecl * SuperClassDecl =
853     OID->getClassInterface()->getSuperClass();
854   std::string SuperClassName;
855   if (SuperClassDecl) {
856     SuperClassName = SuperClassDecl->getNameAsString();
857     EmitClassRef(SuperClassName);
858   }
859 
860   // Get the class name
861   ObjCInterfaceDecl *ClassDecl =
862     const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
863   std::string ClassName = ClassDecl->getNameAsString();
864   // Emit the symbol that is used to generate linker errors if this class is
865   // referenced in other modules but not declared.
866   std::string classSymbolName = "__objc_class_name_" + ClassName;
867   if (llvm::GlobalVariable *symbol =
868       TheModule.getGlobalVariable(classSymbolName)) {
869     symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
870   } else {
871     new llvm::GlobalVariable(TheModule, LongTy, false,
872     llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
873     classSymbolName);
874   }
875 
876   // Get the size of instances.
877   int instanceSize = Context.getASTObjCImplementationLayout(OID).getSize() / 8;
878 
879   // Collect information about instance variables.
880   llvm::SmallVector<llvm::Constant*, 16> IvarNames;
881   llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
882   llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
883 
884   int superInstanceSize = !SuperClassDecl ? 0 :
885     Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize() / 8;
886   // For non-fragile ivars, set the instance size to 0 - {the size of just this
887   // class}.  The runtime will then set this to the correct value on load.
888   if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
889     instanceSize = 0 - (instanceSize - superInstanceSize);
890   }
891   for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
892       endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
893       // Store the name
894       IvarNames.push_back(CGM.GetAddrOfConstantCString((*iter)
895                                                          ->getNameAsString()));
896       // Get the type encoding for this ivar
897       std::string TypeStr;
898       Context.getObjCEncodingForType((*iter)->getType(), TypeStr);
899       IvarTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
900       // Get the offset
901       uint64_t Offset;
902       if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
903 		Offset = ComputeIvarBaseOffset(CGM, ClassDecl, *iter) -
904 			superInstanceSize;
905         ObjCIvarOffsetVariable(ClassDecl, *iter);
906       } else {
907         Offset = ComputeIvarBaseOffset(CGM, ClassDecl, *iter);
908       }
909       IvarOffsets.push_back(
910           llvm::ConstantInt::get(llvm::Type::Int32Ty, Offset));
911   }
912 
913   // Collect information about instance methods
914   llvm::SmallVector<Selector, 16> InstanceMethodSels;
915   llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
916   for (ObjCImplementationDecl::instmeth_iterator
917          iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
918        iter != endIter ; iter++) {
919     InstanceMethodSels.push_back((*iter)->getSelector());
920     std::string TypeStr;
921     Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
922     InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
923   }
924   for (ObjCImplDecl::propimpl_iterator
925          iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
926        iter != endIter ; iter++) {
927     ObjCPropertyDecl *property = (*iter)->getPropertyDecl();
928     if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
929       InstanceMethodSels.push_back(getter->getSelector());
930       std::string TypeStr;
931       Context.getObjCEncodingForMethodDecl(getter,TypeStr);
932       InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
933     }
934     if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
935       InstanceMethodSels.push_back(setter->getSelector());
936       std::string TypeStr;
937       Context.getObjCEncodingForMethodDecl(setter,TypeStr);
938       InstanceMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
939     }
940   }
941 
942   // Collect information about class methods
943   llvm::SmallVector<Selector, 16> ClassMethodSels;
944   llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
945   for (ObjCImplementationDecl::classmeth_iterator
946          iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
947        iter != endIter ; iter++) {
948     ClassMethodSels.push_back((*iter)->getSelector());
949     std::string TypeStr;
950     Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
951     ClassMethodTypes.push_back(CGM.GetAddrOfConstantCString(TypeStr));
952   }
953   // Collect the names of referenced protocols
954   llvm::SmallVector<std::string, 16> Protocols;
955   const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
956   for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
957        E = Protos.end(); I != E; ++I)
958     Protocols.push_back((*I)->getNameAsString());
959 
960 
961 
962   // Get the superclass pointer.
963   llvm::Constant *SuperClass;
964   if (!SuperClassName.empty()) {
965     SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
966   } else {
967     SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
968   }
969   // Empty vector used to construct empty method lists
970   llvm::SmallVector<llvm::Constant*, 1>  empty;
971   // Generate the method and instance variable lists
972   llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
973       InstanceMethodSels, InstanceMethodTypes, false);
974   llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
975       ClassMethodSels, ClassMethodTypes, true);
976   llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
977       IvarOffsets);
978   //Generate metaclass for class methods
979   llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
980       NULLPtr, 0x2L, /*name*/"", 0, Zeros[0], GenerateIvarList(
981         empty, empty, empty), ClassMethodList, NULLPtr);
982 
983   // Generate the class structure
984   llvm::Constant *ClassStruct =
985     GenerateClassStructure(MetaClassStruct, SuperClass, 0x1L,
986                            ClassName.c_str(), 0,
987       llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
988       MethodList, GenerateProtocolList(Protocols));
989 
990   // Resolve the class aliases, if they exist.
991   if (ClassPtrAlias) {
992     ClassPtrAlias->setAliasee(
993         llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
994     ClassPtrAlias = 0;
995   }
996   if (MetaClassPtrAlias) {
997     MetaClassPtrAlias->setAliasee(
998         llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
999     MetaClassPtrAlias = 0;
1000   }
1001 
1002   // Add class structure to list to be added to the symtab later
1003   ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
1004   Classes.push_back(ClassStruct);
1005 }
1006 
1007 void CGObjCGNU::MergeMetadataGlobals(
1008                           std::vector<llvm::Constant*> &UsedArray) {
1009 }
1010 
1011 llvm::Function *CGObjCGNU::ModuleInitFunction() {
1012   // Only emit an ObjC load function if no Objective-C stuff has been called
1013   if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
1014       ExistingProtocols.empty() && TypedSelectors.empty() &&
1015       UntypedSelectors.empty())
1016     return NULL;
1017 
1018   const llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
1019           SelectorTy->getElementType());
1020   const llvm::Type *SelStructPtrTy = SelectorTy;
1021   bool isSelOpaque = false;
1022   if (SelStructTy == 0) {
1023     SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, NULL);
1024     SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
1025     isSelOpaque = true;
1026   }
1027 
1028   // Name the ObjC types to make the IR a bit easier to read
1029   TheModule.addTypeName(".objc_selector", SelStructPtrTy);
1030   TheModule.addTypeName(".objc_id", IdTy);
1031   TheModule.addTypeName(".objc_imp", IMPTy);
1032 
1033   std::vector<llvm::Constant*> Elements;
1034   llvm::Constant *Statics = NULLPtr;
1035   // Generate statics list:
1036   if (ConstantStrings.size()) {
1037     llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
1038         ConstantStrings.size() + 1);
1039     ConstantStrings.push_back(NULLPtr);
1040     Elements.push_back(MakeConstantString("NSConstantString",
1041           ".objc_static_class_name"));
1042     Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
1043        ConstantStrings));
1044     llvm::StructType *StaticsListTy =
1045       llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
1046     llvm::Type *StaticsListPtrTy = llvm::PointerType::getUnqual(StaticsListTy);
1047     Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
1048     llvm::ArrayType *StaticsListArrayTy =
1049       llvm::ArrayType::get(StaticsListPtrTy, 2);
1050     Elements.clear();
1051     Elements.push_back(Statics);
1052     Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
1053     Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
1054     Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
1055   }
1056   // Array of classes, categories, and constant objects
1057   llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
1058       Classes.size() + Categories.size()  + 2);
1059   llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
1060                                                      llvm::Type::Int16Ty,
1061                                                      llvm::Type::Int16Ty,
1062                                                      ClassListTy, NULL);
1063 
1064   Elements.clear();
1065   // Pointer to an array of selectors used in this module.
1066   std::vector<llvm::Constant*> Selectors;
1067   for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
1068      iter = TypedSelectors.begin(), iterEnd = TypedSelectors.end();
1069      iter != iterEnd ; ++iter) {
1070     Elements.push_back(MakeConstantString(iter->first.first, ".objc_sel_name"));
1071     Elements.push_back(MakeConstantString(iter->first.second,
1072                                           ".objc_sel_types"));
1073     Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
1074     Elements.clear();
1075   }
1076   for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1077       iter = UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
1078       iter != iterEnd; ++iter) {
1079     Elements.push_back(
1080         MakeConstantString(iter->getKeyData(), ".objc_sel_name"));
1081     Elements.push_back(NULLPtr);
1082     Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
1083     Elements.clear();
1084   }
1085   Elements.push_back(NULLPtr);
1086   Elements.push_back(NULLPtr);
1087   Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
1088   Elements.clear();
1089   // Number of static selectors
1090   Elements.push_back(llvm::ConstantInt::get(LongTy, Selectors.size() ));
1091   llvm::Constant *SelectorList = MakeGlobal(
1092           llvm::ArrayType::get(SelStructTy, Selectors.size()), Selectors,
1093           ".objc_selector_list");
1094   Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
1095     SelStructPtrTy));
1096 
1097   // Now that all of the static selectors exist, create pointers to them.
1098   int index = 0;
1099   for (std::map<TypedSelector, llvm::GlobalAlias*>::iterator
1100      iter=TypedSelectors.begin(), iterEnd =TypedSelectors.end();
1101      iter != iterEnd; ++iter) {
1102     llvm::Constant *Idxs[] = {Zeros[0],
1103       llvm::ConstantInt::get(llvm::Type::Int32Ty, index++), Zeros[0]};
1104     llvm::Constant *SelPtr = new llvm::GlobalVariable(TheModule, SelStructPtrTy,
1105         true, llvm::GlobalValue::InternalLinkage,
1106         llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
1107         ".objc_sel_ptr");
1108     // If selectors are defined as an opaque type, cast the pointer to this
1109     // type.
1110     if (isSelOpaque) {
1111       SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1112         llvm::PointerType::getUnqual(SelectorTy));
1113     }
1114     (*iter).second->setAliasee(SelPtr);
1115   }
1116   for (llvm::StringMap<llvm::GlobalAlias*>::iterator
1117       iter=UntypedSelectors.begin(), iterEnd = UntypedSelectors.end();
1118       iter != iterEnd; iter++) {
1119     llvm::Constant *Idxs[] = {Zeros[0],
1120       llvm::ConstantInt::get(llvm::Type::Int32Ty, index++), Zeros[0]};
1121     llvm::Constant *SelPtr = new llvm::GlobalVariable(TheModule, SelStructPtrTy,
1122         true, llvm::GlobalValue::InternalLinkage,
1123         llvm::ConstantExpr::getGetElementPtr(SelectorList, Idxs, 2),
1124         ".objc_sel_ptr");
1125     // If selectors are defined as an opaque type, cast the pointer to this
1126     // type.
1127     if (isSelOpaque) {
1128       SelPtr = llvm::ConstantExpr::getBitCast(SelPtr,
1129         llvm::PointerType::getUnqual(SelectorTy));
1130     }
1131     (*iter).second->setAliasee(SelPtr);
1132   }
1133   // Number of classes defined.
1134   Elements.push_back(llvm::ConstantInt::get(llvm::Type::Int16Ty,
1135         Classes.size()));
1136   // Number of categories defined
1137   Elements.push_back(llvm::ConstantInt::get(llvm::Type::Int16Ty,
1138         Categories.size()));
1139   // Create an array of classes, then categories, then static object instances
1140   Classes.insert(Classes.end(), Categories.begin(), Categories.end());
1141   //  NULL-terminated list of static object instances (mainly constant strings)
1142   Classes.push_back(Statics);
1143   Classes.push_back(NULLPtr);
1144   llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
1145   Elements.push_back(ClassList);
1146   // Construct the symbol table
1147   llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
1148 
1149   // The symbol table is contained in a module which has some version-checking
1150   // constants
1151   llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
1152       PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy), NULL);
1153   Elements.clear();
1154   // Runtime version used for compatibility checking.
1155   if (CGM.getContext().getLangOptions().ObjCNonFragileABI) {
1156 	Elements.push_back(llvm::ConstantInt::get(LongTy,
1157         NonFragileRuntimeVersion));
1158   } else {
1159     Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
1160   }
1161   // sizeof(ModuleTy)
1162   llvm::TargetData td = llvm::TargetData::TargetData(&TheModule);
1163   Elements.push_back(llvm::ConstantInt::get(LongTy, td.getTypeSizeInBits(ModuleTy)/8));
1164   //FIXME: Should be the path to the file where this module was declared
1165   Elements.push_back(NULLPtr);
1166   Elements.push_back(SymTab);
1167   llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
1168 
1169   // Create the load function calling the runtime entry point with the module
1170   // structure
1171   llvm::Function * LoadFunction = llvm::Function::Create(
1172       llvm::FunctionType::get(llvm::Type::VoidTy, false),
1173       llvm::GlobalValue::InternalLinkage, ".objc_load_function",
1174       &TheModule);
1175   llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", LoadFunction);
1176   CGBuilderTy Builder(TheModule.getContext());
1177   Builder.SetInsertPoint(EntryBB);
1178 
1179   std::vector<const llvm::Type*> Params(1,
1180       llvm::PointerType::getUnqual(ModuleTy));
1181   llvm::Value *Register = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1182         llvm::Type::VoidTy, Params, true), "__objc_exec_class");
1183   Builder.CreateCall(Register, Module);
1184   Builder.CreateRetVoid();
1185 
1186   return LoadFunction;
1187 }
1188 
1189 llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
1190                                           const ObjCContainerDecl *CD) {
1191   const ObjCCategoryImplDecl *OCD =
1192     dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
1193   std::string CategoryName = OCD ? OCD->getNameAsString() : "";
1194   std::string ClassName = OMD->getClassInterface()->getNameAsString();
1195   std::string MethodName = OMD->getSelector().getAsString();
1196   bool isClassMethod = !OMD->isInstanceMethod();
1197 
1198   CodeGenTypes &Types = CGM.getTypes();
1199   const llvm::FunctionType *MethodTy =
1200     Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
1201   std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
1202       MethodName, isClassMethod);
1203 
1204   llvm::Function *Method = llvm::Function::Create(MethodTy,
1205       llvm::GlobalValue::InternalLinkage,
1206       FunctionName,
1207       &TheModule);
1208   return Method;
1209 }
1210 
1211 llvm::Function *CGObjCGNU::GetPropertyGetFunction() {
1212 	std::vector<const llvm::Type*> Params;
1213 	const llvm::Type *BoolTy =
1214 		CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
1215 	Params.push_back(IdTy);
1216 	Params.push_back(SelectorTy);
1217 	// FIXME: Using LongTy for ptrdiff_t is probably broken on Win64
1218 	Params.push_back(LongTy);
1219 	Params.push_back(BoolTy);
1220 	// void objc_getProperty (id, SEL, ptrdiff_t, bool)
1221 	const llvm::FunctionType *FTy =
1222 		llvm::FunctionType::get(IdTy, Params, false);
1223 	return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1224 				"objc_getProperty"));
1225 }
1226 
1227 llvm::Function *CGObjCGNU::GetPropertySetFunction() {
1228 	std::vector<const llvm::Type*> Params;
1229 	const llvm::Type *BoolTy =
1230 		CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
1231 	Params.push_back(IdTy);
1232 	Params.push_back(SelectorTy);
1233 	// FIXME: Using LongTy for ptrdiff_t is probably broken on Win64
1234 	Params.push_back(LongTy);
1235 	Params.push_back(IdTy);
1236 	Params.push_back(BoolTy);
1237 	Params.push_back(BoolTy);
1238 	// void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
1239 	const llvm::FunctionType *FTy =
1240 		llvm::FunctionType::get(llvm::Type::VoidTy, Params, false);
1241 	return cast<llvm::Function>(CGM.CreateRuntimeFunction(FTy,
1242 				"objc_setProperty"));
1243 }
1244 
1245 llvm::Function *CGObjCGNU::EnumerationMutationFunction() {
1246   std::vector<const llvm::Type*> Params(1, IdTy);
1247   return cast<llvm::Function>(CGM.CreateRuntimeFunction(
1248         llvm::FunctionType::get(llvm::Type::VoidTy, Params, true),
1249         "objc_enumerationMutation"));
1250 }
1251 
1252 void CGObjCGNU::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1253                                           const Stmt &S) {
1254   // Pointer to the personality function
1255   llvm::Constant *Personality =
1256     CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
1257           true),
1258         "__gnu_objc_personality_v0");
1259   Personality = llvm::ConstantExpr::getBitCast(Personality, PtrTy);
1260   std::vector<const llvm::Type*> Params;
1261   Params.push_back(PtrTy);
1262   llvm::Value *RethrowFn =
1263     CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
1264           Params, false), "_Unwind_Resume_or_Rethrow");
1265 
1266   bool isTry = isa<ObjCAtTryStmt>(S);
1267   llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1268   llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
1269   llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
1270   llvm::BasicBlock *CatchInCatch = CGF.createBasicBlock("catch.rethrow");
1271   llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1272   llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1273   llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
1274 
1275   // GNU runtime does not currently support @synchronized()
1276   if (!isTry) {
1277     std::vector<const llvm::Type*> Args(1, IdTy);
1278     llvm::FunctionType *FTy =
1279       llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
1280     llvm::Value *SyncEnter = CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
1281     llvm::Value *SyncArg =
1282       CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1283     SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy);
1284     CGF.Builder.CreateCall(SyncEnter, SyncArg);
1285   }
1286 
1287 
1288   // Push an EH context entry, used for handling rethrows and jumps
1289   // through finally.
1290   CGF.PushCleanupBlock(FinallyBlock);
1291 
1292   // Emit the statements in the @try {} block
1293   CGF.setInvokeDest(TryHandler);
1294 
1295   CGF.EmitBlock(TryBlock);
1296   CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
1297                      : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
1298 
1299   // Jump to @finally if there is no exception
1300   CGF.EmitBranchThroughCleanup(FinallyEnd);
1301 
1302   // Emit the handlers
1303   CGF.EmitBlock(TryHandler);
1304 
1305   // Get the correct versions of the exception handling intrinsics
1306   llvm::TargetData td = llvm::TargetData::TargetData(&TheModule);
1307   int PointerWidth = td.getTypeSizeInBits(PtrTy);
1308   assert((PointerWidth == 32 || PointerWidth == 64) &&
1309     "Can't yet handle exceptions if pointers are not 32 or 64 bits");
1310   llvm::Value *llvm_eh_exception =
1311     CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
1312   llvm::Value *llvm_eh_selector = PointerWidth == 32 ?
1313     CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i32) :
1314     CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
1315   llvm::Value *llvm_eh_typeid_for = PointerWidth == 32 ?
1316     CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i32) :
1317     CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
1318 
1319   // Exception object
1320   llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
1321   llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
1322 
1323   llvm::SmallVector<llvm::Value*, 8> ESelArgs;
1324   llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
1325 
1326   ESelArgs.push_back(Exc);
1327   ESelArgs.push_back(Personality);
1328 
1329   bool HasCatchAll = false;
1330   // Only @try blocks are allowed @catch blocks, but both can have @finally
1331   if (isTry) {
1332     if (const ObjCAtCatchStmt* CatchStmt =
1333       cast<ObjCAtTryStmt>(S).getCatchStmts())  {
1334       CGF.setInvokeDest(CatchInCatch);
1335 
1336       for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
1337         const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
1338         Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
1339 
1340         // @catch() and @catch(id) both catch any ObjC exception
1341         if (!CatchDecl || CGF.getContext().isObjCIdType(CatchDecl->getType())
1342             || CatchDecl->getType()->isObjCQualifiedIdType()) {
1343           // Use i8* null here to signal this is a catch all, not a cleanup.
1344           ESelArgs.push_back(NULLPtr);
1345           HasCatchAll = true;
1346           // No further catches after this one will ever by reached
1347           break;
1348         }
1349 
1350         // All other types should be Objective-C interface pointer types.
1351         const PointerType *PT = CatchDecl->getType()->getAsPointerType();
1352         assert(PT && "Invalid @catch type.");
1353         const ObjCInterfaceType *IT =
1354           PT->getPointeeType()->getAsObjCInterfaceType();
1355         assert(IT && "Invalid @catch type.");
1356         llvm::Value *EHType =
1357           MakeConstantString(IT->getDecl()->getNameAsString());
1358         ESelArgs.push_back(EHType);
1359       }
1360     }
1361   }
1362 
1363   // We use a cleanup unless there was already a catch all.
1364   if (!HasCatchAll) {
1365     ESelArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
1366     Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
1367   }
1368 
1369   // Find which handler was matched.
1370   llvm::Value *ESelector = CGF.Builder.CreateCall(llvm_eh_selector,
1371       ESelArgs.begin(), ESelArgs.end(), "selector");
1372 
1373   for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
1374     const ParmVarDecl *CatchParam = Handlers[i].first;
1375     const Stmt *CatchBody = Handlers[i].second;
1376 
1377     llvm::BasicBlock *Next = 0;
1378 
1379     // The last handler always matches.
1380     if (i + 1 != e) {
1381       assert(CatchParam && "Only last handler can be a catch all.");
1382 
1383       // Test whether this block matches the type for the selector and branch
1384       // to Match if it does, or to the next BB if it doesn't.
1385       llvm::BasicBlock *Match = CGF.createBasicBlock("match");
1386       Next = CGF.createBasicBlock("catch.next");
1387       llvm::Value *Id = CGF.Builder.CreateCall(llvm_eh_typeid_for,
1388           CGF.Builder.CreateBitCast(ESelArgs[i+2], PtrTy));
1389       CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(ESelector, Id), Match,
1390           Next);
1391 
1392       CGF.EmitBlock(Match);
1393     }
1394 
1395     if (CatchBody) {
1396       llvm::Value *ExcObject = CGF.Builder.CreateBitCast(Exc,
1397           CGF.ConvertType(CatchParam->getType()));
1398 
1399       // Bind the catch parameter if it exists.
1400       if (CatchParam) {
1401         // CatchParam is a ParmVarDecl because of the grammar
1402         // construction used to handle this, but for codegen purposes
1403         // we treat this as a local decl.
1404         CGF.EmitLocalBlockVarDecl(*CatchParam);
1405         CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
1406       }
1407 
1408       CGF.ObjCEHValueStack.push_back(ExcObject);
1409       CGF.EmitStmt(CatchBody);
1410       CGF.ObjCEHValueStack.pop_back();
1411 
1412       CGF.EmitBranchThroughCleanup(FinallyEnd);
1413 
1414       if (Next)
1415         CGF.EmitBlock(Next);
1416     } else {
1417       assert(!Next && "catchup should be last handler.");
1418 
1419       CGF.Builder.CreateStore(Exc, RethrowPtr);
1420       CGF.EmitBranchThroughCleanup(FinallyRethrow);
1421     }
1422   }
1423   // The @finally block is a secondary landing pad for any exceptions thrown in
1424   // @catch() blocks
1425   CGF.EmitBlock(CatchInCatch);
1426   Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
1427   ESelArgs.clear();
1428   ESelArgs.push_back(Exc);
1429   ESelArgs.push_back(Personality);
1430   ESelArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
1431   CGF.Builder.CreateCall(llvm_eh_selector, ESelArgs.begin(), ESelArgs.end(),
1432       "selector");
1433   CGF.Builder.CreateCall(llvm_eh_typeid_for,
1434       CGF.Builder.CreateIntToPtr(ESelArgs[2], PtrTy));
1435   CGF.Builder.CreateStore(Exc, RethrowPtr);
1436   CGF.EmitBranchThroughCleanup(FinallyRethrow);
1437 
1438   CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
1439 
1440   CGF.setInvokeDest(PrevLandingPad);
1441 
1442   CGF.EmitBlock(FinallyBlock);
1443 
1444 
1445   if (isTry) {
1446     if (const ObjCAtFinallyStmt* FinallyStmt =
1447         cast<ObjCAtTryStmt>(S).getFinallyStmt())
1448       CGF.EmitStmt(FinallyStmt->getFinallyBody());
1449   } else {
1450     // Emit 'objc_sync_exit(expr)' as finally's sole statement for
1451     // @synchronized.
1452     std::vector<const llvm::Type*> Args(1, IdTy);
1453     llvm::FunctionType *FTy =
1454       llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
1455     llvm::Value *SyncExit = CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
1456     llvm::Value *SyncArg =
1457       CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
1458     SyncArg = CGF.Builder.CreateBitCast(SyncArg, IdTy);
1459     CGF.Builder.CreateCall(SyncExit, SyncArg);
1460   }
1461 
1462   if (Info.SwitchBlock)
1463     CGF.EmitBlock(Info.SwitchBlock);
1464   if (Info.EndBlock)
1465     CGF.EmitBlock(Info.EndBlock);
1466 
1467   // Branch around the rethrow code.
1468   CGF.EmitBranch(FinallyEnd);
1469 
1470   CGF.EmitBlock(FinallyRethrow);
1471   CGF.Builder.CreateCall(RethrowFn, CGF.Builder.CreateLoad(RethrowPtr));
1472   CGF.Builder.CreateUnreachable();
1473 
1474   CGF.EmitBlock(FinallyEnd);
1475 
1476 }
1477 
1478 void CGObjCGNU::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1479                               const ObjCAtThrowStmt &S) {
1480   llvm::Value *ExceptionAsObject;
1481 
1482   std::vector<const llvm::Type*> Args(1, IdTy);
1483   llvm::FunctionType *FTy =
1484     llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
1485   llvm::Value *ThrowFn =
1486     CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
1487 
1488   if (const Expr *ThrowExpr = S.getThrowExpr()) {
1489     llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
1490     ExceptionAsObject = Exception;
1491   } else {
1492     assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
1493            "Unexpected rethrow outside @catch block.");
1494     ExceptionAsObject = CGF.ObjCEHValueStack.back();
1495   }
1496   ExceptionAsObject =
1497       CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy, "tmp");
1498 
1499   // Note: This may have to be an invoke, if we want to support constructs like:
1500   // @try {
1501   //  @throw(obj);
1502   // }
1503   // @catch(id) ...
1504   //
1505   // This is effectively turning @throw into an incredibly-expensive goto, but
1506   // it may happen as a result of inlining followed by missed optimizations, or
1507   // as a result of stupidity.
1508   llvm::BasicBlock *UnwindBB = CGF.getInvokeDest();
1509   if (!UnwindBB) {
1510     CGF.Builder.CreateCall(ThrowFn, ExceptionAsObject);
1511     CGF.Builder.CreateUnreachable();
1512   } else {
1513     CGF.Builder.CreateInvoke(ThrowFn, UnwindBB, UnwindBB, &ExceptionAsObject,
1514         &ExceptionAsObject+1);
1515   }
1516   // Clear the insertion point to indicate we are in unreachable code.
1517   CGF.Builder.ClearInsertionPoint();
1518 }
1519 
1520 llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
1521                                           llvm::Value *AddrWeakObj)
1522 {
1523   return 0;
1524 }
1525 
1526 void CGObjCGNU::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1527                                    llvm::Value *src, llvm::Value *dst)
1528 {
1529   return;
1530 }
1531 
1532 void CGObjCGNU::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1533                                      llvm::Value *src, llvm::Value *dst)
1534 {
1535   return;
1536 }
1537 
1538 void CGObjCGNU::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1539                                    llvm::Value *src, llvm::Value *dst)
1540 {
1541   return;
1542 }
1543 
1544 void CGObjCGNU::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1545                                          llvm::Value *src, llvm::Value *dst)
1546 {
1547   return;
1548 }
1549 
1550 void CGObjCGNU::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
1551                                          llvm::Value *DestPtr,
1552                                          llvm::Value *SrcPtr,
1553                                          unsigned long size) {
1554   return;
1555 }
1556 
1557 llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
1558                               const ObjCInterfaceDecl *ID,
1559                               const ObjCIvarDecl *Ivar) {
1560   const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
1561     + '.' + Ivar->getNameAsString();
1562   // Emit the variable and initialize it with what we think the correct value
1563   // is.  This allows code compiled with non-fragile ivars to work correctly
1564   // when linked against code which isn't (most of the time).
1565   llvm::GlobalVariable *IvarOffsetGV = CGM.getModule().getGlobalVariable(Name);
1566   if (!IvarOffsetGV) {
1567     uint64_t Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
1568     llvm::ConstantInt *OffsetGuess =
1569       llvm::ConstantInt::get(LongTy, Offset, "ivar");
1570     IvarOffsetGV = new llvm::GlobalVariable(TheModule, LongTy, false,
1571         llvm::GlobalValue::CommonLinkage, OffsetGuess, Name);
1572   }
1573   return IvarOffsetGV;
1574 }
1575 
1576 LValue CGObjCGNU::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1577                                        QualType ObjectTy,
1578                                        llvm::Value *BaseValue,
1579                                        const ObjCIvarDecl *Ivar,
1580                                        unsigned CVRQualifiers) {
1581   const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
1582   return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
1583                                   EmitIvarOffset(CGF, ID, Ivar));
1584 }
1585 static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
1586                                                   const ObjCInterfaceDecl *OID,
1587                                                   const ObjCIvarDecl *OIVD) {
1588   llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
1589   Context.ShallowCollectObjCIvars(OID, Ivars);
1590   for (unsigned k = 0, e = Ivars.size(); k != e; ++k) {
1591     if (OIVD == Ivars[k])
1592       return OID;
1593   }
1594 
1595   // Otherwise check in the super class.
1596   if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1597     return FindIvarInterface(Context, Super, OIVD);
1598 
1599   return 0;
1600 }
1601 
1602 llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
1603                          const ObjCInterfaceDecl *Interface,
1604                          const ObjCIvarDecl *Ivar) {
1605   if (CGF.getContext().getLangOptions().ObjCNonFragileABI)
1606   {
1607     Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
1608     return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
1609         false, "ivar");
1610   }
1611   uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
1612   return llvm::ConstantInt::get(LongTy, Offset, "ivar");
1613 }
1614 
1615 CodeGen::CGObjCRuntime *CodeGen::CreateGNUObjCRuntime(CodeGen::CodeGenModule &CGM){
1616   return new CGObjCGNU(CGM);
1617 }
1618