CGObjCMac.cpp revision 5384b0990ea6995121fd4bad0855e96d41dcad18
1//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
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 Apple runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
15
16#include "CodeGenModule.h"
17#include "CodeGenFunction.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/StmtObjC.h"
22#include "clang/Basic/LangOptions.h"
23
24#include "llvm/Intrinsics.h"
25#include "llvm/Module.h"
26#include "llvm/ADT/DenseSet.h"
27#include "llvm/Target/TargetData.h"
28#include <sstream>
29
30using namespace clang;
31using namespace CodeGen;
32
33// Common CGObjCRuntime functions, these don't belong here, but they
34// don't belong in CGObjCRuntime either so we will live with it for
35// now.
36
37const llvm::StructType *
38CGObjCRuntime::GetConcreteClassStruct(CodeGen::CodeGenModule &CGM,
39                                      const ObjCInterfaceDecl *OID) {
40  assert(!OID->isForwardDecl() && "Invalid interface decl!");
41  const RecordDecl *RD = CGM.getContext().addRecordToClass(OID);
42  return cast<llvm::StructType>(CGM.getTypes().ConvertTagDeclType(RD));
43}
44
45
46/// LookupFieldDeclForIvar - looks up a field decl in the laid out
47/// storage which matches this 'ivar'.
48///
49static const FieldDecl *LookupFieldDeclForIvar(ASTContext &Context,
50                                               const ObjCInterfaceDecl *OID,
51                                               const ObjCIvarDecl *OIVD,
52                                               const ObjCInterfaceDecl *&Found) {
53  assert(!OID->isForwardDecl() && "Invalid interface decl!");
54  const RecordDecl *RecordForDecl = Context.addRecordToClass(OID);
55  assert(RecordForDecl && "lookupFieldDeclForIvar no storage for class");
56  DeclContext::lookup_const_result Lookup =
57    RecordForDecl->lookup(Context, OIVD->getDeclName());
58
59  if (Lookup.first != Lookup.second) {
60    Found = OID;
61    return cast<FieldDecl>(*Lookup.first);
62  }
63
64  // If lookup failed, try the superclass.
65  //
66  // FIXME: This is slow, we shouldn't need to do this.
67  const ObjCInterfaceDecl *Super = OID->getSuperClass();
68  assert(OID && "field decl not found!");
69  return LookupFieldDeclForIvar(Context, Super, OIVD, Found);
70}
71
72static uint64_t LookupFieldBitOffset(CodeGen::CodeGenModule &CGM,
73                                     const ObjCInterfaceDecl *OID,
74                                     const ObjCIvarDecl *Ivar) {
75  assert(!OID->isForwardDecl() && "Invalid interface decl!");
76  const ObjCInterfaceDecl *Container;
77  const FieldDecl *Field =
78    LookupFieldDeclForIvar(CGM.getContext(), OID, Ivar, Container);
79  const llvm::StructType *STy =
80    CGObjCRuntime::GetConcreteClassStruct(CGM, Container);
81  const llvm::StructLayout *Layout =
82    CGM.getTargetData().getStructLayout(STy);
83  if (!Field->isBitField())
84    return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field)) * 8;
85
86  // FIXME. Must be a better way of getting a bitfield base offset.
87  CodeGenTypes::BitFieldInfo BFI = CGM.getTypes().getBitFieldInfo(Field);
88  // FIXME: The "field no" for bitfields is something completely
89  // different; it is the offset in multiples of the base type size!
90  uint64_t Offset = CGM.getTypes().getLLVMFieldNo(Field);
91  const llvm::Type *Ty =
92    CGM.getTypes().ConvertTypeForMemRecursive(Field->getType());
93  Offset *= CGM.getTypes().getTargetData().getTypePaddedSizeInBits(Ty);
94  return Offset + BFI.Begin;
95}
96
97uint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
98                                              const ObjCInterfaceDecl *OID,
99                                              const ObjCIvarDecl *Ivar) {
100  return LookupFieldBitOffset(CGM, OID, Ivar) / 8;
101}
102
103LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
104                                               const ObjCInterfaceDecl *OID,
105                                               llvm::Value *BaseValue,
106                                               const ObjCIvarDecl *Ivar,
107                                               unsigned CVRQualifiers,
108                                               llvm::Value *Offset) {
109  // We need to compute the bit offset for the bit-field, the offset
110  // is to the byte.
111  uint64_t BitOffset = LookupFieldBitOffset(CGF.CGM, OID, Ivar) % 8;
112
113  // Compute (type*) ( (char *) BaseValue + Offset)
114  llvm::Type *I8Ptr = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
115  QualType IvarTy = Ivar->getType();
116  const llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);
117  llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, I8Ptr);
118  V = CGF.Builder.CreateGEP(V, Offset, "add.ptr");
119  V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));
120
121  if (Ivar->isBitField()) {
122    uint64_t BitFieldSize =
123      Ivar->getBitWidth()->EvaluateAsInt(CGF.getContext()).getZExtValue();
124    return LValue::MakeBitfield(V, BitOffset, BitFieldSize,
125                                IvarTy->isSignedIntegerType(),
126                                IvarTy.getCVRQualifiers()|CVRQualifiers);
127  }
128
129  LValue LV = LValue::MakeAddr(V, IvarTy.getCVRQualifiers()|CVRQualifiers,
130                               CGF.CGM.getContext().getObjCGCAttrKind(IvarTy));
131  LValue::SetObjCIvar(LV, true);
132  return LV;
133}
134
135///
136
137namespace {
138
139  typedef std::vector<llvm::Constant*> ConstantVector;
140
141  // FIXME: We should find a nicer way to make the labels for
142  // metadata, string concatenation is lame.
143
144class ObjCCommonTypesHelper {
145protected:
146  CodeGen::CodeGenModule &CGM;
147
148public:
149  const llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
150  const llvm::Type *Int8PtrTy;
151
152  /// ObjectPtrTy - LLVM type for object handles (typeof(id))
153  const llvm::Type *ObjectPtrTy;
154
155  /// PtrObjectPtrTy - LLVM type for id *
156  const llvm::Type *PtrObjectPtrTy;
157
158  /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
159  const llvm::Type *SelectorPtrTy;
160  /// ProtocolPtrTy - LLVM type for external protocol handles
161  /// (typeof(Protocol))
162  const llvm::Type *ExternalProtocolPtrTy;
163
164  // SuperCTy - clang type for struct objc_super.
165  QualType SuperCTy;
166  // SuperPtrCTy - clang type for struct objc_super *.
167  QualType SuperPtrCTy;
168
169  /// SuperTy - LLVM type for struct objc_super.
170  const llvm::StructType *SuperTy;
171  /// SuperPtrTy - LLVM type for struct objc_super *.
172  const llvm::Type *SuperPtrTy;
173
174  /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
175  /// in GCC parlance).
176  const llvm::StructType *PropertyTy;
177
178  /// PropertyListTy - LLVM type for struct objc_property_list
179  /// (_prop_list_t in GCC parlance).
180  const llvm::StructType *PropertyListTy;
181  /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
182  const llvm::Type *PropertyListPtrTy;
183
184  // MethodTy - LLVM type for struct objc_method.
185  const llvm::StructType *MethodTy;
186
187  /// CacheTy - LLVM type for struct objc_cache.
188  const llvm::Type *CacheTy;
189  /// CachePtrTy - LLVM type for struct objc_cache *.
190  const llvm::Type *CachePtrTy;
191
192  llvm::Constant *getGetPropertyFn() {
193    CodeGen::CodeGenTypes &Types = CGM.getTypes();
194    ASTContext &Ctx = CGM.getContext();
195    // id objc_getProperty (id, SEL, ptrdiff_t, bool)
196    llvm::SmallVector<QualType,16> Params;
197    QualType IdType = Ctx.getObjCIdType();
198    QualType SelType = Ctx.getObjCSelType();
199    Params.push_back(IdType);
200    Params.push_back(SelType);
201    Params.push_back(Ctx.LongTy);
202    Params.push_back(Ctx.BoolTy);
203    const llvm::FunctionType *FTy =
204      Types.GetFunctionType(Types.getFunctionInfo(IdType, Params), false);
205    return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
206  }
207
208  llvm::Constant *getSetPropertyFn() {
209    CodeGen::CodeGenTypes &Types = CGM.getTypes();
210    ASTContext &Ctx = CGM.getContext();
211    // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
212    llvm::SmallVector<QualType,16> Params;
213    QualType IdType = Ctx.getObjCIdType();
214    QualType SelType = Ctx.getObjCSelType();
215    Params.push_back(IdType);
216    Params.push_back(SelType);
217    Params.push_back(Ctx.LongTy);
218    Params.push_back(IdType);
219    Params.push_back(Ctx.BoolTy);
220    Params.push_back(Ctx.BoolTy);
221    const llvm::FunctionType *FTy =
222      Types.GetFunctionType(Types.getFunctionInfo(Ctx.VoidTy, Params), false);
223    return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
224  }
225
226  llvm::Constant *getEnumerationMutationFn() {
227    // void objc_enumerationMutation (id)
228    std::vector<const llvm::Type*> Args;
229    Args.push_back(ObjectPtrTy);
230    llvm::FunctionType *FTy =
231      llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
232    return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
233  }
234
235  /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
236  llvm::Constant *getGcReadWeakFn() {
237    // id objc_read_weak (id *)
238    std::vector<const llvm::Type*> Args;
239    Args.push_back(ObjectPtrTy->getPointerTo());
240    llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
241    return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
242  }
243
244  /// GcAssignWeakFn -- LLVM objc_assign_weak function.
245  llvm::Constant *getGcAssignWeakFn() {
246    // id objc_assign_weak (id, id *)
247    std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
248    Args.push_back(ObjectPtrTy->getPointerTo());
249    llvm::FunctionType *FTy =
250      llvm::FunctionType::get(ObjectPtrTy, Args, false);
251    return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
252  }
253
254  /// GcAssignGlobalFn -- LLVM objc_assign_global function.
255  llvm::Constant *getGcAssignGlobalFn() {
256    // id objc_assign_global(id, id *)
257    std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
258    Args.push_back(ObjectPtrTy->getPointerTo());
259    llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
260    return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
261  }
262
263  /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
264  llvm::Constant *getGcAssignIvarFn() {
265    // id objc_assign_ivar(id, id *)
266    std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
267    Args.push_back(ObjectPtrTy->getPointerTo());
268    llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
269    return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
270  }
271
272  /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
273  llvm::Constant *getGcAssignStrongCastFn() {
274    // id objc_assign_global(id, id *)
275    std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
276    Args.push_back(ObjectPtrTy->getPointerTo());
277    llvm::FunctionType *FTy = llvm::FunctionType::get(ObjectPtrTy, Args, false);
278    return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
279  }
280
281  /// ExceptionThrowFn - LLVM objc_exception_throw function.
282  llvm::Constant *getExceptionThrowFn() {
283    // void objc_exception_throw(id)
284    std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
285    llvm::FunctionType *FTy =
286      llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
287    return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
288  }
289
290  /// SyncEnterFn - LLVM object_sync_enter function.
291  llvm::Constant *getSyncEnterFn() {
292    // void objc_sync_enter (id)
293    std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
294    llvm::FunctionType *FTy =
295      llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
296    return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
297  }
298
299  /// SyncExitFn - LLVM object_sync_exit function.
300  llvm::Constant *getSyncExitFn() {
301    // void objc_sync_exit (id)
302    std::vector<const llvm::Type*> Args(1, ObjectPtrTy);
303    llvm::FunctionType *FTy =
304    llvm::FunctionType::get(llvm::Type::VoidTy, Args, false);
305    return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
306  }
307
308  ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
309  ~ObjCCommonTypesHelper(){}
310};
311
312/// ObjCTypesHelper - Helper class that encapsulates lazy
313/// construction of varies types used during ObjC generation.
314class ObjCTypesHelper : public ObjCCommonTypesHelper {
315private:
316
317  llvm::Constant *getMessageSendFn() {
318    // id objc_msgSend (id, SEL, ...)
319    std::vector<const llvm::Type*> Params;
320    Params.push_back(ObjectPtrTy);
321    Params.push_back(SelectorPtrTy);
322    return
323      CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
324                                                        Params, true),
325                                "objc_msgSend");
326  }
327
328  llvm::Constant *getMessageSendStretFn() {
329    // id objc_msgSend_stret (id, SEL, ...)
330    std::vector<const llvm::Type*> Params;
331    Params.push_back(ObjectPtrTy);
332    Params.push_back(SelectorPtrTy);
333    return
334      CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
335                                                        Params, true),
336                                "objc_msgSend_stret");
337
338  }
339
340  llvm::Constant *getMessageSendFpretFn() {
341    // FIXME: This should be long double on x86_64?
342    // [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
343    std::vector<const llvm::Type*> Params;
344    Params.push_back(ObjectPtrTy);
345    Params.push_back(SelectorPtrTy);
346    return
347      CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
348                                                        Params,
349                                                        true),
350                                "objc_msgSend_fpret");
351
352  }
353
354  llvm::Constant *getMessageSendSuperFn() {
355    // id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
356    std::vector<const llvm::Type*> Params;
357    Params.push_back(SuperPtrTy);
358    Params.push_back(SelectorPtrTy);
359    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
360                                                             Params, true),
361                                     "objc_msgSendSuper");
362  }
363  llvm::Constant *getMessageSendSuperStretFn() {
364    // void objc_msgSendSuper_stret(void * stretAddr, struct objc_super *super,
365    //                              SEL op, ...)
366    std::vector<const llvm::Type*> Params;
367    Params.push_back(Int8PtrTy);
368    Params.push_back(SuperPtrTy);
369    Params.push_back(SelectorPtrTy);
370    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
371                                                             Params, true),
372                                     "objc_msgSendSuper_stret");
373  }
374
375  llvm::Constant *getMessageSendSuperFpretFn() {
376    // There is no objc_msgSendSuper_fpret? How can that work?
377    return getMessageSendSuperFn();
378  }
379
380public:
381  /// SymtabTy - LLVM type for struct objc_symtab.
382  const llvm::StructType *SymtabTy;
383  /// SymtabPtrTy - LLVM type for struct objc_symtab *.
384  const llvm::Type *SymtabPtrTy;
385  /// ModuleTy - LLVM type for struct objc_module.
386  const llvm::StructType *ModuleTy;
387
388  /// ProtocolTy - LLVM type for struct objc_protocol.
389  const llvm::StructType *ProtocolTy;
390  /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
391  const llvm::Type *ProtocolPtrTy;
392  /// ProtocolExtensionTy - LLVM type for struct
393  /// objc_protocol_extension.
394  const llvm::StructType *ProtocolExtensionTy;
395  /// ProtocolExtensionTy - LLVM type for struct
396  /// objc_protocol_extension *.
397  const llvm::Type *ProtocolExtensionPtrTy;
398  /// MethodDescriptionTy - LLVM type for struct
399  /// objc_method_description.
400  const llvm::StructType *MethodDescriptionTy;
401  /// MethodDescriptionListTy - LLVM type for struct
402  /// objc_method_description_list.
403  const llvm::StructType *MethodDescriptionListTy;
404  /// MethodDescriptionListPtrTy - LLVM type for struct
405  /// objc_method_description_list *.
406  const llvm::Type *MethodDescriptionListPtrTy;
407  /// ProtocolListTy - LLVM type for struct objc_property_list.
408  const llvm::Type *ProtocolListTy;
409  /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
410  const llvm::Type *ProtocolListPtrTy;
411  /// CategoryTy - LLVM type for struct objc_category.
412  const llvm::StructType *CategoryTy;
413  /// ClassTy - LLVM type for struct objc_class.
414  const llvm::StructType *ClassTy;
415  /// ClassPtrTy - LLVM type for struct objc_class *.
416  const llvm::Type *ClassPtrTy;
417  /// ClassExtensionTy - LLVM type for struct objc_class_ext.
418  const llvm::StructType *ClassExtensionTy;
419  /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
420  const llvm::Type *ClassExtensionPtrTy;
421  // IvarTy - LLVM type for struct objc_ivar.
422  const llvm::StructType *IvarTy;
423  /// IvarListTy - LLVM type for struct objc_ivar_list.
424  const llvm::Type *IvarListTy;
425  /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
426  const llvm::Type *IvarListPtrTy;
427  /// MethodListTy - LLVM type for struct objc_method_list.
428  const llvm::Type *MethodListTy;
429  /// MethodListPtrTy - LLVM type for struct objc_method_list *.
430  const llvm::Type *MethodListPtrTy;
431
432  /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
433  const llvm::Type *ExceptionDataTy;
434
435  /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
436  llvm::Constant *getExceptionTryEnterFn() {
437    std::vector<const llvm::Type*> Params;
438    Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
439    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
440                                                             Params, false),
441                                     "objc_exception_try_enter");
442  }
443
444  /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
445  llvm::Constant *getExceptionTryExitFn() {
446    std::vector<const llvm::Type*> Params;
447    Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
448    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
449                                                             Params, false),
450                                     "objc_exception_try_exit");
451  }
452
453  /// ExceptionExtractFn - LLVM objc_exception_extract function.
454  llvm::Constant *getExceptionExtractFn() {
455    std::vector<const llvm::Type*> Params;
456    Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
457    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
458                                                             Params, false),
459                                     "objc_exception_extract");
460
461  }
462
463  /// ExceptionMatchFn - LLVM objc_exception_match function.
464  llvm::Constant *getExceptionMatchFn() {
465    std::vector<const llvm::Type*> Params;
466    Params.push_back(ClassPtrTy);
467    Params.push_back(ObjectPtrTy);
468   return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
469                                                            Params, false),
470                                    "objc_exception_match");
471
472  }
473
474  /// SetJmpFn - LLVM _setjmp function.
475  llvm::Constant *getSetJmpFn() {
476    std::vector<const llvm::Type*> Params;
477    Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
478    return
479      CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
480                                                        Params, false),
481                                "_setjmp");
482
483  }
484
485public:
486  ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
487  ~ObjCTypesHelper() {}
488
489
490  llvm::Constant *getSendFn(bool IsSuper) {
491    return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
492  }
493
494  llvm::Constant *getSendStretFn(bool IsSuper) {
495    return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
496  }
497
498  llvm::Constant *getSendFpretFn(bool IsSuper) {
499    return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
500  }
501};
502
503/// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
504/// modern abi
505class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
506public:
507
508  // MethodListnfABITy - LLVM for struct _method_list_t
509  const llvm::StructType *MethodListnfABITy;
510
511  // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
512  const llvm::Type *MethodListnfABIPtrTy;
513
514  // ProtocolnfABITy = LLVM for struct _protocol_t
515  const llvm::StructType *ProtocolnfABITy;
516
517  // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
518  const llvm::Type *ProtocolnfABIPtrTy;
519
520  // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
521  const llvm::StructType *ProtocolListnfABITy;
522
523  // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
524  const llvm::Type *ProtocolListnfABIPtrTy;
525
526  // ClassnfABITy - LLVM for struct _class_t
527  const llvm::StructType *ClassnfABITy;
528
529  // ClassnfABIPtrTy - LLVM for struct _class_t*
530  const llvm::Type *ClassnfABIPtrTy;
531
532  // IvarnfABITy - LLVM for struct _ivar_t
533  const llvm::StructType *IvarnfABITy;
534
535  // IvarListnfABITy - LLVM for struct _ivar_list_t
536  const llvm::StructType *IvarListnfABITy;
537
538  // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
539  const llvm::Type *IvarListnfABIPtrTy;
540
541  // ClassRonfABITy - LLVM for struct _class_ro_t
542  const llvm::StructType *ClassRonfABITy;
543
544  // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
545  const llvm::Type *ImpnfABITy;
546
547  // CategorynfABITy - LLVM for struct _category_t
548  const llvm::StructType *CategorynfABITy;
549
550  // New types for nonfragile abi messaging.
551
552  // MessageRefTy - LLVM for:
553  // struct _message_ref_t {
554  //   IMP messenger;
555  //   SEL name;
556  // };
557  const llvm::StructType *MessageRefTy;
558  // MessageRefCTy - clang type for struct _message_ref_t
559  QualType MessageRefCTy;
560
561  // MessageRefPtrTy - LLVM for struct _message_ref_t*
562  const llvm::Type *MessageRefPtrTy;
563  // MessageRefCPtrTy - clang type for struct _message_ref_t*
564  QualType MessageRefCPtrTy;
565
566  // MessengerTy - Type of the messenger (shown as IMP above)
567  const llvm::FunctionType *MessengerTy;
568
569  // SuperMessageRefTy - LLVM for:
570  // struct _super_message_ref_t {
571  //   SUPER_IMP messenger;
572  //   SEL name;
573  // };
574  const llvm::StructType *SuperMessageRefTy;
575
576  // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
577  const llvm::Type *SuperMessageRefPtrTy;
578
579  llvm::Constant *getMessageSendFixupFn() {
580    // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
581    std::vector<const llvm::Type*> Params;
582    Params.push_back(ObjectPtrTy);
583    Params.push_back(MessageRefPtrTy);
584    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
585                                                             Params, true),
586                                     "objc_msgSend_fixup");
587  }
588
589  llvm::Constant *getMessageSendFpretFixupFn() {
590    // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
591    std::vector<const llvm::Type*> Params;
592    Params.push_back(ObjectPtrTy);
593    Params.push_back(MessageRefPtrTy);
594    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
595                                                             Params, true),
596                                     "objc_msgSend_fpret_fixup");
597  }
598
599  llvm::Constant *getMessageSendStretFixupFn() {
600    // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
601    std::vector<const llvm::Type*> Params;
602    Params.push_back(ObjectPtrTy);
603    Params.push_back(MessageRefPtrTy);
604    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
605                                                             Params, true),
606                                     "objc_msgSend_stret_fixup");
607  }
608
609  llvm::Constant *getMessageSendIdFixupFn() {
610    // id objc_msgSendId_fixup(id, struct message_ref_t*, ...)
611    std::vector<const llvm::Type*> Params;
612    Params.push_back(ObjectPtrTy);
613    Params.push_back(MessageRefPtrTy);
614    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
615                                                             Params, true),
616                                     "objc_msgSendId_fixup");
617  }
618
619  llvm::Constant *getMessageSendIdStretFixupFn() {
620    // id objc_msgSendId_stret_fixup(id, struct message_ref_t*, ...)
621    std::vector<const llvm::Type*> Params;
622    Params.push_back(ObjectPtrTy);
623    Params.push_back(MessageRefPtrTy);
624    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
625                                                             Params, true),
626                                     "objc_msgSendId_stret_fixup");
627  }
628  llvm::Constant *getMessageSendSuper2FixupFn() {
629    // id objc_msgSendSuper2_fixup (struct objc_super *,
630    //                              struct _super_message_ref_t*, ...)
631    std::vector<const llvm::Type*> Params;
632    Params.push_back(SuperPtrTy);
633    Params.push_back(SuperMessageRefPtrTy);
634    return  CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
635                                                              Params, true),
636                                      "objc_msgSendSuper2_fixup");
637  }
638
639  llvm::Constant *getMessageSendSuper2StretFixupFn() {
640    // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
641    //                                   struct _super_message_ref_t*, ...)
642    std::vector<const llvm::Type*> Params;
643    Params.push_back(SuperPtrTy);
644    Params.push_back(SuperMessageRefPtrTy);
645    return  CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
646                                                              Params, true),
647                                      "objc_msgSendSuper2_stret_fixup");
648  }
649
650
651
652  /// EHPersonalityPtr - LLVM value for an i8* to the Objective-C
653  /// exception personality function.
654  llvm::Value *getEHPersonalityPtr() {
655    llvm::Constant *Personality =
656      CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
657                                              std::vector<const llvm::Type*>(),
658                                                        true),
659                              "__objc_personality_v0");
660    return llvm::ConstantExpr::getBitCast(Personality, Int8PtrTy);
661  }
662
663  llvm::Constant *getUnwindResumeOrRethrowFn() {
664    std::vector<const llvm::Type*> Params;
665    Params.push_back(Int8PtrTy);
666    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
667                                                             Params, false),
668                                     "_Unwind_Resume_or_Rethrow");
669  }
670
671  llvm::Constant *getObjCEndCatchFn() {
672    std::vector<const llvm::Type*> Params;
673    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
674                                                             Params, false),
675                                     "objc_end_catch");
676
677  }
678
679  llvm::Constant *getObjCBeginCatchFn() {
680    std::vector<const llvm::Type*> Params;
681    Params.push_back(Int8PtrTy);
682    return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
683                                                             Params, false),
684                                     "objc_begin_catch");
685  }
686
687  const llvm::StructType *EHTypeTy;
688  const llvm::Type *EHTypePtrTy;
689
690  ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
691  ~ObjCNonFragileABITypesHelper(){}
692};
693
694class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
695public:
696  // FIXME - accessibility
697  class GC_IVAR {
698  public:
699    unsigned int ivar_bytepos;
700    unsigned int ivar_size;
701    GC_IVAR() : ivar_bytepos(0), ivar_size(0) {}
702
703    // Allow sorting based on byte pos.
704    bool operator<(const GC_IVAR &b) const {
705      return ivar_bytepos < b.ivar_bytepos;
706    }
707  };
708
709  class SKIP_SCAN {
710    public:
711    unsigned int skip;
712    unsigned int scan;
713    SKIP_SCAN() : skip(0), scan(0) {}
714  };
715
716protected:
717  CodeGen::CodeGenModule &CGM;
718  // FIXME! May not be needing this after all.
719  unsigned ObjCABI;
720
721  // gc ivar layout bitmap calculation helper caches.
722  llvm::SmallVector<GC_IVAR, 16> SkipIvars;
723  llvm::SmallVector<GC_IVAR, 16> IvarsInfo;
724
725  /// LazySymbols - Symbols to generate a lazy reference for. See
726  /// DefinedSymbols and FinishModule().
727  std::set<IdentifierInfo*> LazySymbols;
728
729  /// DefinedSymbols - External symbols which are defined by this
730  /// module. The symbols in this list and LazySymbols are used to add
731  /// special linker symbols which ensure that Objective-C modules are
732  /// linked properly.
733  std::set<IdentifierInfo*> DefinedSymbols;
734
735  /// ClassNames - uniqued class names.
736  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
737
738  /// MethodVarNames - uniqued method variable names.
739  llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
740
741  /// MethodVarTypes - uniqued method type signatures. We have to use
742  /// a StringMap here because have no other unique reference.
743  llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
744
745  /// MethodDefinitions - map of methods which have been defined in
746  /// this translation unit.
747  llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
748
749  /// PropertyNames - uniqued method variable names.
750  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
751
752  /// ClassReferences - uniqued class references.
753  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
754
755  /// SelectorReferences - uniqued selector references.
756  llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
757
758  /// Protocols - Protocols for which an objc_protocol structure has
759  /// been emitted. Forward declarations are handled by creating an
760  /// empty structure whose initializer is filled in when/if defined.
761  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
762
763  /// DefinedProtocols - Protocols which have actually been
764  /// defined. We should not need this, see FIXME in GenerateProtocol.
765  llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
766
767  /// DefinedClasses - List of defined classes.
768  std::vector<llvm::GlobalValue*> DefinedClasses;
769
770  /// DefinedCategories - List of defined categories.
771  std::vector<llvm::GlobalValue*> DefinedCategories;
772
773  /// UsedGlobals - List of globals to pack into the llvm.used metadata
774  /// to prevent them from being clobbered.
775  std::vector<llvm::GlobalVariable*> UsedGlobals;
776
777  /// GetNameForMethod - Return a name for the given method.
778  /// \param[out] NameOut - The return value.
779  void GetNameForMethod(const ObjCMethodDecl *OMD,
780                        const ObjCContainerDecl *CD,
781                        std::string &NameOut);
782
783  /// GetMethodVarName - Return a unique constant for the given
784  /// selector's name. The return value has type char *.
785  llvm::Constant *GetMethodVarName(Selector Sel);
786  llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
787  llvm::Constant *GetMethodVarName(const std::string &Name);
788
789  /// GetMethodVarType - Return a unique constant for the given
790  /// selector's name. The return value has type char *.
791
792  // FIXME: This is a horrible name.
793  llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
794  llvm::Constant *GetMethodVarType(const FieldDecl *D);
795
796  /// GetPropertyName - Return a unique constant for the given
797  /// name. The return value has type char *.
798  llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
799
800  // FIXME: This can be dropped once string functions are unified.
801  llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
802                                        const Decl *Container);
803
804  /// GetClassName - Return a unique constant for the given selector's
805  /// name. The return value has type char *.
806  llvm::Constant *GetClassName(IdentifierInfo *Ident);
807
808  /// BuildIvarLayout - Builds ivar layout bitmap for the class
809  /// implementation for the __strong or __weak case.
810  ///
811  llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
812                                  bool ForStrongLayout);
813
814  void BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
815                           const llvm::StructLayout *Layout,
816                           const RecordDecl *RD,
817                           const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
818                           unsigned int BytePos, bool ForStrongLayout,
819                           bool &HasUnion);
820
821  /// GetIvarLayoutName - Returns a unique constant for the given
822  /// ivar layout bitmap.
823  llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
824                                    const ObjCCommonTypesHelper &ObjCTypes);
825
826  /// EmitPropertyList - Emit the given property list. The return
827  /// value has type PropertyListPtrTy.
828  llvm::Constant *EmitPropertyList(const std::string &Name,
829                                   const Decl *Container,
830                                   const ObjCContainerDecl *OCD,
831                                   const ObjCCommonTypesHelper &ObjCTypes);
832
833  /// GetProtocolRef - Return a reference to the internal protocol
834  /// description, creating an empty one if it has not been
835  /// defined. The return value has type ProtocolPtrTy.
836  llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
837
838  /// GetFieldBaseOffset - return's field byte offset.
839  uint64_t GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
840                              const llvm::StructLayout *Layout,
841                              const FieldDecl *Field);
842
843  /// CreateMetadataVar - Create a global variable with internal
844  /// linkage for use by the Objective-C runtime.
845  ///
846  /// This is a convenience wrapper which not only creates the
847  /// variable, but also sets the section and alignment and adds the
848  /// global to the UsedGlobals list.
849  ///
850  /// \param Name - The variable name.
851  /// \param Init - The variable initializer; this is also used to
852  /// define the type of the variable.
853  /// \param Section - The section the variable should go into, or 0.
854  /// \param Align - The alignment for the variable, or 0.
855  /// \param AddToUsed - Whether the variable should be added to
856  /// "llvm.used".
857  llvm::GlobalVariable *CreateMetadataVar(const std::string &Name,
858                                          llvm::Constant *Init,
859                                          const char *Section,
860                                          unsigned Align,
861                                          bool AddToUsed);
862
863  /// GetNamedIvarList - Return the list of ivars in the interface
864  /// itself (not including super classes and not including unnamed
865  /// bitfields).
866  ///
867  /// For the non-fragile ABI, this also includes synthesized property
868  /// ivars.
869  void GetNamedIvarList(const ObjCInterfaceDecl *OID,
870                        llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const;
871
872public:
873  CGObjCCommonMac(CodeGen::CodeGenModule &cgm) : CGM(cgm)
874  { }
875
876  virtual llvm::Constant *GenerateConstantString(const ObjCStringLiteral *SL);
877
878  virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
879                                         const ObjCContainerDecl *CD=0);
880
881  virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
882
883  /// GetOrEmitProtocol - Get the protocol object for the given
884  /// declaration, emitting it if necessary. The return value has type
885  /// ProtocolPtrTy.
886  virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
887
888  /// GetOrEmitProtocolRef - Get a forward reference to the protocol
889  /// object for the given declaration, emitting it if needed. These
890  /// forward references will be filled in with empty bodies if no
891  /// definition is seen. The return value has type ProtocolPtrTy.
892  virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
893};
894
895class CGObjCMac : public CGObjCCommonMac {
896private:
897  ObjCTypesHelper ObjCTypes;
898  /// EmitImageInfo - Emit the image info marker used to encode some module
899  /// level information.
900  void EmitImageInfo();
901
902  /// EmitModuleInfo - Another marker encoding module level
903  /// information.
904  void EmitModuleInfo();
905
906  /// EmitModuleSymols - Emit module symbols, the list of defined
907  /// classes and categories. The result has type SymtabPtrTy.
908  llvm::Constant *EmitModuleSymbols();
909
910  /// FinishModule - Write out global data structures at the end of
911  /// processing a translation unit.
912  void FinishModule();
913
914  /// EmitClassExtension - Generate the class extension structure used
915  /// to store the weak ivar layout and properties. The return value
916  /// has type ClassExtensionPtrTy.
917  llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
918
919  /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
920  /// for the given class.
921  llvm::Value *EmitClassRef(CGBuilderTy &Builder,
922                            const ObjCInterfaceDecl *ID);
923
924  CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
925                                  QualType ResultType,
926                                  Selector Sel,
927                                  llvm::Value *Arg0,
928                                  QualType Arg0Ty,
929                                  bool IsSuper,
930                                  const CallArgList &CallArgs);
931
932  /// EmitIvarList - Emit the ivar list for the given
933  /// implementation. If ForClass is true the list of class ivars
934  /// (i.e. metaclass ivars) is emitted, otherwise the list of
935  /// interface ivars will be emitted. The return value has type
936  /// IvarListPtrTy.
937  llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
938                               bool ForClass);
939
940  /// EmitMetaClass - Emit a forward reference to the class structure
941  /// for the metaclass of the given interface. The return value has
942  /// type ClassPtrTy.
943  llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
944
945  /// EmitMetaClass - Emit a class structure for the metaclass of the
946  /// given implementation. The return value has type ClassPtrTy.
947  llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
948                                llvm::Constant *Protocols,
949                                const ConstantVector &Methods);
950
951  llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
952
953  llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
954
955  /// EmitMethodList - Emit the method list for the given
956  /// implementation. The return value has type MethodListPtrTy.
957  llvm::Constant *EmitMethodList(const std::string &Name,
958                                 const char *Section,
959                                 const ConstantVector &Methods);
960
961  /// EmitMethodDescList - Emit a method description list for a list of
962  /// method declarations.
963  ///  - TypeName: The name for the type containing the methods.
964  ///  - IsProtocol: True iff these methods are for a protocol.
965  ///  - ClassMethds: True iff these are class methods.
966  ///  - Required: When true, only "required" methods are
967  ///    listed. Similarly, when false only "optional" methods are
968  ///    listed. For classes this should always be true.
969  ///  - begin, end: The method list to output.
970  ///
971  /// The return value has type MethodDescriptionListPtrTy.
972  llvm::Constant *EmitMethodDescList(const std::string &Name,
973                                     const char *Section,
974                                     const ConstantVector &Methods);
975
976  /// GetOrEmitProtocol - Get the protocol object for the given
977  /// declaration, emitting it if necessary. The return value has type
978  /// ProtocolPtrTy.
979  virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
980
981  /// GetOrEmitProtocolRef - Get a forward reference to the protocol
982  /// object for the given declaration, emitting it if needed. These
983  /// forward references will be filled in with empty bodies if no
984  /// definition is seen. The return value has type ProtocolPtrTy.
985  virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
986
987  /// EmitProtocolExtension - Generate the protocol extension
988  /// structure used to store optional instance and class methods, and
989  /// protocol properties. The return value has type
990  /// ProtocolExtensionPtrTy.
991  llvm::Constant *
992  EmitProtocolExtension(const ObjCProtocolDecl *PD,
993                        const ConstantVector &OptInstanceMethods,
994                        const ConstantVector &OptClassMethods);
995
996  /// EmitProtocolList - Generate the list of referenced
997  /// protocols. The return value has type ProtocolListPtrTy.
998  llvm::Constant *EmitProtocolList(const std::string &Name,
999                                   ObjCProtocolDecl::protocol_iterator begin,
1000                                   ObjCProtocolDecl::protocol_iterator end);
1001
1002  /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1003  /// for the given selector.
1004  llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
1005
1006  public:
1007  CGObjCMac(CodeGen::CodeGenModule &cgm);
1008
1009  virtual llvm::Function *ModuleInitFunction();
1010
1011  virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1012                                              QualType ResultType,
1013                                              Selector Sel,
1014                                              llvm::Value *Receiver,
1015                                              bool IsClassMessage,
1016                                              const CallArgList &CallArgs);
1017
1018  virtual CodeGen::RValue
1019  GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1020                           QualType ResultType,
1021                           Selector Sel,
1022                           const ObjCInterfaceDecl *Class,
1023                           bool isCategoryImpl,
1024                           llvm::Value *Receiver,
1025                           bool IsClassMessage,
1026                           const CallArgList &CallArgs);
1027
1028  virtual llvm::Value *GetClass(CGBuilderTy &Builder,
1029                                const ObjCInterfaceDecl *ID);
1030
1031  virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
1032
1033  virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
1034
1035  virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
1036
1037  virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
1038                                           const ObjCProtocolDecl *PD);
1039
1040  virtual llvm::Constant *GetPropertyGetFunction();
1041  virtual llvm::Constant *GetPropertySetFunction();
1042  virtual llvm::Constant *EnumerationMutationFunction();
1043
1044  virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1045                                         const Stmt &S);
1046  virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1047                             const ObjCAtThrowStmt &S);
1048  virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
1049                                         llvm::Value *AddrWeakObj);
1050  virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1051                                  llvm::Value *src, llvm::Value *dst);
1052  virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1053                                    llvm::Value *src, llvm::Value *dest);
1054  virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1055                                  llvm::Value *src, llvm::Value *dest);
1056  virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1057                                        llvm::Value *src, llvm::Value *dest);
1058
1059  virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1060                                      QualType ObjectTy,
1061                                      llvm::Value *BaseValue,
1062                                      const ObjCIvarDecl *Ivar,
1063                                      unsigned CVRQualifiers);
1064  virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
1065                                      const ObjCInterfaceDecl *Interface,
1066                                      const ObjCIvarDecl *Ivar);
1067};
1068
1069class CGObjCNonFragileABIMac : public CGObjCCommonMac {
1070private:
1071  ObjCNonFragileABITypesHelper ObjCTypes;
1072  llvm::GlobalVariable* ObjCEmptyCacheVar;
1073  llvm::GlobalVariable* ObjCEmptyVtableVar;
1074
1075  /// SuperClassReferences - uniqued super class references.
1076  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
1077
1078  /// MetaClassReferences - uniqued meta class references.
1079  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
1080
1081  /// EHTypeReferences - uniqued class ehtype references.
1082  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
1083
1084  /// FinishNonFragileABIModule - Write out global data structures at the end of
1085  /// processing a translation unit.
1086  void FinishNonFragileABIModule();
1087
1088  llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
1089                                unsigned InstanceStart,
1090                                unsigned InstanceSize,
1091                                const ObjCImplementationDecl *ID);
1092  llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
1093                                            llvm::Constant *IsAGV,
1094                                            llvm::Constant *SuperClassGV,
1095                                            llvm::Constant *ClassRoGV,
1096                                            bool HiddenVisibility);
1097
1098  llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
1099
1100  llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
1101
1102  /// EmitMethodList - Emit the method list for the given
1103  /// implementation. The return value has type MethodListnfABITy.
1104  llvm::Constant *EmitMethodList(const std::string &Name,
1105                                 const char *Section,
1106                                 const ConstantVector &Methods);
1107  /// EmitIvarList - Emit the ivar list for the given
1108  /// implementation. If ForClass is true the list of class ivars
1109  /// (i.e. metaclass ivars) is emitted, otherwise the list of
1110  /// interface ivars will be emitted. The return value has type
1111  /// IvarListnfABIPtrTy.
1112  llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
1113
1114  llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
1115                                    const ObjCIvarDecl *Ivar,
1116                                    unsigned long int offset);
1117
1118  /// GetOrEmitProtocol - Get the protocol object for the given
1119  /// declaration, emitting it if necessary. The return value has type
1120  /// ProtocolPtrTy.
1121  virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
1122
1123  /// GetOrEmitProtocolRef - Get a forward reference to the protocol
1124  /// object for the given declaration, emitting it if needed. These
1125  /// forward references will be filled in with empty bodies if no
1126  /// definition is seen. The return value has type ProtocolPtrTy.
1127  virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
1128
1129  /// EmitProtocolList - Generate the list of referenced
1130  /// protocols. The return value has type ProtocolListPtrTy.
1131  llvm::Constant *EmitProtocolList(const std::string &Name,
1132                                   ObjCProtocolDecl::protocol_iterator begin,
1133                                   ObjCProtocolDecl::protocol_iterator end);
1134
1135  CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1136                                  QualType ResultType,
1137                                  Selector Sel,
1138                                  llvm::Value *Receiver,
1139                                  QualType Arg0Ty,
1140                                  bool IsSuper,
1141                                  const CallArgList &CallArgs);
1142
1143  /// GetClassGlobal - Return the global variable for the Objective-C
1144  /// class of the given name.
1145  llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
1146
1147  /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1148  /// for the given class reference.
1149  llvm::Value *EmitClassRef(CGBuilderTy &Builder,
1150                            const ObjCInterfaceDecl *ID);
1151
1152  /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
1153  /// for the given super class reference.
1154  llvm::Value *EmitSuperClassRef(CGBuilderTy &Builder,
1155                            const ObjCInterfaceDecl *ID);
1156
1157  /// EmitMetaClassRef - Return a Value * of the address of _class_t
1158  /// meta-data
1159  llvm::Value *EmitMetaClassRef(CGBuilderTy &Builder,
1160                                const ObjCInterfaceDecl *ID);
1161
1162  /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
1163  /// the given ivar.
1164  ///
1165  llvm::GlobalVariable * ObjCIvarOffsetVariable(
1166                              const ObjCInterfaceDecl *ID,
1167                              const ObjCIvarDecl *Ivar);
1168
1169  /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
1170  /// for the given selector.
1171  llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
1172
1173  /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
1174  /// interface. The return value has type EHTypePtrTy.
1175  llvm::Value *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
1176                                  bool ForDefinition);
1177
1178  const char *getMetaclassSymbolPrefix() const {
1179    return "OBJC_METACLASS_$_";
1180  }
1181
1182  const char *getClassSymbolPrefix() const {
1183    return "OBJC_CLASS_$_";
1184  }
1185
1186  void GetClassSizeInfo(const ObjCInterfaceDecl *OID,
1187                        uint32_t &InstanceStart,
1188                        uint32_t &InstanceSize);
1189
1190public:
1191  CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
1192  // FIXME. All stubs for now!
1193  virtual llvm::Function *ModuleInitFunction();
1194
1195  virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1196                                              QualType ResultType,
1197                                              Selector Sel,
1198                                              llvm::Value *Receiver,
1199                                              bool IsClassMessage,
1200                                              const CallArgList &CallArgs);
1201
1202  virtual CodeGen::RValue
1203  GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1204                           QualType ResultType,
1205                           Selector Sel,
1206                           const ObjCInterfaceDecl *Class,
1207                           bool isCategoryImpl,
1208                           llvm::Value *Receiver,
1209                           bool IsClassMessage,
1210                           const CallArgList &CallArgs);
1211
1212  virtual llvm::Value *GetClass(CGBuilderTy &Builder,
1213                                const ObjCInterfaceDecl *ID);
1214
1215  virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel)
1216    { return EmitSelector(Builder, Sel); }
1217
1218  virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
1219
1220  virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
1221  virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
1222                                           const ObjCProtocolDecl *PD);
1223
1224  virtual llvm::Constant *GetPropertyGetFunction() {
1225    return ObjCTypes.getGetPropertyFn();
1226  }
1227  virtual llvm::Constant *GetPropertySetFunction() {
1228    return ObjCTypes.getSetPropertyFn();
1229  }
1230  virtual llvm::Constant *EnumerationMutationFunction() {
1231    return ObjCTypes.getEnumerationMutationFn();
1232  }
1233
1234  virtual void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1235                                         const Stmt &S);
1236  virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1237                             const ObjCAtThrowStmt &S);
1238  virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
1239                                         llvm::Value *AddrWeakObj);
1240  virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
1241                                  llvm::Value *src, llvm::Value *dst);
1242  virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
1243                                    llvm::Value *src, llvm::Value *dest);
1244  virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
1245                                  llvm::Value *src, llvm::Value *dest);
1246  virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
1247                                        llvm::Value *src, llvm::Value *dest);
1248  virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
1249                                      QualType ObjectTy,
1250                                      llvm::Value *BaseValue,
1251                                      const ObjCIvarDecl *Ivar,
1252                                      unsigned CVRQualifiers);
1253  virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
1254                                      const ObjCInterfaceDecl *Interface,
1255                                      const ObjCIvarDecl *Ivar);
1256};
1257
1258} // end anonymous namespace
1259
1260/* *** Helper Functions *** */
1261
1262/// getConstantGEP() - Help routine to construct simple GEPs.
1263static llvm::Constant *getConstantGEP(llvm::Constant *C,
1264                                      unsigned idx0,
1265                                      unsigned idx1) {
1266  llvm::Value *Idxs[] = {
1267    llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
1268    llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
1269  };
1270  return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
1271}
1272
1273/// hasObjCExceptionAttribute - Return true if this class or any super
1274/// class has the __objc_exception__ attribute.
1275static bool hasObjCExceptionAttribute(const ObjCInterfaceDecl *OID) {
1276  if (OID->hasAttr<ObjCExceptionAttr>())
1277    return true;
1278  if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
1279    return hasObjCExceptionAttribute(Super);
1280  return false;
1281}
1282
1283/* *** CGObjCMac Public Interface *** */
1284
1285CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
1286                                                    ObjCTypes(cgm)
1287{
1288  ObjCABI = 1;
1289  EmitImageInfo();
1290}
1291
1292/// GetClass - Return a reference to the class for the given interface
1293/// decl.
1294llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
1295                                 const ObjCInterfaceDecl *ID) {
1296  return EmitClassRef(Builder, ID);
1297}
1298
1299/// GetSelector - Return the pointer to the unique'd string for this selector.
1300llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
1301  return EmitSelector(Builder, Sel);
1302}
1303
1304/// Generate a constant CFString object.
1305/*
1306   struct __builtin_CFString {
1307     const int *isa; // point to __CFConstantStringClassReference
1308     int flags;
1309     const char *str;
1310     long length;
1311   };
1312*/
1313
1314llvm::Constant *CGObjCCommonMac::GenerateConstantString(
1315  const ObjCStringLiteral *SL) {
1316  return CGM.GetAddrOfConstantCFString(SL->getString());
1317}
1318
1319/// Generates a message send where the super is the receiver.  This is
1320/// a message send to self with special delivery semantics indicating
1321/// which class's method should be called.
1322CodeGen::RValue
1323CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
1324                                    QualType ResultType,
1325                                    Selector Sel,
1326                                    const ObjCInterfaceDecl *Class,
1327                                    bool isCategoryImpl,
1328                                    llvm::Value *Receiver,
1329                                    bool IsClassMessage,
1330                                    const CodeGen::CallArgList &CallArgs) {
1331  // Create and init a super structure; this is a (receiver, class)
1332  // pair we will pass to objc_msgSendSuper.
1333  llvm::Value *ObjCSuper =
1334    CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
1335  llvm::Value *ReceiverAsObject =
1336    CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
1337  CGF.Builder.CreateStore(ReceiverAsObject,
1338                          CGF.Builder.CreateStructGEP(ObjCSuper, 0));
1339
1340  // If this is a class message the metaclass is passed as the target.
1341  llvm::Value *Target;
1342  if (IsClassMessage) {
1343    if (isCategoryImpl) {
1344      // Message sent to 'super' in a class method defined in a category
1345      // implementation requires an odd treatment.
1346      // If we are in a class method, we must retrieve the
1347      // _metaclass_ for the current class, pointed at by
1348      // the class's "isa" pointer.  The following assumes that
1349      // isa" is the first ivar in a class (which it must be).
1350      Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1351      Target = CGF.Builder.CreateStructGEP(Target, 0);
1352      Target = CGF.Builder.CreateLoad(Target);
1353    }
1354    else {
1355      llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
1356      llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
1357      llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
1358      Target = Super;
1359   }
1360  } else {
1361    Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
1362  }
1363  // FIXME: We shouldn't need to do this cast, rectify the ASTContext
1364  // and ObjCTypes types.
1365  const llvm::Type *ClassTy =
1366    CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
1367  Target = CGF.Builder.CreateBitCast(Target, ClassTy);
1368  CGF.Builder.CreateStore(Target,
1369                          CGF.Builder.CreateStructGEP(ObjCSuper, 1));
1370
1371  return EmitMessageSend(CGF, ResultType, Sel,
1372                         ObjCSuper, ObjCTypes.SuperPtrCTy,
1373                         true, CallArgs);
1374}
1375
1376/// Generate code for a message send expression.
1377CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
1378                                               QualType ResultType,
1379                                               Selector Sel,
1380                                               llvm::Value *Receiver,
1381                                               bool IsClassMessage,
1382                                               const CallArgList &CallArgs) {
1383  return EmitMessageSend(CGF, ResultType, Sel,
1384                         Receiver, CGF.getContext().getObjCIdType(),
1385                         false, CallArgs);
1386}
1387
1388CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
1389                                           QualType ResultType,
1390                                           Selector Sel,
1391                                           llvm::Value *Arg0,
1392                                           QualType Arg0Ty,
1393                                           bool IsSuper,
1394                                           const CallArgList &CallArgs) {
1395  CallArgList ActualArgs;
1396  if (!IsSuper)
1397    Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
1398  ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
1399  ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
1400                                                               Sel)),
1401                                      CGF.getContext().getObjCSelType()));
1402  ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
1403
1404  CodeGenTypes &Types = CGM.getTypes();
1405  const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, ActualArgs);
1406  // FIXME. vararg flag must be true when this API is used for 64bit code gen.
1407  const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo, false);
1408
1409  llvm::Constant *Fn;
1410  if (CGM.ReturnTypeUsesSret(FnInfo)) {
1411    Fn = ObjCTypes.getSendStretFn(IsSuper);
1412  } else if (ResultType->isFloatingType()) {
1413    // FIXME: Sadly, this is wrong. This actually depends on the
1414    // architecture. This happens to be right for x86-32 though.
1415    Fn = ObjCTypes.getSendFpretFn(IsSuper);
1416  } else {
1417    Fn = ObjCTypes.getSendFn(IsSuper);
1418  }
1419  Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
1420  return CGF.EmitCall(FnInfo, Fn, ActualArgs);
1421}
1422
1423llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
1424                                            const ObjCProtocolDecl *PD) {
1425  // FIXME: I don't understand why gcc generates this, or where it is
1426  // resolved. Investigate. Its also wasteful to look this up over and
1427  // over.
1428  LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1429
1430  return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
1431                                        ObjCTypes.ExternalProtocolPtrTy);
1432}
1433
1434void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
1435  // FIXME: We shouldn't need this, the protocol decl should contain
1436  // enough information to tell us whether this was a declaration or a
1437  // definition.
1438  DefinedProtocols.insert(PD->getIdentifier());
1439
1440  // If we have generated a forward reference to this protocol, emit
1441  // it now. Otherwise do nothing, the protocol objects are lazily
1442  // emitted.
1443  if (Protocols.count(PD->getIdentifier()))
1444    GetOrEmitProtocol(PD);
1445}
1446
1447llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
1448  if (DefinedProtocols.count(PD->getIdentifier()))
1449    return GetOrEmitProtocol(PD);
1450  return GetOrEmitProtocolRef(PD);
1451}
1452
1453/*
1454     // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
1455  struct _objc_protocol {
1456    struct _objc_protocol_extension *isa;
1457    char *protocol_name;
1458    struct _objc_protocol_list *protocol_list;
1459    struct _objc__method_prototype_list *instance_methods;
1460    struct _objc__method_prototype_list *class_methods
1461  };
1462
1463  See EmitProtocolExtension().
1464*/
1465llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
1466  llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1467
1468  // Early exit if a defining object has already been generated.
1469  if (Entry && Entry->hasInitializer())
1470    return Entry;
1471
1472  // FIXME: I don't understand why gcc generates this, or where it is
1473  // resolved. Investigate. Its also wasteful to look this up over and
1474  // over.
1475  LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
1476
1477  const char *ProtocolName = PD->getNameAsCString();
1478
1479  // Construct method lists.
1480  std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1481  std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
1482  for (ObjCProtocolDecl::instmeth_iterator
1483         i = PD->instmeth_begin(CGM.getContext()),
1484         e = PD->instmeth_end(CGM.getContext()); i != e; ++i) {
1485    ObjCMethodDecl *MD = *i;
1486    llvm::Constant *C = GetMethodDescriptionConstant(MD);
1487    if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1488      OptInstanceMethods.push_back(C);
1489    } else {
1490      InstanceMethods.push_back(C);
1491    }
1492  }
1493
1494  for (ObjCProtocolDecl::classmeth_iterator
1495         i = PD->classmeth_begin(CGM.getContext()),
1496         e = PD->classmeth_end(CGM.getContext()); i != e; ++i) {
1497    ObjCMethodDecl *MD = *i;
1498    llvm::Constant *C = GetMethodDescriptionConstant(MD);
1499    if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
1500      OptClassMethods.push_back(C);
1501    } else {
1502      ClassMethods.push_back(C);
1503    }
1504  }
1505
1506  std::vector<llvm::Constant*> Values(5);
1507  Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
1508  Values[1] = GetClassName(PD->getIdentifier());
1509  Values[2] =
1510    EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getNameAsString(),
1511                     PD->protocol_begin(),
1512                     PD->protocol_end());
1513  Values[3] =
1514    EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_"
1515                          + PD->getNameAsString(),
1516                       "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1517                       InstanceMethods);
1518  Values[4] =
1519    EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_"
1520                            + PD->getNameAsString(),
1521                       "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1522                       ClassMethods);
1523  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
1524                                                   Values);
1525
1526  if (Entry) {
1527    // Already created, fix the linkage and update the initializer.
1528    Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
1529    Entry->setInitializer(Init);
1530  } else {
1531    Entry =
1532      new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1533                               llvm::GlobalValue::InternalLinkage,
1534                               Init,
1535                               std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
1536                               &CGM.getModule());
1537    Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
1538    Entry->setAlignment(4);
1539    UsedGlobals.push_back(Entry);
1540    // FIXME: Is this necessary? Why only for protocol?
1541    Entry->setAlignment(4);
1542  }
1543
1544  return Entry;
1545}
1546
1547llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
1548  llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
1549
1550  if (!Entry) {
1551    // We use the initializer as a marker of whether this is a forward
1552    // reference or not. At module finalization we add the empty
1553    // contents for protocols which were referenced but never defined.
1554    Entry =
1555      new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
1556                               llvm::GlobalValue::ExternalLinkage,
1557                               0,
1558                               "\01L_OBJC_PROTOCOL_" + PD->getNameAsString(),
1559                               &CGM.getModule());
1560    Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
1561    Entry->setAlignment(4);
1562    UsedGlobals.push_back(Entry);
1563    // FIXME: Is this necessary? Why only for protocol?
1564    Entry->setAlignment(4);
1565  }
1566
1567  return Entry;
1568}
1569
1570/*
1571  struct _objc_protocol_extension {
1572    uint32_t size;
1573    struct objc_method_description_list *optional_instance_methods;
1574    struct objc_method_description_list *optional_class_methods;
1575    struct objc_property_list *instance_properties;
1576  };
1577*/
1578llvm::Constant *
1579CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
1580                                 const ConstantVector &OptInstanceMethods,
1581                                 const ConstantVector &OptClassMethods) {
1582  uint64_t Size =
1583    CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolExtensionTy);
1584  std::vector<llvm::Constant*> Values(4);
1585  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
1586  Values[1] =
1587    EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
1588                           + PD->getNameAsString(),
1589                       "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1590                       OptInstanceMethods);
1591  Values[2] =
1592    EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_"
1593                          + PD->getNameAsString(),
1594                       "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1595                       OptClassMethods);
1596  Values[3] = EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" +
1597                                   PD->getNameAsString(),
1598                               0, PD, ObjCTypes);
1599
1600  // Return null if no extension bits are used.
1601  if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
1602      Values[3]->isNullValue())
1603    return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
1604
1605  llvm::Constant *Init =
1606    llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
1607
1608  // No special section, but goes in llvm.used
1609  return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getNameAsString(),
1610                           Init,
1611                           0, 0, true);
1612}
1613
1614/*
1615  struct objc_protocol_list {
1616    struct objc_protocol_list *next;
1617    long count;
1618    Protocol *list[];
1619  };
1620*/
1621llvm::Constant *
1622CGObjCMac::EmitProtocolList(const std::string &Name,
1623                            ObjCProtocolDecl::protocol_iterator begin,
1624                            ObjCProtocolDecl::protocol_iterator end) {
1625  std::vector<llvm::Constant*> ProtocolRefs;
1626
1627  for (; begin != end; ++begin)
1628    ProtocolRefs.push_back(GetProtocolRef(*begin));
1629
1630  // Just return null for empty protocol lists
1631  if (ProtocolRefs.empty())
1632    return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1633
1634  // This list is null terminated.
1635  ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
1636
1637  std::vector<llvm::Constant*> Values(3);
1638  // This field is only used by the runtime.
1639  Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1640  Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
1641  Values[2] =
1642    llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
1643                                                  ProtocolRefs.size()),
1644                             ProtocolRefs);
1645
1646  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1647  llvm::GlobalVariable *GV =
1648    CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1649                      4, false);
1650  return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
1651}
1652
1653/*
1654  struct _objc_property {
1655    const char * const name;
1656    const char * const attributes;
1657  };
1658
1659  struct _objc_property_list {
1660    uint32_t entsize; // sizeof (struct _objc_property)
1661    uint32_t prop_count;
1662    struct _objc_property[prop_count];
1663  };
1664*/
1665llvm::Constant *CGObjCCommonMac::EmitPropertyList(const std::string &Name,
1666                                      const Decl *Container,
1667                                      const ObjCContainerDecl *OCD,
1668                                      const ObjCCommonTypesHelper &ObjCTypes) {
1669  std::vector<llvm::Constant*> Properties, Prop(2);
1670  for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(CGM.getContext()),
1671       E = OCD->prop_end(CGM.getContext()); I != E; ++I) {
1672    const ObjCPropertyDecl *PD = *I;
1673    Prop[0] = GetPropertyName(PD->getIdentifier());
1674    Prop[1] = GetPropertyTypeString(PD, Container);
1675    Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
1676                                                   Prop));
1677  }
1678
1679  // Return null for empty list.
1680  if (Properties.empty())
1681    return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1682
1683  unsigned PropertySize =
1684    CGM.getTargetData().getTypePaddedSize(ObjCTypes.PropertyTy);
1685  std::vector<llvm::Constant*> Values(3);
1686  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
1687  Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
1688  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
1689                                             Properties.size());
1690  Values[2] = llvm::ConstantArray::get(AT, Properties);
1691  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1692
1693  llvm::GlobalVariable *GV =
1694    CreateMetadataVar(Name, Init,
1695                      (ObjCABI == 2) ? "__DATA, __objc_const" :
1696                      "__OBJC,__property,regular,no_dead_strip",
1697                      (ObjCABI == 2) ? 8 : 4,
1698                      true);
1699  return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
1700}
1701
1702/*
1703  struct objc_method_description_list {
1704    int count;
1705    struct objc_method_description list[];
1706  };
1707*/
1708llvm::Constant *
1709CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
1710  std::vector<llvm::Constant*> Desc(2);
1711  Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1712                                           ObjCTypes.SelectorPtrTy);
1713  Desc[1] = GetMethodVarType(MD);
1714  return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
1715                                   Desc);
1716}
1717
1718llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
1719                                              const char *Section,
1720                                              const ConstantVector &Methods) {
1721  // Return null for empty list.
1722  if (Methods.empty())
1723    return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
1724
1725  std::vector<llvm::Constant*> Values(2);
1726  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1727  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
1728                                             Methods.size());
1729  Values[1] = llvm::ConstantArray::get(AT, Methods);
1730  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1731
1732  llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
1733  return llvm::ConstantExpr::getBitCast(GV,
1734                                        ObjCTypes.MethodDescriptionListPtrTy);
1735}
1736
1737/*
1738  struct _objc_category {
1739    char *category_name;
1740    char *class_name;
1741    struct _objc_method_list *instance_methods;
1742    struct _objc_method_list *class_methods;
1743    struct _objc_protocol_list *protocols;
1744    uint32_t size; // <rdar://4585769>
1745    struct _objc_property_list *instance_properties;
1746  };
1747 */
1748void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
1749  unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.CategoryTy);
1750
1751  // FIXME: This is poor design, the OCD should have a pointer to the
1752  // category decl. Additionally, note that Category can be null for
1753  // the @implementation w/o an @interface case. Sema should just
1754  // create one for us as it does for @implementation so everyone else
1755  // can live life under a clear blue sky.
1756  const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
1757  const ObjCCategoryDecl *Category =
1758    Interface->FindCategoryDeclaration(OCD->getIdentifier());
1759  std::string ExtName(Interface->getNameAsString() + "_" +
1760                      OCD->getNameAsString());
1761
1762  std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1763  for (ObjCCategoryImplDecl::instmeth_iterator
1764         i = OCD->instmeth_begin(CGM.getContext()),
1765         e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
1766    // Instance methods should always be defined.
1767    InstanceMethods.push_back(GetMethodConstant(*i));
1768  }
1769  for (ObjCCategoryImplDecl::classmeth_iterator
1770         i = OCD->classmeth_begin(CGM.getContext()),
1771         e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
1772    // Class methods should always be defined.
1773    ClassMethods.push_back(GetMethodConstant(*i));
1774  }
1775
1776  std::vector<llvm::Constant*> Values(7);
1777  Values[0] = GetClassName(OCD->getIdentifier());
1778  Values[1] = GetClassName(Interface->getIdentifier());
1779  LazySymbols.insert(Interface->getIdentifier());
1780  Values[2] =
1781    EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
1782                   ExtName,
1783                   "__OBJC,__cat_inst_meth,regular,no_dead_strip",
1784                   InstanceMethods);
1785  Values[3] =
1786    EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
1787                   "__OBJC,__cat_cls_meth,regular,no_dead_strip",
1788                   ClassMethods);
1789  if (Category) {
1790    Values[4] =
1791      EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
1792                       Category->protocol_begin(),
1793                       Category->protocol_end());
1794  } else {
1795    Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
1796  }
1797  Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
1798
1799  // If there is no category @interface then there can be no properties.
1800  if (Category) {
1801    Values[6] = EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
1802                                 OCD, Category, ObjCTypes);
1803  } else {
1804    Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1805  }
1806
1807  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1808                                                   Values);
1809
1810  llvm::GlobalVariable *GV =
1811    CreateMetadataVar(std::string("\01L_OBJC_CATEGORY_")+ExtName, Init,
1812                      "__OBJC,__category,regular,no_dead_strip",
1813                      4, true);
1814  DefinedCategories.push_back(GV);
1815}
1816
1817// FIXME: Get from somewhere?
1818enum ClassFlags {
1819  eClassFlags_Factory              = 0x00001,
1820  eClassFlags_Meta                 = 0x00002,
1821  // <rdr://5142207>
1822  eClassFlags_HasCXXStructors      = 0x02000,
1823  eClassFlags_Hidden               = 0x20000,
1824  eClassFlags_ABI2_Hidden          = 0x00010,
1825  eClassFlags_ABI2_HasCXXStructors = 0x00004   // <rdr://4923634>
1826};
1827
1828/*
1829  struct _objc_class {
1830    Class isa;
1831    Class super_class;
1832    const char *name;
1833    long version;
1834    long info;
1835    long instance_size;
1836    struct _objc_ivar_list *ivars;
1837    struct _objc_method_list *methods;
1838    struct _objc_cache *cache;
1839    struct _objc_protocol_list *protocols;
1840    // Objective-C 1.0 extensions (<rdr://4585769>)
1841    const char *ivar_layout;
1842    struct _objc_class_ext *ext;
1843  };
1844
1845  See EmitClassExtension();
1846 */
1847void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
1848  DefinedSymbols.insert(ID->getIdentifier());
1849
1850  std::string ClassName = ID->getNameAsString();
1851  // FIXME: Gross
1852  ObjCInterfaceDecl *Interface =
1853    const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
1854  llvm::Constant *Protocols =
1855    EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getNameAsString(),
1856                     Interface->protocol_begin(),
1857                     Interface->protocol_end());
1858  const llvm::Type *InterfaceTy =
1859    CGObjCRuntime::GetConcreteClassStruct(CGM, Interface);
1860  unsigned Flags = eClassFlags_Factory;
1861  unsigned Size = CGM.getTargetData().getTypePaddedSize(InterfaceTy);
1862
1863  // FIXME: Set CXX-structors flag.
1864  if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
1865    Flags |= eClassFlags_Hidden;
1866
1867  std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1868  for (ObjCImplementationDecl::instmeth_iterator
1869         i = ID->instmeth_begin(CGM.getContext()),
1870         e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
1871    // Instance methods should always be defined.
1872    InstanceMethods.push_back(GetMethodConstant(*i));
1873  }
1874  for (ObjCImplementationDecl::classmeth_iterator
1875         i = ID->classmeth_begin(CGM.getContext()),
1876         e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
1877    // Class methods should always be defined.
1878    ClassMethods.push_back(GetMethodConstant(*i));
1879  }
1880
1881  for (ObjCImplementationDecl::propimpl_iterator
1882         i = ID->propimpl_begin(CGM.getContext()),
1883         e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
1884    ObjCPropertyImplDecl *PID = *i;
1885
1886    if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1887      ObjCPropertyDecl *PD = PID->getPropertyDecl();
1888
1889      if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1890        if (llvm::Constant *C = GetMethodConstant(MD))
1891          InstanceMethods.push_back(C);
1892      if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1893        if (llvm::Constant *C = GetMethodConstant(MD))
1894          InstanceMethods.push_back(C);
1895    }
1896  }
1897
1898  std::vector<llvm::Constant*> Values(12);
1899  Values[ 0] = EmitMetaClass(ID, Protocols, ClassMethods);
1900  if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
1901    // Record a reference to the super class.
1902    LazySymbols.insert(Super->getIdentifier());
1903
1904    Values[ 1] =
1905      llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1906                                     ObjCTypes.ClassPtrTy);
1907  } else {
1908    Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1909  }
1910  Values[ 2] = GetClassName(ID->getIdentifier());
1911  // Version is always 0.
1912  Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1913  Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1914  Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1915  Values[ 6] = EmitIvarList(ID, false);
1916  Values[ 7] =
1917    EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getNameAsString(),
1918                   "__OBJC,__inst_meth,regular,no_dead_strip",
1919                   InstanceMethods);
1920  // cache is always NULL.
1921  Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1922  Values[ 9] = Protocols;
1923  Values[10] = BuildIvarLayout(ID, true);
1924  Values[11] = EmitClassExtension(ID);
1925  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1926                                                   Values);
1927
1928  llvm::GlobalVariable *GV =
1929    CreateMetadataVar(std::string("\01L_OBJC_CLASS_")+ClassName, Init,
1930                      "__OBJC,__class,regular,no_dead_strip",
1931                      4, true);
1932  DefinedClasses.push_back(GV);
1933}
1934
1935llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1936                                         llvm::Constant *Protocols,
1937                                         const ConstantVector &Methods) {
1938  unsigned Flags = eClassFlags_Meta;
1939  unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassTy);
1940
1941  if (CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden)
1942    Flags |= eClassFlags_Hidden;
1943
1944  std::vector<llvm::Constant*> Values(12);
1945  // The isa for the metaclass is the root of the hierarchy.
1946  const ObjCInterfaceDecl *Root = ID->getClassInterface();
1947  while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1948    Root = Super;
1949  Values[ 0] =
1950    llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1951                                   ObjCTypes.ClassPtrTy);
1952  // The super class for the metaclass is emitted as the name of the
1953  // super class. The runtime fixes this up to point to the
1954  // *metaclass* for the super class.
1955  if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1956    Values[ 1] =
1957      llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1958                                     ObjCTypes.ClassPtrTy);
1959  } else {
1960    Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1961  }
1962  Values[ 2] = GetClassName(ID->getIdentifier());
1963  // Version is always 0.
1964  Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1965  Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1966  Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1967  Values[ 6] = EmitIvarList(ID, true);
1968  Values[ 7] =
1969    EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
1970                   "__OBJC,__cls_meth,regular,no_dead_strip",
1971                   Methods);
1972  // cache is always NULL.
1973  Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1974  Values[ 9] = Protocols;
1975  // ivar_layout for metaclass is always NULL.
1976  Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1977  // The class extension is always unused for metaclasses.
1978  Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1979  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1980                                                   Values);
1981
1982  std::string Name("\01L_OBJC_METACLASS_");
1983  Name += ID->getNameAsCString();
1984
1985  // Check for a forward reference.
1986  llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1987  if (GV) {
1988    assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1989           "Forward metaclass reference has incorrect type.");
1990    GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1991    GV->setInitializer(Init);
1992  } else {
1993    GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1994                                  llvm::GlobalValue::InternalLinkage,
1995                                  Init, Name,
1996                                  &CGM.getModule());
1997  }
1998  GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
1999  GV->setAlignment(4);
2000  UsedGlobals.push_back(GV);
2001
2002  return GV;
2003}
2004
2005llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
2006  std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
2007
2008  // FIXME: Should we look these up somewhere other than the
2009  // module. Its a bit silly since we only generate these while
2010  // processing an implementation, so exactly one pointer would work
2011  // if know when we entered/exitted an implementation block.
2012
2013  // Check for an existing forward reference.
2014  // Previously, metaclass with internal linkage may have been defined.
2015  // pass 'true' as 2nd argument so it is returned.
2016  if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true)) {
2017    assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
2018           "Forward metaclass reference has incorrect type.");
2019    return GV;
2020  } else {
2021    // Generate as an external reference to keep a consistent
2022    // module. This will be patched up when we emit the metaclass.
2023    return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
2024                                    llvm::GlobalValue::ExternalLinkage,
2025                                    0,
2026                                    Name,
2027                                    &CGM.getModule());
2028  }
2029}
2030
2031/*
2032  struct objc_class_ext {
2033    uint32_t size;
2034    const char *weak_ivar_layout;
2035    struct _objc_property_list *properties;
2036  };
2037*/
2038llvm::Constant *
2039CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
2040  uint64_t Size =
2041    CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassExtensionTy);
2042
2043  std::vector<llvm::Constant*> Values(3);
2044  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
2045  Values[1] = BuildIvarLayout(ID, false);
2046  Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
2047                               ID, ID->getClassInterface(), ObjCTypes);
2048
2049  // Return null if no extension bits are used.
2050  if (Values[1]->isNullValue() && Values[2]->isNullValue())
2051    return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
2052
2053  llvm::Constant *Init =
2054    llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
2055  return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getNameAsString(),
2056                           Init, "__OBJC,__class_ext,regular,no_dead_strip",
2057                           4, true);
2058}
2059
2060/// getInterfaceDeclForIvar - Get the interface declaration node where
2061/// this ivar is declared in.
2062/// FIXME. Ideally, this info should be in the ivar node. But currently
2063/// it is not and prevailing wisdom is that ASTs should not have more
2064/// info than is absolutely needed, even though this info reflects the
2065/// source language.
2066///
2067static const ObjCInterfaceDecl *getInterfaceDeclForIvar(
2068                                  const ObjCInterfaceDecl *OI,
2069                                  const ObjCIvarDecl *IVD,
2070                                  ASTContext &Context) {
2071  if (!OI)
2072    return 0;
2073  assert(isa<ObjCInterfaceDecl>(OI) && "OI is not an interface");
2074  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
2075       E = OI->ivar_end(); I != E; ++I)
2076    if ((*I)->getIdentifier() == IVD->getIdentifier())
2077      return OI;
2078  // look into properties.
2079  for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(Context),
2080       E = OI->prop_end(Context); I != E; ++I) {
2081    ObjCPropertyDecl *PDecl = (*I);
2082    if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl())
2083      if (IV->getIdentifier() == IVD->getIdentifier())
2084        return OI;
2085  }
2086  return getInterfaceDeclForIvar(OI->getSuperClass(), IVD, Context);
2087}
2088
2089/*
2090  struct objc_ivar {
2091    char *ivar_name;
2092    char *ivar_type;
2093    int ivar_offset;
2094  };
2095
2096  struct objc_ivar_list {
2097    int ivar_count;
2098    struct objc_ivar list[count];
2099  };
2100 */
2101llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
2102                                        bool ForClass) {
2103  std::vector<llvm::Constant*> Ivars, Ivar(3);
2104
2105  // When emitting the root class GCC emits ivar entries for the
2106  // actual class structure. It is not clear if we need to follow this
2107  // behavior; for now lets try and get away with not doing it. If so,
2108  // the cleanest solution would be to make up an ObjCInterfaceDecl
2109  // for the class.
2110  if (ForClass)
2111    return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2112
2113  ObjCInterfaceDecl *OID =
2114    const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
2115
2116  llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
2117  GetNamedIvarList(OID, OIvars);
2118
2119  for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
2120    ObjCIvarDecl *IVD = OIvars[i];
2121    Ivar[0] = GetMethodVarName(IVD->getIdentifier());
2122    Ivar[1] = GetMethodVarType(IVD);
2123    Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy,
2124                                     ComputeIvarBaseOffset(CGM, OID, IVD));
2125    Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
2126  }
2127
2128  // Return null for empty list.
2129  if (Ivars.empty())
2130    return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
2131
2132  std::vector<llvm::Constant*> Values(2);
2133  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
2134  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
2135                                             Ivars.size());
2136  Values[1] = llvm::ConstantArray::get(AT, Ivars);
2137  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2138
2139  llvm::GlobalVariable *GV;
2140  if (ForClass)
2141    GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getNameAsString(),
2142                           Init, "__OBJC,__class_vars,regular,no_dead_strip",
2143                           4, true);
2144  else
2145    GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_"
2146                           + ID->getNameAsString(),
2147                           Init, "__OBJC,__instance_vars,regular,no_dead_strip",
2148                           4, true);
2149  return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
2150}
2151
2152/*
2153  struct objc_method {
2154    SEL method_name;
2155    char *method_types;
2156    void *method;
2157  };
2158
2159  struct objc_method_list {
2160    struct objc_method_list *obsolete;
2161    int count;
2162    struct objc_method methods_list[count];
2163  };
2164*/
2165
2166/// GetMethodConstant - Return a struct objc_method constant for the
2167/// given method if it has been defined. The result is null if the
2168/// method has not been defined. The return value has type MethodPtrTy.
2169llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
2170  // FIXME: Use DenseMap::lookup
2171  llvm::Function *Fn = MethodDefinitions[MD];
2172  if (!Fn)
2173    return 0;
2174
2175  std::vector<llvm::Constant*> Method(3);
2176  Method[0] =
2177    llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
2178                                   ObjCTypes.SelectorPtrTy);
2179  Method[1] = GetMethodVarType(MD);
2180  Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
2181  return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
2182}
2183
2184llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
2185                                          const char *Section,
2186                                          const ConstantVector &Methods) {
2187  // Return null for empty list.
2188  if (Methods.empty())
2189    return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
2190
2191  std::vector<llvm::Constant*> Values(3);
2192  Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2193  Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
2194  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
2195                                             Methods.size());
2196  Values[2] = llvm::ConstantArray::get(AT, Methods);
2197  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2198
2199  llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
2200  return llvm::ConstantExpr::getBitCast(GV,
2201                                        ObjCTypes.MethodListPtrTy);
2202}
2203
2204llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
2205                                                const ObjCContainerDecl *CD) {
2206  std::string Name;
2207  GetNameForMethod(OMD, CD, Name);
2208
2209  CodeGenTypes &Types = CGM.getTypes();
2210  const llvm::FunctionType *MethodTy =
2211    Types.GetFunctionType(Types.getFunctionInfo(OMD), OMD->isVariadic());
2212  llvm::Function *Method =
2213    llvm::Function::Create(MethodTy,
2214                           llvm::GlobalValue::InternalLinkage,
2215                           Name,
2216                           &CGM.getModule());
2217  MethodDefinitions.insert(std::make_pair(OMD, Method));
2218
2219  return Method;
2220}
2221
2222/// GetFieldBaseOffset - return the field's byte offset.
2223uint64_t CGObjCCommonMac::GetFieldBaseOffset(const ObjCInterfaceDecl *OI,
2224                                             const llvm::StructLayout *Layout,
2225                                             const FieldDecl *Field) {
2226  // Is this a C struct?
2227  if (!OI)
2228    return Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(Field));
2229  return ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field));
2230}
2231
2232llvm::GlobalVariable *
2233CGObjCCommonMac::CreateMetadataVar(const std::string &Name,
2234                                   llvm::Constant *Init,
2235                                   const char *Section,
2236                                   unsigned Align,
2237                                   bool AddToUsed) {
2238  const llvm::Type *Ty = Init->getType();
2239  llvm::GlobalVariable *GV =
2240    new llvm::GlobalVariable(Ty, false,
2241                             llvm::GlobalValue::InternalLinkage,
2242                             Init,
2243                             Name,
2244                             &CGM.getModule());
2245  if (Section)
2246    GV->setSection(Section);
2247  if (Align)
2248    GV->setAlignment(Align);
2249  if (AddToUsed)
2250    UsedGlobals.push_back(GV);
2251  return GV;
2252}
2253
2254llvm::Function *CGObjCMac::ModuleInitFunction() {
2255  // Abuse this interface function as a place to finalize.
2256  FinishModule();
2257
2258  return NULL;
2259}
2260
2261llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
2262  return ObjCTypes.getGetPropertyFn();
2263}
2264
2265llvm::Constant *CGObjCMac::GetPropertySetFunction() {
2266  return ObjCTypes.getSetPropertyFn();
2267}
2268
2269llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
2270  return ObjCTypes.getEnumerationMutationFn();
2271}
2272
2273/*
2274
2275Objective-C setjmp-longjmp (sjlj) Exception Handling
2276--
2277
2278The basic framework for a @try-catch-finally is as follows:
2279{
2280  objc_exception_data d;
2281  id _rethrow = null;
2282  bool _call_try_exit = true;
2283
2284  objc_exception_try_enter(&d);
2285  if (!setjmp(d.jmp_buf)) {
2286    ... try body ...
2287  } else {
2288    // exception path
2289    id _caught = objc_exception_extract(&d);
2290
2291    // enter new try scope for handlers
2292    if (!setjmp(d.jmp_buf)) {
2293      ... match exception and execute catch blocks ...
2294
2295      // fell off end, rethrow.
2296      _rethrow = _caught;
2297      ... jump-through-finally to finally_rethrow ...
2298    } else {
2299      // exception in catch block
2300      _rethrow = objc_exception_extract(&d);
2301      _call_try_exit = false;
2302      ... jump-through-finally to finally_rethrow ...
2303    }
2304  }
2305  ... jump-through-finally to finally_end ...
2306
2307finally:
2308  if (_call_try_exit)
2309    objc_exception_try_exit(&d);
2310
2311  ... finally block ....
2312  ... dispatch to finally destination ...
2313
2314finally_rethrow:
2315  objc_exception_throw(_rethrow);
2316
2317finally_end:
2318}
2319
2320This framework differs slightly from the one gcc uses, in that gcc
2321uses _rethrow to determine if objc_exception_try_exit should be called
2322and if the object should be rethrown. This breaks in the face of
2323throwing nil and introduces unnecessary branches.
2324
2325We specialize this framework for a few particular circumstances:
2326
2327 - If there are no catch blocks, then we avoid emitting the second
2328   exception handling context.
2329
2330 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
2331   e)) we avoid emitting the code to rethrow an uncaught exception.
2332
2333 - FIXME: If there is no @finally block we can do a few more
2334   simplifications.
2335
2336Rethrows and Jumps-Through-Finally
2337--
2338
2339Support for implicit rethrows and jumping through the finally block is
2340handled by storing the current exception-handling context in
2341ObjCEHStack.
2342
2343In order to implement proper @finally semantics, we support one basic
2344mechanism for jumping through the finally block to an arbitrary
2345destination. Constructs which generate exits from a @try or @catch
2346block use this mechanism to implement the proper semantics by chaining
2347jumps, as necessary.
2348
2349This mechanism works like the one used for indirect goto: we
2350arbitrarily assign an ID to each destination and store the ID for the
2351destination in a variable prior to entering the finally block. At the
2352end of the finally block we simply create a switch to the proper
2353destination.
2354
2355Code gen for @synchronized(expr) stmt;
2356Effectively generating code for:
2357objc_sync_enter(expr);
2358@try stmt @finally { objc_sync_exit(expr); }
2359*/
2360
2361void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
2362                                          const Stmt &S) {
2363  bool isTry = isa<ObjCAtTryStmt>(S);
2364  // Create various blocks we refer to for handling @finally.
2365  llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
2366  llvm::BasicBlock *FinallyExit = CGF.createBasicBlock("finally.exit");
2367  llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
2368  llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
2369  llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
2370
2371  // For @synchronized, call objc_sync_enter(sync.expr). The
2372  // evaluation of the expression must occur before we enter the
2373  // @synchronized. We can safely avoid a temp here because jumps into
2374  // @synchronized are illegal & this will dominate uses.
2375  llvm::Value *SyncArg = 0;
2376  if (!isTry) {
2377    SyncArg =
2378      CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
2379    SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
2380    CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
2381  }
2382
2383  // Push an EH context entry, used for handling rethrows and jumps
2384  // through finally.
2385  CGF.PushCleanupBlock(FinallyBlock);
2386
2387  CGF.ObjCEHValueStack.push_back(0);
2388
2389  // Allocate memory for the exception data and rethrow pointer.
2390  llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
2391                                                    "exceptiondata.ptr");
2392  llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
2393                                                 "_rethrow");
2394  llvm::Value *CallTryExitPtr = CGF.CreateTempAlloca(llvm::Type::Int1Ty,
2395                                                     "_call_try_exit");
2396  CGF.Builder.CreateStore(llvm::ConstantInt::getTrue(), CallTryExitPtr);
2397
2398  // Enter a new try block and call setjmp.
2399  CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
2400  llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
2401                                                       "jmpbufarray");
2402  JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
2403  llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
2404                                                     JmpBufPtr, "result");
2405
2406  llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
2407  llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
2408  CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
2409                           TryHandler, TryBlock);
2410
2411  // Emit the @try block.
2412  CGF.EmitBlock(TryBlock);
2413  CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
2414                     : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
2415  CGF.EmitBranchThroughCleanup(FinallyEnd);
2416
2417  // Emit the "exception in @try" block.
2418  CGF.EmitBlock(TryHandler);
2419
2420  // Retrieve the exception object.  We may emit multiple blocks but
2421  // nothing can cross this so the value is already in SSA form.
2422  llvm::Value *Caught =
2423    CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2424                           ExceptionData, "caught");
2425  CGF.ObjCEHValueStack.back() = Caught;
2426  if (!isTry)
2427  {
2428    CGF.Builder.CreateStore(Caught, RethrowPtr);
2429    CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
2430    CGF.EmitBranchThroughCleanup(FinallyRethrow);
2431  }
2432  else if (const ObjCAtCatchStmt* CatchStmt =
2433           cast<ObjCAtTryStmt>(S).getCatchStmts())
2434  {
2435    // Enter a new exception try block (in case a @catch block throws
2436    // an exception).
2437    CGF.Builder.CreateCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
2438
2439    llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.getSetJmpFn(),
2440                                                       JmpBufPtr, "result");
2441    llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
2442
2443    llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
2444    llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
2445    CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
2446
2447    CGF.EmitBlock(CatchBlock);
2448
2449    // Handle catch list. As a special case we check if everything is
2450    // matched and avoid generating code for falling off the end if
2451    // so.
2452    bool AllMatched = false;
2453    for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
2454      llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
2455
2456      const ParmVarDecl *CatchParam = CatchStmt->getCatchParamDecl();
2457      const PointerType *PT = 0;
2458
2459      // catch(...) always matches.
2460      if (!CatchParam) {
2461        AllMatched = true;
2462      } else {
2463        PT = CatchParam->getType()->getAsPointerType();
2464
2465        // catch(id e) always matches.
2466        // FIXME: For the time being we also match id<X>; this should
2467        // be rejected by Sema instead.
2468        if ((PT && CGF.getContext().isObjCIdStructType(PT->getPointeeType())) ||
2469            CatchParam->getType()->isObjCQualifiedIdType())
2470          AllMatched = true;
2471      }
2472
2473      if (AllMatched) {
2474        if (CatchParam) {
2475          CGF.EmitLocalBlockVarDecl(*CatchParam);
2476          assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
2477          CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
2478        }
2479
2480        CGF.EmitStmt(CatchStmt->getCatchBody());
2481        CGF.EmitBranchThroughCleanup(FinallyEnd);
2482        break;
2483      }
2484
2485      assert(PT && "Unexpected non-pointer type in @catch");
2486      QualType T = PT->getPointeeType();
2487      const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
2488      assert(ObjCType && "Catch parameter must have Objective-C type!");
2489
2490      // Check if the @catch block matches the exception object.
2491      llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
2492
2493      llvm::Value *Match =
2494        CGF.Builder.CreateCall2(ObjCTypes.getExceptionMatchFn(),
2495                                Class, Caught, "match");
2496
2497      llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
2498
2499      CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
2500                               MatchedBlock, NextCatchBlock);
2501
2502      // Emit the @catch block.
2503      CGF.EmitBlock(MatchedBlock);
2504      CGF.EmitLocalBlockVarDecl(*CatchParam);
2505      assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
2506
2507      llvm::Value *Tmp =
2508        CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(CatchParam->getType()),
2509                                  "tmp");
2510      CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
2511
2512      CGF.EmitStmt(CatchStmt->getCatchBody());
2513      CGF.EmitBranchThroughCleanup(FinallyEnd);
2514
2515      CGF.EmitBlock(NextCatchBlock);
2516    }
2517
2518    if (!AllMatched) {
2519      // None of the handlers caught the exception, so store it to be
2520      // rethrown at the end of the @finally block.
2521      CGF.Builder.CreateStore(Caught, RethrowPtr);
2522      CGF.EmitBranchThroughCleanup(FinallyRethrow);
2523    }
2524
2525    // Emit the exception handler for the @catch blocks.
2526    CGF.EmitBlock(CatchHandler);
2527    CGF.Builder.CreateStore(
2528                    CGF.Builder.CreateCall(ObjCTypes.getExceptionExtractFn(),
2529                                           ExceptionData),
2530                            RethrowPtr);
2531    CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
2532    CGF.EmitBranchThroughCleanup(FinallyRethrow);
2533  } else {
2534    CGF.Builder.CreateStore(Caught, RethrowPtr);
2535    CGF.Builder.CreateStore(llvm::ConstantInt::getFalse(), CallTryExitPtr);
2536    CGF.EmitBranchThroughCleanup(FinallyRethrow);
2537  }
2538
2539  // Pop the exception-handling stack entry. It is important to do
2540  // this now, because the code in the @finally block is not in this
2541  // context.
2542  CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
2543
2544  CGF.ObjCEHValueStack.pop_back();
2545
2546  // Emit the @finally block.
2547  CGF.EmitBlock(FinallyBlock);
2548  llvm::Value* CallTryExit = CGF.Builder.CreateLoad(CallTryExitPtr, "tmp");
2549
2550  CGF.Builder.CreateCondBr(CallTryExit, FinallyExit, FinallyNoExit);
2551
2552  CGF.EmitBlock(FinallyExit);
2553  CGF.Builder.CreateCall(ObjCTypes.getExceptionTryExitFn(), ExceptionData);
2554
2555  CGF.EmitBlock(FinallyNoExit);
2556  if (isTry) {
2557    if (const ObjCAtFinallyStmt* FinallyStmt =
2558          cast<ObjCAtTryStmt>(S).getFinallyStmt())
2559      CGF.EmitStmt(FinallyStmt->getFinallyBody());
2560  } else {
2561    // Emit objc_sync_exit(expr); as finally's sole statement for
2562    // @synchronized.
2563    CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
2564  }
2565
2566  // Emit the switch block
2567  if (Info.SwitchBlock)
2568    CGF.EmitBlock(Info.SwitchBlock);
2569  if (Info.EndBlock)
2570    CGF.EmitBlock(Info.EndBlock);
2571
2572  CGF.EmitBlock(FinallyRethrow);
2573  CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(),
2574                         CGF.Builder.CreateLoad(RethrowPtr));
2575  CGF.Builder.CreateUnreachable();
2576
2577  CGF.EmitBlock(FinallyEnd);
2578}
2579
2580void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
2581                              const ObjCAtThrowStmt &S) {
2582  llvm::Value *ExceptionAsObject;
2583
2584  if (const Expr *ThrowExpr = S.getThrowExpr()) {
2585    llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
2586    ExceptionAsObject =
2587      CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
2588  } else {
2589    assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
2590           "Unexpected rethrow outside @catch block.");
2591    ExceptionAsObject = CGF.ObjCEHValueStack.back();
2592  }
2593
2594  CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
2595  CGF.Builder.CreateUnreachable();
2596
2597  // Clear the insertion point to indicate we are in unreachable code.
2598  CGF.Builder.ClearInsertionPoint();
2599}
2600
2601/// EmitObjCWeakRead - Code gen for loading value of a __weak
2602/// object: objc_read_weak (id *src)
2603///
2604llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
2605                                          llvm::Value *AddrWeakObj)
2606{
2607  const llvm::Type* DestTy =
2608      cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
2609  AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
2610  llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
2611                                                  AddrWeakObj, "weakread");
2612  read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
2613  return read_weak;
2614}
2615
2616/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
2617/// objc_assign_weak (id src, id *dst)
2618///
2619void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
2620                                   llvm::Value *src, llvm::Value *dst)
2621{
2622  const llvm::Type * SrcTy = src->getType();
2623  if (!isa<llvm::PointerType>(SrcTy)) {
2624    unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2625    assert(Size <= 8 && "does not support size > 8");
2626    src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2627    : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
2628    src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2629  }
2630  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2631  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2632  CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
2633                          src, dst, "weakassign");
2634  return;
2635}
2636
2637/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
2638/// objc_assign_global (id src, id *dst)
2639///
2640void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
2641                                     llvm::Value *src, llvm::Value *dst)
2642{
2643  const llvm::Type * SrcTy = src->getType();
2644  if (!isa<llvm::PointerType>(SrcTy)) {
2645    unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2646    assert(Size <= 8 && "does not support size > 8");
2647    src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2648    : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
2649    src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2650  }
2651  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2652  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2653  CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
2654                          src, dst, "globalassign");
2655  return;
2656}
2657
2658/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
2659/// objc_assign_ivar (id src, id *dst)
2660///
2661void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
2662                                   llvm::Value *src, llvm::Value *dst)
2663{
2664  const llvm::Type * SrcTy = src->getType();
2665  if (!isa<llvm::PointerType>(SrcTy)) {
2666    unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2667    assert(Size <= 8 && "does not support size > 8");
2668    src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2669    : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
2670    src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2671  }
2672  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2673  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2674  CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
2675                          src, dst, "assignivar");
2676  return;
2677}
2678
2679/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
2680/// objc_assign_strongCast (id src, id *dst)
2681///
2682void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
2683                                         llvm::Value *src, llvm::Value *dst)
2684{
2685  const llvm::Type * SrcTy = src->getType();
2686  if (!isa<llvm::PointerType>(SrcTy)) {
2687    unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
2688    assert(Size <= 8 && "does not support size > 8");
2689    src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
2690                      : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
2691    src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
2692  }
2693  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
2694  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
2695  CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
2696                          src, dst, "weakassign");
2697  return;
2698}
2699
2700/// EmitObjCValueForIvar - Code Gen for ivar reference.
2701///
2702LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
2703                                       QualType ObjectTy,
2704                                       llvm::Value *BaseValue,
2705                                       const ObjCIvarDecl *Ivar,
2706                                       unsigned CVRQualifiers) {
2707  const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
2708  return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2709                                  EmitIvarOffset(CGF, ID, Ivar));
2710}
2711
2712llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
2713                                       const ObjCInterfaceDecl *Interface,
2714                                       const ObjCIvarDecl *Ivar) {
2715  uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
2716  return llvm::ConstantInt::get(
2717                            CGM.getTypes().ConvertType(CGM.getContext().LongTy),
2718                            Offset);
2719}
2720
2721/* *** Private Interface *** */
2722
2723/// EmitImageInfo - Emit the image info marker used to encode some module
2724/// level information.
2725///
2726/// See: <rdr://4810609&4810587&4810587>
2727/// struct IMAGE_INFO {
2728///   unsigned version;
2729///   unsigned flags;
2730/// };
2731enum ImageInfoFlags {
2732  eImageInfo_FixAndContinue      = (1 << 0), // FIXME: Not sure what
2733                                             // this implies.
2734  eImageInfo_GarbageCollected    = (1 << 1),
2735  eImageInfo_GCOnly              = (1 << 2),
2736  eImageInfo_OptimizedByDyld     = (1 << 3), // FIXME: When is this set.
2737
2738  // A flag indicating that the module has no instances of an
2739  // @synthesize of a superclass variable. <rdar://problem/6803242>
2740  eImageInfo_CorrectedSynthesize = (1 << 4)
2741};
2742
2743void CGObjCMac::EmitImageInfo() {
2744  unsigned version = 0; // Version is unused?
2745  unsigned flags = 0;
2746
2747  // FIXME: Fix and continue?
2748  if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
2749    flags |= eImageInfo_GarbageCollected;
2750  if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
2751    flags |= eImageInfo_GCOnly;
2752
2753  // We never allow @synthesize of a superclass property.
2754  flags |= eImageInfo_CorrectedSynthesize;
2755
2756  // Emitted as int[2];
2757  llvm::Constant *values[2] = {
2758    llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
2759    llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
2760  };
2761  llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
2762
2763  const char *Section;
2764  if (ObjCABI == 1)
2765    Section = "__OBJC, __image_info,regular";
2766  else
2767    Section = "__DATA, __objc_imageinfo, regular, no_dead_strip";
2768  llvm::GlobalVariable *GV =
2769    CreateMetadataVar("\01L_OBJC_IMAGE_INFO",
2770                      llvm::ConstantArray::get(AT, values, 2),
2771                      Section,
2772                      0,
2773                      true);
2774  GV->setConstant(true);
2775}
2776
2777
2778// struct objc_module {
2779//   unsigned long version;
2780//   unsigned long size;
2781//   const char *name;
2782//   Symtab symtab;
2783// };
2784
2785// FIXME: Get from somewhere
2786static const int ModuleVersion = 7;
2787
2788void CGObjCMac::EmitModuleInfo() {
2789  uint64_t Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.ModuleTy);
2790
2791  std::vector<llvm::Constant*> Values(4);
2792  Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
2793  Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
2794  // This used to be the filename, now it is unused. <rdr://4327263>
2795  Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
2796  Values[3] = EmitModuleSymbols();
2797  CreateMetadataVar("\01L_OBJC_MODULES",
2798                    llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
2799                    "__OBJC,__module_info,regular,no_dead_strip",
2800                    4, true);
2801}
2802
2803llvm::Constant *CGObjCMac::EmitModuleSymbols() {
2804  unsigned NumClasses = DefinedClasses.size();
2805  unsigned NumCategories = DefinedCategories.size();
2806
2807  // Return null if no symbols were defined.
2808  if (!NumClasses && !NumCategories)
2809    return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
2810
2811  std::vector<llvm::Constant*> Values(5);
2812  Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
2813  Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
2814  Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
2815  Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
2816
2817  // The runtime expects exactly the list of defined classes followed
2818  // by the list of defined categories, in a single array.
2819  std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
2820  for (unsigned i=0; i<NumClasses; i++)
2821    Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
2822                                                ObjCTypes.Int8PtrTy);
2823  for (unsigned i=0; i<NumCategories; i++)
2824    Symbols[NumClasses + i] =
2825      llvm::ConstantExpr::getBitCast(DefinedCategories[i],
2826                                     ObjCTypes.Int8PtrTy);
2827
2828  Values[4] =
2829    llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
2830                                                  NumClasses + NumCategories),
2831                             Symbols);
2832
2833  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
2834
2835  llvm::GlobalVariable *GV =
2836    CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
2837                      "__OBJC,__symbols,regular,no_dead_strip",
2838                      4, true);
2839  return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
2840}
2841
2842llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
2843                                     const ObjCInterfaceDecl *ID) {
2844  LazySymbols.insert(ID->getIdentifier());
2845
2846  llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
2847
2848  if (!Entry) {
2849    llvm::Constant *Casted =
2850      llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2851                                     ObjCTypes.ClassPtrTy);
2852    Entry =
2853      CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
2854                        "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
2855                        4, true);
2856  }
2857
2858  return Builder.CreateLoad(Entry, false, "tmp");
2859}
2860
2861llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
2862  llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2863
2864  if (!Entry) {
2865    llvm::Constant *Casted =
2866      llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2867                                     ObjCTypes.SelectorPtrTy);
2868    Entry =
2869      CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
2870                        "__OBJC,__message_refs,literal_pointers,no_dead_strip",
2871                        4, true);
2872  }
2873
2874  return Builder.CreateLoad(Entry, false, "tmp");
2875}
2876
2877llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
2878  llvm::GlobalVariable *&Entry = ClassNames[Ident];
2879
2880  if (!Entry)
2881    Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
2882                              llvm::ConstantArray::get(Ident->getName()),
2883                              "__TEXT,__cstring,cstring_literals",
2884                              1, true);
2885
2886  return getConstantGEP(Entry, 0, 0);
2887}
2888
2889/// GetIvarLayoutName - Returns a unique constant for the given
2890/// ivar layout bitmap.
2891llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
2892                                      const ObjCCommonTypesHelper &ObjCTypes) {
2893  return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
2894}
2895
2896void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCInterfaceDecl *OI,
2897                              const llvm::StructLayout *Layout,
2898                              const RecordDecl *RD,
2899                             const llvm::SmallVectorImpl<FieldDecl*> &RecFields,
2900                              unsigned int BytePos, bool ForStrongLayout,
2901                              bool &HasUnion) {
2902  bool IsUnion = (RD && RD->isUnion());
2903  uint64_t MaxUnionIvarSize = 0;
2904  uint64_t MaxSkippedUnionIvarSize = 0;
2905  FieldDecl *MaxField = 0;
2906  FieldDecl *MaxSkippedField = 0;
2907  FieldDecl *LastFieldBitfield = 0;
2908
2909  unsigned base = 0;
2910  if (RecFields.empty())
2911    return;
2912  if (IsUnion)
2913    base = BytePos + GetFieldBaseOffset(OI, Layout, RecFields[0]);
2914  unsigned WordSizeInBits = CGM.getContext().Target.getPointerWidth(0);
2915  unsigned ByteSizeInBits = CGM.getContext().Target.getCharWidth();
2916
2917  llvm::SmallVector<FieldDecl*, 16> TmpRecFields;
2918
2919  for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
2920    FieldDecl *Field = RecFields[i];
2921    // Skip over unnamed or bitfields
2922    if (!Field->getIdentifier() || Field->isBitField()) {
2923      LastFieldBitfield = Field;
2924      continue;
2925    }
2926    LastFieldBitfield = 0;
2927    QualType FQT = Field->getType();
2928    if (FQT->isRecordType() || FQT->isUnionType()) {
2929      if (FQT->isUnionType())
2930        HasUnion = true;
2931      else
2932        assert(FQT->isRecordType() &&
2933               "only union/record is supported for ivar layout bitmap");
2934
2935      const RecordType *RT = FQT->getAsRecordType();
2936      const RecordDecl *RD = RT->getDecl();
2937      // FIXME - Find a more efficient way of passing records down.
2938      TmpRecFields.append(RD->field_begin(CGM.getContext()),
2939                          RD->field_end(CGM.getContext()));
2940      const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2941      const llvm::StructLayout *RecLayout =
2942        CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2943
2944      BuildAggrIvarLayout(0, RecLayout, RD, TmpRecFields,
2945                          BytePos + GetFieldBaseOffset(OI, Layout, Field),
2946                          ForStrongLayout, HasUnion);
2947      TmpRecFields.clear();
2948      continue;
2949    }
2950
2951    if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2952      const ConstantArrayType *CArray =
2953                                 dyn_cast_or_null<ConstantArrayType>(Array);
2954      uint64_t ElCount = CArray->getSize().getZExtValue();
2955      assert(CArray && "only array with know element size is supported");
2956      FQT = CArray->getElementType();
2957      while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
2958        const ConstantArrayType *CArray =
2959                                 dyn_cast_or_null<ConstantArrayType>(Array);
2960        ElCount *= CArray->getSize().getZExtValue();
2961        FQT = CArray->getElementType();
2962      }
2963
2964      assert(!FQT->isUnionType() &&
2965             "layout for array of unions not supported");
2966      if (FQT->isRecordType()) {
2967        int OldIndex = IvarsInfo.size() - 1;
2968        int OldSkIndex = SkipIvars.size() -1;
2969
2970        // FIXME - Use a common routine with the above!
2971        const RecordType *RT = FQT->getAsRecordType();
2972        const RecordDecl *RD = RT->getDecl();
2973        // FIXME - Find a more efficiant way of passing records down.
2974        TmpRecFields.append(RD->field_begin(CGM.getContext()),
2975                            RD->field_end(CGM.getContext()));
2976        const llvm::Type *Ty = CGM.getTypes().ConvertType(FQT);
2977        const llvm::StructLayout *RecLayout =
2978        CGM.getTargetData().getStructLayout(cast<llvm::StructType>(Ty));
2979
2980        BuildAggrIvarLayout(0, RecLayout, RD,
2981                            TmpRecFields,
2982                            BytePos + GetFieldBaseOffset(OI, Layout, Field),
2983                            ForStrongLayout, HasUnion);
2984        TmpRecFields.clear();
2985
2986        // Replicate layout information for each array element. Note that
2987        // one element is already done.
2988        uint64_t ElIx = 1;
2989        for (int FirstIndex = IvarsInfo.size() - 1,
2990                 FirstSkIndex = SkipIvars.size() - 1 ;ElIx < ElCount; ElIx++) {
2991          uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
2992          for (int i = OldIndex+1; i <= FirstIndex; ++i)
2993          {
2994            GC_IVAR gcivar;
2995            gcivar.ivar_bytepos = IvarsInfo[i].ivar_bytepos + Size*ElIx;
2996            gcivar.ivar_size = IvarsInfo[i].ivar_size;
2997            IvarsInfo.push_back(gcivar);
2998          }
2999
3000          for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i) {
3001            GC_IVAR skivar;
3002            skivar.ivar_bytepos = SkipIvars[i].ivar_bytepos + Size*ElIx;
3003            skivar.ivar_size = SkipIvars[i].ivar_size;
3004            SkipIvars.push_back(skivar);
3005          }
3006        }
3007        continue;
3008      }
3009    }
3010    // At this point, we are done with Record/Union and array there of.
3011    // For other arrays we are down to its element type.
3012    QualType::GCAttrTypes GCAttr = QualType::GCNone;
3013    do {
3014      if (FQT.isObjCGCStrong() || FQT.isObjCGCWeak()) {
3015        GCAttr = FQT.isObjCGCStrong() ? QualType::Strong : QualType::Weak;
3016        break;
3017      }
3018      else if (CGM.getContext().isObjCObjectPointerType(FQT)) {
3019        GCAttr = QualType::Strong;
3020        break;
3021      }
3022      else if (const PointerType *PT = FQT->getAsPointerType()) {
3023        FQT = PT->getPointeeType();
3024      }
3025      else {
3026        break;
3027      }
3028    } while (true);
3029
3030    if ((ForStrongLayout && GCAttr == QualType::Strong)
3031        || (!ForStrongLayout && GCAttr == QualType::Weak)) {
3032      if (IsUnion)
3033      {
3034        uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType())
3035                                 / WordSizeInBits;
3036        if (UnionIvarSize > MaxUnionIvarSize)
3037        {
3038          MaxUnionIvarSize = UnionIvarSize;
3039          MaxField = Field;
3040        }
3041      }
3042      else
3043      {
3044        GC_IVAR gcivar;
3045        gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
3046        gcivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
3047                           WordSizeInBits;
3048        IvarsInfo.push_back(gcivar);
3049      }
3050    }
3051    else if ((ForStrongLayout &&
3052              (GCAttr == QualType::GCNone || GCAttr == QualType::Weak))
3053             || (!ForStrongLayout && GCAttr != QualType::Weak)) {
3054      if (IsUnion)
3055      {
3056        uint64_t UnionIvarSize = CGM.getContext().getTypeSize(Field->getType());
3057        if (UnionIvarSize > MaxSkippedUnionIvarSize)
3058        {
3059          MaxSkippedUnionIvarSize = UnionIvarSize;
3060          MaxSkippedField = Field;
3061        }
3062      }
3063      else
3064      {
3065        GC_IVAR skivar;
3066        skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, Field);
3067        skivar.ivar_size = CGM.getContext().getTypeSize(Field->getType()) /
3068                           ByteSizeInBits;
3069        SkipIvars.push_back(skivar);
3070      }
3071    }
3072  }
3073  if (LastFieldBitfield) {
3074    // Last field was a bitfield. Must update skip info.
3075    GC_IVAR skivar;
3076    skivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout,
3077                                                       LastFieldBitfield);
3078    Expr *BitWidth = LastFieldBitfield->getBitWidth();
3079    uint64_t BitFieldSize =
3080      BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
3081    skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
3082                         + ((BitFieldSize % ByteSizeInBits) != 0);
3083    SkipIvars.push_back(skivar);
3084  }
3085
3086  if (MaxField) {
3087    GC_IVAR gcivar;
3088    gcivar.ivar_bytepos = BytePos + GetFieldBaseOffset(OI, Layout, MaxField);
3089    gcivar.ivar_size = MaxUnionIvarSize;
3090    IvarsInfo.push_back(gcivar);
3091  }
3092
3093  if (MaxSkippedField) {
3094    GC_IVAR skivar;
3095    skivar.ivar_bytepos = BytePos +
3096                          GetFieldBaseOffset(OI, Layout, MaxSkippedField);
3097    skivar.ivar_size = MaxSkippedUnionIvarSize;
3098    SkipIvars.push_back(skivar);
3099  }
3100}
3101
3102/// BuildIvarLayout - Builds ivar layout bitmap for the class
3103/// implementation for the __strong or __weak case.
3104/// The layout map displays which words in ivar list must be skipped
3105/// and which must be scanned by GC (see below). String is built of bytes.
3106/// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
3107/// of words to skip and right nibble is count of words to scan. So, each
3108/// nibble represents up to 15 workds to skip or scan. Skipping the rest is
3109/// represented by a 0x00 byte which also ends the string.
3110/// 1. when ForStrongLayout is true, following ivars are scanned:
3111/// - id, Class
3112/// - object *
3113/// - __strong anything
3114///
3115/// 2. When ForStrongLayout is false, following ivars are scanned:
3116/// - __weak anything
3117///
3118llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
3119                                      const ObjCImplementationDecl *OMD,
3120                                      bool ForStrongLayout) {
3121  bool hasUnion = false;
3122
3123  unsigned int WordsToScan, WordsToSkip;
3124  const llvm::Type *PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3125  if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
3126    return llvm::Constant::getNullValue(PtrTy);
3127
3128  llvm::SmallVector<FieldDecl*, 32> RecFields;
3129  const ObjCInterfaceDecl *OI = OMD->getClassInterface();
3130  CGM.getContext().CollectObjCIvars(OI, RecFields);
3131  if (RecFields.empty())
3132    return llvm::Constant::getNullValue(PtrTy);
3133
3134  SkipIvars.clear();
3135  IvarsInfo.clear();
3136
3137  const llvm::StructLayout *Layout =
3138    CGM.getTargetData().getStructLayout(GetConcreteClassStruct(CGM, OI));
3139  BuildAggrIvarLayout(OI, Layout, 0, RecFields, 0, ForStrongLayout, hasUnion);
3140  if (IvarsInfo.empty())
3141    return llvm::Constant::getNullValue(PtrTy);
3142
3143  // Sort on byte position in case we encounterred a union nested in
3144  // the ivar list.
3145  if (hasUnion && !IvarsInfo.empty())
3146    std::sort(IvarsInfo.begin(), IvarsInfo.end());
3147  if (hasUnion && !SkipIvars.empty())
3148    std::sort(SkipIvars.begin(), SkipIvars.end());
3149
3150  // Build the string of skip/scan nibbles
3151  llvm::SmallVector<SKIP_SCAN, 32> SkipScanIvars;
3152  unsigned int WordSize =
3153    CGM.getTypes().getTargetData().getTypePaddedSize(PtrTy);
3154  if (IvarsInfo[0].ivar_bytepos == 0) {
3155    WordsToSkip = 0;
3156    WordsToScan = IvarsInfo[0].ivar_size;
3157  }
3158  else {
3159    WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
3160    WordsToScan = IvarsInfo[0].ivar_size;
3161  }
3162  for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++)
3163  {
3164    unsigned int TailPrevGCObjC =
3165      IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
3166    if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC)
3167    {
3168      // consecutive 'scanned' object pointers.
3169      WordsToScan += IvarsInfo[i].ivar_size;
3170    }
3171    else
3172    {
3173      // Skip over 'gc'able object pointer which lay over each other.
3174      if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
3175        continue;
3176      // Must skip over 1 or more words. We save current skip/scan values
3177      //  and start a new pair.
3178      SKIP_SCAN SkScan;
3179      SkScan.skip = WordsToSkip;
3180      SkScan.scan = WordsToScan;
3181      SkipScanIvars.push_back(SkScan);
3182
3183      // Skip the hole.
3184      SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
3185      SkScan.scan = 0;
3186      SkipScanIvars.push_back(SkScan);
3187      WordsToSkip = 0;
3188      WordsToScan = IvarsInfo[i].ivar_size;
3189    }
3190  }
3191  if (WordsToScan > 0)
3192  {
3193    SKIP_SCAN SkScan;
3194    SkScan.skip = WordsToSkip;
3195    SkScan.scan = WordsToScan;
3196    SkipScanIvars.push_back(SkScan);
3197  }
3198
3199  bool BytesSkipped = false;
3200  if (!SkipIvars.empty())
3201  {
3202    unsigned int LastIndex = SkipIvars.size()-1;
3203    int LastByteSkipped =
3204          SkipIvars[LastIndex].ivar_bytepos + SkipIvars[LastIndex].ivar_size;
3205    LastIndex = IvarsInfo.size()-1;
3206    int LastByteScanned =
3207          IvarsInfo[LastIndex].ivar_bytepos +
3208          IvarsInfo[LastIndex].ivar_size * WordSize;
3209    BytesSkipped = (LastByteSkipped > LastByteScanned);
3210    // Compute number of bytes to skip at the tail end of the last ivar scanned.
3211    if (BytesSkipped)
3212    {
3213      unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
3214      SKIP_SCAN SkScan;
3215      SkScan.skip = TotalWords - (LastByteScanned/WordSize);
3216      SkScan.scan = 0;
3217      SkipScanIvars.push_back(SkScan);
3218    }
3219  }
3220  // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
3221  // as 0xMN.
3222  int SkipScan = SkipScanIvars.size()-1;
3223  for (int i = 0; i <= SkipScan; i++)
3224  {
3225    if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
3226        && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
3227      // 0xM0 followed by 0x0N detected.
3228      SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
3229      for (int j = i+1; j < SkipScan; j++)
3230        SkipScanIvars[j] = SkipScanIvars[j+1];
3231      --SkipScan;
3232    }
3233  }
3234
3235  // Generate the string.
3236  std::string BitMap;
3237  for (int i = 0; i <= SkipScan; i++)
3238  {
3239    unsigned char byte;
3240    unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
3241    unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
3242    unsigned int skip_big  = SkipScanIvars[i].skip / 0xf;
3243    unsigned int scan_big  = SkipScanIvars[i].scan / 0xf;
3244
3245    if (skip_small > 0 || skip_big > 0)
3246      BytesSkipped = true;
3247    // first skip big.
3248    for (unsigned int ix = 0; ix < skip_big; ix++)
3249      BitMap += (unsigned char)(0xf0);
3250
3251    // next (skip small, scan)
3252    if (skip_small)
3253    {
3254      byte = skip_small << 4;
3255      if (scan_big > 0)
3256      {
3257        byte |= 0xf;
3258        --scan_big;
3259      }
3260      else if (scan_small)
3261      {
3262        byte |= scan_small;
3263        scan_small = 0;
3264      }
3265      BitMap += byte;
3266    }
3267    // next scan big
3268    for (unsigned int ix = 0; ix < scan_big; ix++)
3269      BitMap += (unsigned char)(0x0f);
3270    // last scan small
3271    if (scan_small)
3272    {
3273      byte = scan_small;
3274      BitMap += byte;
3275    }
3276  }
3277  // null terminate string.
3278  unsigned char zero = 0;
3279  BitMap += zero;
3280
3281  if (CGM.getLangOptions().ObjCGCBitmapPrint) {
3282    printf("\n%s ivar layout for class '%s': ",
3283           ForStrongLayout ? "strong" : "weak",
3284           OMD->getClassInterface()->getNameAsCString());
3285    const unsigned char *s = (unsigned char*)BitMap.c_str();
3286    for (unsigned i = 0; i < BitMap.size(); i++)
3287      if (!(s[i] & 0xf0))
3288        printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
3289      else
3290        printf("0x%x%s",  s[i], s[i] != 0 ? ", " : "");
3291    printf("\n");
3292  }
3293
3294  // if ivar_layout bitmap is all 1 bits (nothing skipped) then use NULL as
3295  // final layout.
3296  if (ForStrongLayout && !BytesSkipped)
3297    return llvm::Constant::getNullValue(PtrTy);
3298  llvm::GlobalVariable * Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
3299                                      llvm::ConstantArray::get(BitMap.c_str()),
3300                                      "__TEXT,__cstring,cstring_literals",
3301                                      1, true);
3302    return getConstantGEP(Entry, 0, 0);
3303}
3304
3305llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
3306  llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
3307
3308  // FIXME: Avoid std::string copying.
3309  if (!Entry)
3310    Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
3311                              llvm::ConstantArray::get(Sel.getAsString()),
3312                              "__TEXT,__cstring,cstring_literals",
3313                              1, true);
3314
3315  return getConstantGEP(Entry, 0, 0);
3316}
3317
3318// FIXME: Merge into a single cstring creation function.
3319llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
3320  return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
3321}
3322
3323// FIXME: Merge into a single cstring creation function.
3324llvm::Constant *CGObjCCommonMac::GetMethodVarName(const std::string &Name) {
3325  return GetMethodVarName(&CGM.getContext().Idents.get(Name));
3326}
3327
3328llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
3329  std::string TypeStr;
3330  CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
3331
3332  llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3333
3334  if (!Entry)
3335    Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3336                              llvm::ConstantArray::get(TypeStr),
3337                              "__TEXT,__cstring,cstring_literals",
3338                              1, true);
3339
3340  return getConstantGEP(Entry, 0, 0);
3341}
3342
3343llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D) {
3344  std::string TypeStr;
3345  CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
3346                                                TypeStr);
3347
3348  llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
3349
3350  if (!Entry)
3351    Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
3352                              llvm::ConstantArray::get(TypeStr),
3353                              "__TEXT,__cstring,cstring_literals",
3354                              1, true);
3355
3356  return getConstantGEP(Entry, 0, 0);
3357}
3358
3359// FIXME: Merge into a single cstring creation function.
3360llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
3361  llvm::GlobalVariable *&Entry = PropertyNames[Ident];
3362
3363  if (!Entry)
3364    Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
3365                              llvm::ConstantArray::get(Ident->getName()),
3366                              "__TEXT,__cstring,cstring_literals",
3367                              1, true);
3368
3369  return getConstantGEP(Entry, 0, 0);
3370}
3371
3372// FIXME: Merge into a single cstring creation function.
3373// FIXME: This Decl should be more precise.
3374llvm::Constant *
3375  CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
3376                                         const Decl *Container) {
3377  std::string TypeStr;
3378  CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
3379  return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
3380}
3381
3382void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
3383                                       const ObjCContainerDecl *CD,
3384                                       std::string &NameOut) {
3385  NameOut = '\01';
3386  NameOut += (D->isInstanceMethod() ? '-' : '+');
3387  NameOut += '[';
3388  assert (CD && "Missing container decl in GetNameForMethod");
3389  NameOut += CD->getNameAsString();
3390  if (const ObjCCategoryImplDecl *CID =
3391      dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext())) {
3392    NameOut += '(';
3393    NameOut += CID->getNameAsString();
3394    NameOut+= ')';
3395  }
3396  NameOut += ' ';
3397  NameOut += D->getSelector().getAsString();
3398  NameOut += ']';
3399}
3400
3401void CGObjCMac::FinishModule() {
3402  EmitModuleInfo();
3403
3404  // Emit the dummy bodies for any protocols which were referenced but
3405  // never defined.
3406  for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
3407         i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
3408    if (i->second->hasInitializer())
3409      continue;
3410
3411    std::vector<llvm::Constant*> Values(5);
3412    Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
3413    Values[1] = GetClassName(i->first);
3414    Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
3415    Values[3] = Values[4] =
3416      llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
3417    i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
3418    i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
3419                                                        Values));
3420  }
3421
3422  std::vector<llvm::Constant*> Used;
3423  for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
3424         e = UsedGlobals.end(); i != e; ++i) {
3425    Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
3426  }
3427
3428  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
3429  llvm::GlobalValue *GV =
3430    new llvm::GlobalVariable(AT, false,
3431                             llvm::GlobalValue::AppendingLinkage,
3432                             llvm::ConstantArray::get(AT, Used),
3433                             "llvm.used",
3434                             &CGM.getModule());
3435
3436  GV->setSection("llvm.metadata");
3437
3438  // Add assembler directives to add lazy undefined symbol references
3439  // for classes which are referenced but not defined. This is
3440  // important for correct linker interaction.
3441
3442  // FIXME: Uh, this isn't particularly portable.
3443  std::stringstream s;
3444
3445  if (!CGM.getModule().getModuleInlineAsm().empty())
3446    s << "\n";
3447
3448  for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
3449         e = LazySymbols.end(); i != e; ++i) {
3450    s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
3451  }
3452  for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
3453         e = DefinedSymbols.end(); i != e; ++i) {
3454    s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
3455      << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
3456  }
3457
3458  CGM.getModule().appendModuleInlineAsm(s.str());
3459}
3460
3461CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
3462  : CGObjCCommonMac(cgm),
3463  ObjCTypes(cgm)
3464{
3465  ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
3466  ObjCABI = 2;
3467}
3468
3469/* *** */
3470
3471ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
3472: CGM(cgm)
3473{
3474  CodeGen::CodeGenTypes &Types = CGM.getTypes();
3475  ASTContext &Ctx = CGM.getContext();
3476
3477  ShortTy = Types.ConvertType(Ctx.ShortTy);
3478  IntTy = Types.ConvertType(Ctx.IntTy);
3479  LongTy = Types.ConvertType(Ctx.LongTy);
3480  LongLongTy = Types.ConvertType(Ctx.LongLongTy);
3481  Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
3482
3483  ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
3484  PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
3485  SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
3486
3487  // FIXME: It would be nice to unify this with the opaque type, so
3488  // that the IR comes out a bit cleaner.
3489  const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
3490  ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
3491
3492  // I'm not sure I like this. The implicit coordination is a bit
3493  // gross. We should solve this in a reasonable fashion because this
3494  // is a pretty common task (match some runtime data structure with
3495  // an LLVM data structure).
3496
3497  // FIXME: This is leaked.
3498  // FIXME: Merge with rewriter code?
3499
3500  // struct _objc_super {
3501  //   id self;
3502  //   Class cls;
3503  // }
3504  RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3505                                      SourceLocation(),
3506                                      &Ctx.Idents.get("_objc_super"));
3507  RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3508                                     Ctx.getObjCIdType(), 0, false));
3509  RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3510                                     Ctx.getObjCClassType(), 0, false));
3511  RD->completeDefinition(Ctx);
3512
3513  SuperCTy = Ctx.getTagDeclType(RD);
3514  SuperPtrCTy = Ctx.getPointerType(SuperCTy);
3515
3516  SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
3517  SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
3518
3519  // struct _prop_t {
3520  //   char *name;
3521  //   char *attributes;
3522  // }
3523  PropertyTy = llvm::StructType::get(Int8PtrTy, Int8PtrTy, NULL);
3524  CGM.getModule().addTypeName("struct._prop_t",
3525                              PropertyTy);
3526
3527  // struct _prop_list_t {
3528  //   uint32_t entsize;      // sizeof(struct _prop_t)
3529  //   uint32_t count_of_properties;
3530  //   struct _prop_t prop_list[count_of_properties];
3531  // }
3532  PropertyListTy = llvm::StructType::get(IntTy,
3533                                         IntTy,
3534                                         llvm::ArrayType::get(PropertyTy, 0),
3535                                         NULL);
3536  CGM.getModule().addTypeName("struct._prop_list_t",
3537                              PropertyListTy);
3538  // struct _prop_list_t *
3539  PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
3540
3541  // struct _objc_method {
3542  //   SEL _cmd;
3543  //   char *method_type;
3544  //   char *_imp;
3545  // }
3546  MethodTy = llvm::StructType::get(SelectorPtrTy,
3547                                   Int8PtrTy,
3548                                   Int8PtrTy,
3549                                   NULL);
3550  CGM.getModule().addTypeName("struct._objc_method", MethodTy);
3551
3552  // struct _objc_cache *
3553  CacheTy = llvm::OpaqueType::get();
3554  CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
3555  CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
3556}
3557
3558ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
3559  : ObjCCommonTypesHelper(cgm)
3560{
3561  // struct _objc_method_description {
3562  //   SEL name;
3563  //   char *types;
3564  // }
3565  MethodDescriptionTy =
3566    llvm::StructType::get(SelectorPtrTy,
3567                          Int8PtrTy,
3568                          NULL);
3569  CGM.getModule().addTypeName("struct._objc_method_description",
3570                              MethodDescriptionTy);
3571
3572  // struct _objc_method_description_list {
3573  //   int count;
3574  //   struct _objc_method_description[1];
3575  // }
3576  MethodDescriptionListTy =
3577    llvm::StructType::get(IntTy,
3578                          llvm::ArrayType::get(MethodDescriptionTy, 0),
3579                          NULL);
3580  CGM.getModule().addTypeName("struct._objc_method_description_list",
3581                              MethodDescriptionListTy);
3582
3583  // struct _objc_method_description_list *
3584  MethodDescriptionListPtrTy =
3585    llvm::PointerType::getUnqual(MethodDescriptionListTy);
3586
3587  // Protocol description structures
3588
3589  // struct _objc_protocol_extension {
3590  //   uint32_t size;  // sizeof(struct _objc_protocol_extension)
3591  //   struct _objc_method_description_list *optional_instance_methods;
3592  //   struct _objc_method_description_list *optional_class_methods;
3593  //   struct _objc_property_list *instance_properties;
3594  // }
3595  ProtocolExtensionTy =
3596    llvm::StructType::get(IntTy,
3597                          MethodDescriptionListPtrTy,
3598                          MethodDescriptionListPtrTy,
3599                          PropertyListPtrTy,
3600                          NULL);
3601  CGM.getModule().addTypeName("struct._objc_protocol_extension",
3602                              ProtocolExtensionTy);
3603
3604  // struct _objc_protocol_extension *
3605  ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
3606
3607  // Handle recursive construction of Protocol and ProtocolList types
3608
3609  llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
3610  llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3611
3612  const llvm::Type *T =
3613    llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
3614                          LongTy,
3615                          llvm::ArrayType::get(ProtocolTyHolder, 0),
3616                          NULL);
3617  cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
3618
3619  // struct _objc_protocol {
3620  //   struct _objc_protocol_extension *isa;
3621  //   char *protocol_name;
3622  //   struct _objc_protocol **_objc_protocol_list;
3623  //   struct _objc_method_description_list *instance_methods;
3624  //   struct _objc_method_description_list *class_methods;
3625  // }
3626  T = llvm::StructType::get(ProtocolExtensionPtrTy,
3627                            Int8PtrTy,
3628                            llvm::PointerType::getUnqual(ProtocolListTyHolder),
3629                            MethodDescriptionListPtrTy,
3630                            MethodDescriptionListPtrTy,
3631                            NULL);
3632  cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
3633
3634  ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
3635  CGM.getModule().addTypeName("struct._objc_protocol_list",
3636                              ProtocolListTy);
3637  // struct _objc_protocol_list *
3638  ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
3639
3640  ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
3641  CGM.getModule().addTypeName("struct._objc_protocol", ProtocolTy);
3642  ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
3643
3644  // Class description structures
3645
3646  // struct _objc_ivar {
3647  //   char *ivar_name;
3648  //   char *ivar_type;
3649  //   int  ivar_offset;
3650  // }
3651  IvarTy = llvm::StructType::get(Int8PtrTy,
3652                                 Int8PtrTy,
3653                                 IntTy,
3654                                 NULL);
3655  CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
3656
3657  // struct _objc_ivar_list *
3658  IvarListTy = llvm::OpaqueType::get();
3659  CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
3660  IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
3661
3662  // struct _objc_method_list *
3663  MethodListTy = llvm::OpaqueType::get();
3664  CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
3665  MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
3666
3667  // struct _objc_class_extension *
3668  ClassExtensionTy =
3669    llvm::StructType::get(IntTy,
3670                          Int8PtrTy,
3671                          PropertyListPtrTy,
3672                          NULL);
3673  CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
3674  ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
3675
3676  llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3677
3678  // struct _objc_class {
3679  //   Class isa;
3680  //   Class super_class;
3681  //   char *name;
3682  //   long version;
3683  //   long info;
3684  //   long instance_size;
3685  //   struct _objc_ivar_list *ivars;
3686  //   struct _objc_method_list *methods;
3687  //   struct _objc_cache *cache;
3688  //   struct _objc_protocol_list *protocols;
3689  //   char *ivar_layout;
3690  //   struct _objc_class_ext *ext;
3691  // };
3692  T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3693                            llvm::PointerType::getUnqual(ClassTyHolder),
3694                            Int8PtrTy,
3695                            LongTy,
3696                            LongTy,
3697                            LongTy,
3698                            IvarListPtrTy,
3699                            MethodListPtrTy,
3700                            CachePtrTy,
3701                            ProtocolListPtrTy,
3702                            Int8PtrTy,
3703                            ClassExtensionPtrTy,
3704                            NULL);
3705  cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
3706
3707  ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
3708  CGM.getModule().addTypeName("struct._objc_class", ClassTy);
3709  ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
3710
3711  // struct _objc_category {
3712  //   char *category_name;
3713  //   char *class_name;
3714  //   struct _objc_method_list *instance_method;
3715  //   struct _objc_method_list *class_method;
3716  //   uint32_t size;  // sizeof(struct _objc_category)
3717  //   struct _objc_property_list *instance_properties;// category's @property
3718  // }
3719  CategoryTy = llvm::StructType::get(Int8PtrTy,
3720                                     Int8PtrTy,
3721                                     MethodListPtrTy,
3722                                     MethodListPtrTy,
3723                                     ProtocolListPtrTy,
3724                                     IntTy,
3725                                     PropertyListPtrTy,
3726                                     NULL);
3727  CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
3728
3729  // Global metadata structures
3730
3731  // struct _objc_symtab {
3732  //   long sel_ref_cnt;
3733  //   SEL *refs;
3734  //   short cls_def_cnt;
3735  //   short cat_def_cnt;
3736  //   char *defs[cls_def_cnt + cat_def_cnt];
3737  // }
3738  SymtabTy = llvm::StructType::get(LongTy,
3739                                   SelectorPtrTy,
3740                                   ShortTy,
3741                                   ShortTy,
3742                                   llvm::ArrayType::get(Int8PtrTy, 0),
3743                                   NULL);
3744  CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
3745  SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
3746
3747  // struct _objc_module {
3748  //   long version;
3749  //   long size;   // sizeof(struct _objc_module)
3750  //   char *name;
3751  //   struct _objc_symtab* symtab;
3752  //  }
3753  ModuleTy =
3754    llvm::StructType::get(LongTy,
3755                          LongTy,
3756                          Int8PtrTy,
3757                          SymtabPtrTy,
3758                          NULL);
3759  CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
3760
3761
3762  // FIXME: This is the size of the setjmp buffer and should be
3763  // target specific. 18 is what's used on 32-bit X86.
3764  uint64_t SetJmpBufferSize = 18;
3765
3766  // Exceptions
3767  const llvm::Type *StackPtrTy =
3768    llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
3769
3770  ExceptionDataTy =
3771    llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
3772                                               SetJmpBufferSize),
3773                          StackPtrTy, NULL);
3774  CGM.getModule().addTypeName("struct._objc_exception_data",
3775                              ExceptionDataTy);
3776
3777}
3778
3779ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
3780: ObjCCommonTypesHelper(cgm)
3781{
3782  // struct _method_list_t {
3783  //   uint32_t entsize;  // sizeof(struct _objc_method)
3784  //   uint32_t method_count;
3785  //   struct _objc_method method_list[method_count];
3786  // }
3787  MethodListnfABITy = llvm::StructType::get(IntTy,
3788                                            IntTy,
3789                                            llvm::ArrayType::get(MethodTy, 0),
3790                                            NULL);
3791  CGM.getModule().addTypeName("struct.__method_list_t",
3792                              MethodListnfABITy);
3793  // struct method_list_t *
3794  MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
3795
3796  // struct _protocol_t {
3797  //   id isa;  // NULL
3798  //   const char * const protocol_name;
3799  //   const struct _protocol_list_t * protocol_list; // super protocols
3800  //   const struct method_list_t * const instance_methods;
3801  //   const struct method_list_t * const class_methods;
3802  //   const struct method_list_t *optionalInstanceMethods;
3803  //   const struct method_list_t *optionalClassMethods;
3804  //   const struct _prop_list_t * properties;
3805  //   const uint32_t size;  // sizeof(struct _protocol_t)
3806  //   const uint32_t flags;  // = 0
3807  // }
3808
3809  // Holder for struct _protocol_list_t *
3810  llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
3811
3812  ProtocolnfABITy = llvm::StructType::get(ObjectPtrTy,
3813                                          Int8PtrTy,
3814                                          llvm::PointerType::getUnqual(
3815                                            ProtocolListTyHolder),
3816                                          MethodListnfABIPtrTy,
3817                                          MethodListnfABIPtrTy,
3818                                          MethodListnfABIPtrTy,
3819                                          MethodListnfABIPtrTy,
3820                                          PropertyListPtrTy,
3821                                          IntTy,
3822                                          IntTy,
3823                                          NULL);
3824  CGM.getModule().addTypeName("struct._protocol_t",
3825                              ProtocolnfABITy);
3826
3827  // struct _protocol_t*
3828  ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
3829
3830  // struct _protocol_list_t {
3831  //   long protocol_count;   // Note, this is 32/64 bit
3832  //   struct _protocol_t *[protocol_count];
3833  // }
3834  ProtocolListnfABITy = llvm::StructType::get(LongTy,
3835                                              llvm::ArrayType::get(
3836                                                ProtocolnfABIPtrTy, 0),
3837                                              NULL);
3838  CGM.getModule().addTypeName("struct._objc_protocol_list",
3839                              ProtocolListnfABITy);
3840  cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(
3841                                                      ProtocolListnfABITy);
3842
3843  // struct _objc_protocol_list*
3844  ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
3845
3846  // struct _ivar_t {
3847  //   unsigned long int *offset;  // pointer to ivar offset location
3848  //   char *name;
3849  //   char *type;
3850  //   uint32_t alignment;
3851  //   uint32_t size;
3852  // }
3853  IvarnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(LongTy),
3854                                      Int8PtrTy,
3855                                      Int8PtrTy,
3856                                      IntTy,
3857                                      IntTy,
3858                                      NULL);
3859  CGM.getModule().addTypeName("struct._ivar_t", IvarnfABITy);
3860
3861  // struct _ivar_list_t {
3862  //   uint32 entsize;  // sizeof(struct _ivar_t)
3863  //   uint32 count;
3864  //   struct _iver_t list[count];
3865  // }
3866  IvarListnfABITy = llvm::StructType::get(IntTy,
3867                                          IntTy,
3868                                          llvm::ArrayType::get(
3869                                                               IvarnfABITy, 0),
3870                                          NULL);
3871  CGM.getModule().addTypeName("struct._ivar_list_t", IvarListnfABITy);
3872
3873  IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
3874
3875  // struct _class_ro_t {
3876  //   uint32_t const flags;
3877  //   uint32_t const instanceStart;
3878  //   uint32_t const instanceSize;
3879  //   uint32_t const reserved;  // only when building for 64bit targets
3880  //   const uint8_t * const ivarLayout;
3881  //   const char *const name;
3882  //   const struct _method_list_t * const baseMethods;
3883  //   const struct _objc_protocol_list *const baseProtocols;
3884  //   const struct _ivar_list_t *const ivars;
3885  //   const uint8_t * const weakIvarLayout;
3886  //   const struct _prop_list_t * const properties;
3887  // }
3888
3889  // FIXME. Add 'reserved' field in 64bit abi mode!
3890  ClassRonfABITy = llvm::StructType::get(IntTy,
3891                                         IntTy,
3892                                         IntTy,
3893                                         Int8PtrTy,
3894                                         Int8PtrTy,
3895                                         MethodListnfABIPtrTy,
3896                                         ProtocolListnfABIPtrTy,
3897                                         IvarListnfABIPtrTy,
3898                                         Int8PtrTy,
3899                                         PropertyListPtrTy,
3900                                         NULL);
3901  CGM.getModule().addTypeName("struct._class_ro_t",
3902                              ClassRonfABITy);
3903
3904  // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
3905  std::vector<const llvm::Type*> Params;
3906  Params.push_back(ObjectPtrTy);
3907  Params.push_back(SelectorPtrTy);
3908  ImpnfABITy = llvm::PointerType::getUnqual(
3909                          llvm::FunctionType::get(ObjectPtrTy, Params, false));
3910
3911  // struct _class_t {
3912  //   struct _class_t *isa;
3913  //   struct _class_t * const superclass;
3914  //   void *cache;
3915  //   IMP *vtable;
3916  //   struct class_ro_t *ro;
3917  // }
3918
3919  llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
3920  ClassnfABITy = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
3921                                       llvm::PointerType::getUnqual(ClassTyHolder),
3922                                       CachePtrTy,
3923                                       llvm::PointerType::getUnqual(ImpnfABITy),
3924                                       llvm::PointerType::getUnqual(
3925                                                                ClassRonfABITy),
3926                                       NULL);
3927  CGM.getModule().addTypeName("struct._class_t", ClassnfABITy);
3928
3929  cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(
3930                                                                ClassnfABITy);
3931
3932  // LLVM for struct _class_t *
3933  ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
3934
3935  // struct _category_t {
3936  //   const char * const name;
3937  //   struct _class_t *const cls;
3938  //   const struct _method_list_t * const instance_methods;
3939  //   const struct _method_list_t * const class_methods;
3940  //   const struct _protocol_list_t * const protocols;
3941  //   const struct _prop_list_t * const properties;
3942  // }
3943  CategorynfABITy = llvm::StructType::get(Int8PtrTy,
3944                                          ClassnfABIPtrTy,
3945                                          MethodListnfABIPtrTy,
3946                                          MethodListnfABIPtrTy,
3947                                          ProtocolListnfABIPtrTy,
3948                                          PropertyListPtrTy,
3949                                          NULL);
3950  CGM.getModule().addTypeName("struct._category_t", CategorynfABITy);
3951
3952  // New types for nonfragile abi messaging.
3953  CodeGen::CodeGenTypes &Types = CGM.getTypes();
3954  ASTContext &Ctx = CGM.getContext();
3955
3956  // MessageRefTy - LLVM for:
3957  // struct _message_ref_t {
3958  //   IMP messenger;
3959  //   SEL name;
3960  // };
3961
3962  // First the clang type for struct _message_ref_t
3963  RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
3964                                      SourceLocation(),
3965                                      &Ctx.Idents.get("_message_ref_t"));
3966  RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3967                                     Ctx.VoidPtrTy, 0, false));
3968  RD->addDecl(Ctx, FieldDecl::Create(Ctx, RD, SourceLocation(), 0,
3969                                     Ctx.getObjCSelType(), 0, false));
3970  RD->completeDefinition(Ctx);
3971
3972  MessageRefCTy = Ctx.getTagDeclType(RD);
3973  MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
3974  MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
3975
3976  // MessageRefPtrTy - LLVM for struct _message_ref_t*
3977  MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
3978
3979  // SuperMessageRefTy - LLVM for:
3980  // struct _super_message_ref_t {
3981  //   SUPER_IMP messenger;
3982  //   SEL name;
3983  // };
3984  SuperMessageRefTy = llvm::StructType::get(ImpnfABITy,
3985                                            SelectorPtrTy,
3986                                            NULL);
3987  CGM.getModule().addTypeName("struct._super_message_ref_t", SuperMessageRefTy);
3988
3989  // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
3990  SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
3991
3992
3993  // struct objc_typeinfo {
3994  //   const void** vtable; // objc_ehtype_vtable + 2
3995  //   const char*  name;    // c++ typeinfo string
3996  //   Class        cls;
3997  // };
3998  EHTypeTy = llvm::StructType::get(llvm::PointerType::getUnqual(Int8PtrTy),
3999                                   Int8PtrTy,
4000                                   ClassnfABIPtrTy,
4001                                   NULL);
4002  CGM.getModule().addTypeName("struct._objc_typeinfo", EHTypeTy);
4003  EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
4004}
4005
4006llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
4007  FinishNonFragileABIModule();
4008
4009  return NULL;
4010}
4011
4012void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
4013  // nonfragile abi has no module definition.
4014
4015  // Build list of all implemented classe addresses in array
4016  // L_OBJC_LABEL_CLASS_$.
4017  // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CLASS_$
4018  // list of 'nonlazy' implementations (defined as those with a +load{}
4019  // method!!).
4020  unsigned NumClasses = DefinedClasses.size();
4021  if (NumClasses) {
4022    std::vector<llvm::Constant*> Symbols(NumClasses);
4023    for (unsigned i=0; i<NumClasses; i++)
4024      Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
4025                                                  ObjCTypes.Int8PtrTy);
4026    llvm::Constant* Init =
4027      llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4028                                                    NumClasses),
4029                               Symbols);
4030
4031    llvm::GlobalVariable *GV =
4032      new llvm::GlobalVariable(Init->getType(), false,
4033                               llvm::GlobalValue::InternalLinkage,
4034                               Init,
4035                               "\01L_OBJC_LABEL_CLASS_$",
4036                               &CGM.getModule());
4037    GV->setAlignment(8);
4038    GV->setSection("__DATA, __objc_classlist, regular, no_dead_strip");
4039    UsedGlobals.push_back(GV);
4040  }
4041
4042  // Build list of all implemented category addresses in array
4043  // L_OBJC_LABEL_CATEGORY_$.
4044  // FIXME. Also generate in L_OBJC_LABEL_NONLAZY_CATEGORY_$
4045  // list of 'nonlazy' category implementations (defined as those with a +load{}
4046  // method!!).
4047  unsigned NumCategory = DefinedCategories.size();
4048  if (NumCategory) {
4049    std::vector<llvm::Constant*> Symbols(NumCategory);
4050    for (unsigned i=0; i<NumCategory; i++)
4051      Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedCategories[i],
4052                                                  ObjCTypes.Int8PtrTy);
4053    llvm::Constant* Init =
4054      llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
4055                                                    NumCategory),
4056                               Symbols);
4057
4058    llvm::GlobalVariable *GV =
4059      new llvm::GlobalVariable(Init->getType(), false,
4060                               llvm::GlobalValue::InternalLinkage,
4061                               Init,
4062                               "\01L_OBJC_LABEL_CATEGORY_$",
4063                               &CGM.getModule());
4064    GV->setAlignment(8);
4065    GV->setSection("__DATA, __objc_catlist, regular, no_dead_strip");
4066    UsedGlobals.push_back(GV);
4067  }
4068
4069  //  static int L_OBJC_IMAGE_INFO[2] = { 0, flags };
4070  // FIXME. flags can be 0 | 1 | 2 | 6. For now just use 0
4071  std::vector<llvm::Constant*> Values(2);
4072  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, 0);
4073  unsigned int flags = 0;
4074  // FIXME: Fix and continue?
4075  if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
4076    flags |= eImageInfo_GarbageCollected;
4077  if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
4078    flags |= eImageInfo_GCOnly;
4079  Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4080  llvm::Constant* Init = llvm::ConstantArray::get(
4081                                      llvm::ArrayType::get(ObjCTypes.IntTy, 2),
4082                                      Values);
4083  llvm::GlobalVariable *IMGV =
4084    new llvm::GlobalVariable(Init->getType(), false,
4085                             llvm::GlobalValue::InternalLinkage,
4086                             Init,
4087                             "\01L_OBJC_IMAGE_INFO",
4088                             &CGM.getModule());
4089  IMGV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
4090  IMGV->setConstant(true);
4091  UsedGlobals.push_back(IMGV);
4092
4093  std::vector<llvm::Constant*> Used;
4094
4095  for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
4096       e = UsedGlobals.end(); i != e; ++i) {
4097    Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
4098  }
4099
4100  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
4101  llvm::GlobalValue *GV =
4102  new llvm::GlobalVariable(AT, false,
4103                           llvm::GlobalValue::AppendingLinkage,
4104                           llvm::ConstantArray::get(AT, Used),
4105                           "llvm.used",
4106                           &CGM.getModule());
4107
4108  GV->setSection("llvm.metadata");
4109
4110}
4111
4112// Metadata flags
4113enum MetaDataDlags {
4114  CLS = 0x0,
4115  CLS_META = 0x1,
4116  CLS_ROOT = 0x2,
4117  OBJC2_CLS_HIDDEN = 0x10,
4118  CLS_EXCEPTION = 0x20
4119};
4120/// BuildClassRoTInitializer - generate meta-data for:
4121/// struct _class_ro_t {
4122///   uint32_t const flags;
4123///   uint32_t const instanceStart;
4124///   uint32_t const instanceSize;
4125///   uint32_t const reserved;  // only when building for 64bit targets
4126///   const uint8_t * const ivarLayout;
4127///   const char *const name;
4128///   const struct _method_list_t * const baseMethods;
4129///   const struct _protocol_list_t *const baseProtocols;
4130///   const struct _ivar_list_t *const ivars;
4131///   const uint8_t * const weakIvarLayout;
4132///   const struct _prop_list_t * const properties;
4133/// }
4134///
4135llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
4136                                                unsigned flags,
4137                                                unsigned InstanceStart,
4138                                                unsigned InstanceSize,
4139                                                const ObjCImplementationDecl *ID) {
4140  std::string ClassName = ID->getNameAsString();
4141  std::vector<llvm::Constant*> Values(10); // 11 for 64bit targets!
4142  Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
4143  Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
4144  Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
4145  // FIXME. For 64bit targets add 0 here.
4146  Values[ 3] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4147                                  : BuildIvarLayout(ID, true);
4148  Values[ 4] = GetClassName(ID->getIdentifier());
4149  // const struct _method_list_t * const baseMethods;
4150  std::vector<llvm::Constant*> Methods;
4151  std::string MethodListName("\01l_OBJC_$_");
4152  if (flags & CLS_META) {
4153    MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
4154    for (ObjCImplementationDecl::classmeth_iterator
4155           i = ID->classmeth_begin(CGM.getContext()),
4156           e = ID->classmeth_end(CGM.getContext()); i != e; ++i) {
4157      // Class methods should always be defined.
4158      Methods.push_back(GetMethodConstant(*i));
4159    }
4160  } else {
4161    MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
4162    for (ObjCImplementationDecl::instmeth_iterator
4163           i = ID->instmeth_begin(CGM.getContext()),
4164           e = ID->instmeth_end(CGM.getContext()); i != e; ++i) {
4165      // Instance methods should always be defined.
4166      Methods.push_back(GetMethodConstant(*i));
4167    }
4168    for (ObjCImplementationDecl::propimpl_iterator
4169           i = ID->propimpl_begin(CGM.getContext()),
4170           e = ID->propimpl_end(CGM.getContext()); i != e; ++i) {
4171      ObjCPropertyImplDecl *PID = *i;
4172
4173      if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
4174        ObjCPropertyDecl *PD = PID->getPropertyDecl();
4175
4176        if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
4177          if (llvm::Constant *C = GetMethodConstant(MD))
4178            Methods.push_back(C);
4179        if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
4180          if (llvm::Constant *C = GetMethodConstant(MD))
4181            Methods.push_back(C);
4182      }
4183    }
4184  }
4185  Values[ 5] = EmitMethodList(MethodListName,
4186               "__DATA, __objc_const", Methods);
4187
4188  const ObjCInterfaceDecl *OID = ID->getClassInterface();
4189  assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
4190  Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
4191                                + OID->getNameAsString(),
4192                                OID->protocol_begin(),
4193                                OID->protocol_end());
4194
4195  if (flags & CLS_META)
4196    Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4197  else
4198    Values[ 7] = EmitIvarList(ID);
4199  Values[ 8] = (flags & CLS_META) ? GetIvarLayoutName(0, ObjCTypes)
4200                                  : BuildIvarLayout(ID, false);
4201  if (flags & CLS_META)
4202    Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4203  else
4204    Values[ 9] =
4205      EmitPropertyList(
4206                       "\01l_OBJC_$_PROP_LIST_" + ID->getNameAsString(),
4207                       ID, ID->getClassInterface(), ObjCTypes);
4208  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
4209                                                   Values);
4210  llvm::GlobalVariable *CLASS_RO_GV =
4211  new llvm::GlobalVariable(ObjCTypes.ClassRonfABITy, false,
4212                           llvm::GlobalValue::InternalLinkage,
4213                           Init,
4214                           (flags & CLS_META) ?
4215                           std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
4216                           std::string("\01l_OBJC_CLASS_RO_$_")+ClassName,
4217                           &CGM.getModule());
4218  CLASS_RO_GV->setAlignment(
4219    CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassRonfABITy));
4220  CLASS_RO_GV->setSection("__DATA, __objc_const");
4221  return CLASS_RO_GV;
4222
4223}
4224
4225/// BuildClassMetaData - This routine defines that to-level meta-data
4226/// for the given ClassName for:
4227/// struct _class_t {
4228///   struct _class_t *isa;
4229///   struct _class_t * const superclass;
4230///   void *cache;
4231///   IMP *vtable;
4232///   struct class_ro_t *ro;
4233/// }
4234///
4235llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
4236                                                std::string &ClassName,
4237                                                llvm::Constant *IsAGV,
4238                                                llvm::Constant *SuperClassGV,
4239                                                llvm::Constant *ClassRoGV,
4240                                                bool HiddenVisibility) {
4241  std::vector<llvm::Constant*> Values(5);
4242  Values[0] = IsAGV;
4243  Values[1] = SuperClassGV
4244                ? SuperClassGV
4245                : llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
4246  Values[2] = ObjCEmptyCacheVar;  // &ObjCEmptyCacheVar
4247  Values[3] = ObjCEmptyVtableVar; // &ObjCEmptyVtableVar
4248  Values[4] = ClassRoGV;                 // &CLASS_RO_GV
4249  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
4250                                                   Values);
4251  llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
4252  GV->setInitializer(Init);
4253  GV->setSection("__DATA, __objc_data");
4254  GV->setAlignment(
4255    CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ClassnfABITy));
4256  if (HiddenVisibility)
4257    GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4258  return GV;
4259}
4260
4261void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCInterfaceDecl *OID,
4262                                              uint32_t &InstanceStart,
4263                                              uint32_t &InstanceSize) {
4264  // Find first and last (non-padding) ivars in this interface.
4265
4266  // FIXME: Use iterator.
4267  llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
4268  GetNamedIvarList(OID, OIvars);
4269
4270  if (OIvars.empty()) {
4271    InstanceStart = InstanceSize = 0;
4272    return;
4273  }
4274
4275  const ObjCIvarDecl *First = OIvars.front();
4276  const ObjCIvarDecl *Last = OIvars.back();
4277
4278  InstanceStart = ComputeIvarBaseOffset(CGM, OID, First);
4279  const llvm::Type *FieldTy =
4280    CGM.getTypes().ConvertTypeForMem(Last->getType());
4281  unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4282// FIXME. This breaks compatibility with llvm-gcc-4.2 (but makes it compatible
4283// with gcc-4.2). We postpone this for now.
4284#if 0
4285  if (Last->isBitField()) {
4286    Expr *BitWidth = Last->getBitWidth();
4287    uint64_t BitFieldSize =
4288      BitWidth->EvaluateAsInt(CGM.getContext()).getZExtValue();
4289    Size = (BitFieldSize / 8) + ((BitFieldSize % 8) != 0);
4290  }
4291#endif
4292  InstanceSize = ComputeIvarBaseOffset(CGM, OID, Last) + Size;
4293}
4294
4295void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
4296  std::string ClassName = ID->getNameAsString();
4297  if (!ObjCEmptyCacheVar) {
4298    ObjCEmptyCacheVar = new llvm::GlobalVariable(
4299                                            ObjCTypes.CacheTy,
4300                                            false,
4301                                            llvm::GlobalValue::ExternalLinkage,
4302                                            0,
4303                                            "_objc_empty_cache",
4304                                            &CGM.getModule());
4305
4306    ObjCEmptyVtableVar = new llvm::GlobalVariable(
4307                            ObjCTypes.ImpnfABITy,
4308                            false,
4309                            llvm::GlobalValue::ExternalLinkage,
4310                            0,
4311                            "_objc_empty_vtable",
4312                            &CGM.getModule());
4313  }
4314  assert(ID->getClassInterface() &&
4315         "CGObjCNonFragileABIMac::GenerateClass - class is 0");
4316  // FIXME: Is this correct (that meta class size is never computed)?
4317  uint32_t InstanceStart =
4318    CGM.getTargetData().getTypePaddedSize(ObjCTypes.ClassnfABITy);
4319  uint32_t InstanceSize = InstanceStart;
4320  uint32_t flags = CLS_META;
4321  std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
4322  std::string ObjCClassName(getClassSymbolPrefix());
4323
4324  llvm::GlobalVariable *SuperClassGV, *IsAGV;
4325
4326  bool classIsHidden =
4327    CGM.getDeclVisibilityMode(ID->getClassInterface()) == LangOptions::Hidden;
4328  if (classIsHidden)
4329    flags |= OBJC2_CLS_HIDDEN;
4330  if (!ID->getClassInterface()->getSuperClass()) {
4331    // class is root
4332    flags |= CLS_ROOT;
4333    SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
4334    IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
4335  } else {
4336    // Has a root. Current class is not a root.
4337    const ObjCInterfaceDecl *Root = ID->getClassInterface();
4338    while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
4339      Root = Super;
4340    IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
4341    // work on super class metadata symbol.
4342    std::string SuperClassName =
4343      ObjCMetaClassName + ID->getClassInterface()->getSuperClass()->getNameAsString();
4344    SuperClassGV = GetClassGlobal(SuperClassName);
4345  }
4346  llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
4347                                                               InstanceStart,
4348                                                               InstanceSize,ID);
4349  std::string TClassName = ObjCMetaClassName + ClassName;
4350  llvm::GlobalVariable *MetaTClass =
4351    BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
4352                       classIsHidden);
4353
4354  // Metadata for the class
4355  flags = CLS;
4356  if (classIsHidden)
4357    flags |= OBJC2_CLS_HIDDEN;
4358
4359  if (hasObjCExceptionAttribute(ID->getClassInterface()))
4360    flags |= CLS_EXCEPTION;
4361
4362  if (!ID->getClassInterface()->getSuperClass()) {
4363    flags |= CLS_ROOT;
4364    SuperClassGV = 0;
4365  } else {
4366    // Has a root. Current class is not a root.
4367    std::string RootClassName =
4368      ID->getClassInterface()->getSuperClass()->getNameAsString();
4369    SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
4370  }
4371  GetClassSizeInfo(ID->getClassInterface(), InstanceStart, InstanceSize);
4372  CLASS_RO_GV = BuildClassRoTInitializer(flags,
4373                                         InstanceStart,
4374                                         InstanceSize,
4375                                         ID);
4376
4377  TClassName = ObjCClassName + ClassName;
4378  llvm::GlobalVariable *ClassMD =
4379    BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
4380                       classIsHidden);
4381  DefinedClasses.push_back(ClassMD);
4382
4383  // Force the definition of the EHType if necessary.
4384  if (flags & CLS_EXCEPTION)
4385    GetInterfaceEHType(ID->getClassInterface(), true);
4386}
4387
4388/// GenerateProtocolRef - This routine is called to generate code for
4389/// a protocol reference expression; as in:
4390/// @code
4391///   @protocol(Proto1);
4392/// @endcode
4393/// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
4394/// which will hold address of the protocol meta-data.
4395///
4396llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CGBuilderTy &Builder,
4397                                            const ObjCProtocolDecl *PD) {
4398
4399  // This routine is called for @protocol only. So, we must build definition
4400  // of protocol's meta-data (not a reference to it!)
4401  //
4402  llvm::Constant *Init =  llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
4403                                        ObjCTypes.ExternalProtocolPtrTy);
4404
4405  std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
4406  ProtocolName += PD->getNameAsCString();
4407
4408  llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
4409  if (PTGV)
4410    return Builder.CreateLoad(PTGV, false, "tmp");
4411  PTGV = new llvm::GlobalVariable(
4412                                Init->getType(), false,
4413                                llvm::GlobalValue::WeakAnyLinkage,
4414                                Init,
4415                                ProtocolName,
4416                                &CGM.getModule());
4417  PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
4418  PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4419  UsedGlobals.push_back(PTGV);
4420  return Builder.CreateLoad(PTGV, false, "tmp");
4421}
4422
4423/// GenerateCategory - Build metadata for a category implementation.
4424/// struct _category_t {
4425///   const char * const name;
4426///   struct _class_t *const cls;
4427///   const struct _method_list_t * const instance_methods;
4428///   const struct _method_list_t * const class_methods;
4429///   const struct _protocol_list_t * const protocols;
4430///   const struct _prop_list_t * const properties;
4431/// }
4432///
4433void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD)
4434{
4435  const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
4436  const char *Prefix = "\01l_OBJC_$_CATEGORY_";
4437  std::string ExtCatName(Prefix + Interface->getNameAsString()+
4438                      "_$_" + OCD->getNameAsString());
4439  std::string ExtClassName(getClassSymbolPrefix() +
4440                           Interface->getNameAsString());
4441
4442  std::vector<llvm::Constant*> Values(6);
4443  Values[0] = GetClassName(OCD->getIdentifier());
4444  // meta-class entry symbol
4445  llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
4446  Values[1] = ClassGV;
4447  std::vector<llvm::Constant*> Methods;
4448  std::string MethodListName(Prefix);
4449  MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
4450    "_$_" + OCD->getNameAsString();
4451
4452  for (ObjCCategoryImplDecl::instmeth_iterator
4453         i = OCD->instmeth_begin(CGM.getContext()),
4454         e = OCD->instmeth_end(CGM.getContext()); i != e; ++i) {
4455    // Instance methods should always be defined.
4456    Methods.push_back(GetMethodConstant(*i));
4457  }
4458
4459  Values[2] = EmitMethodList(MethodListName,
4460                             "__DATA, __objc_const",
4461                             Methods);
4462
4463  MethodListName = Prefix;
4464  MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
4465    OCD->getNameAsString();
4466  Methods.clear();
4467  for (ObjCCategoryImplDecl::classmeth_iterator
4468         i = OCD->classmeth_begin(CGM.getContext()),
4469         e = OCD->classmeth_end(CGM.getContext()); i != e; ++i) {
4470    // Class methods should always be defined.
4471    Methods.push_back(GetMethodConstant(*i));
4472  }
4473
4474  Values[3] = EmitMethodList(MethodListName,
4475                             "__DATA, __objc_const",
4476                             Methods);
4477  const ObjCCategoryDecl *Category =
4478    Interface->FindCategoryDeclaration(OCD->getIdentifier());
4479  if (Category) {
4480    std::string ExtName(Interface->getNameAsString() + "_$_" +
4481                        OCD->getNameAsString());
4482    Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
4483                                 + Interface->getNameAsString() + "_$_"
4484                                 + Category->getNameAsString(),
4485                                 Category->protocol_begin(),
4486                                 Category->protocol_end());
4487    Values[5] =
4488      EmitPropertyList(std::string("\01l_OBJC_$_PROP_LIST_") + ExtName,
4489                       OCD, Category, ObjCTypes);
4490  }
4491  else {
4492    Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4493    Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
4494  }
4495
4496  llvm::Constant *Init =
4497    llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
4498                              Values);
4499  llvm::GlobalVariable *GCATV
4500    = new llvm::GlobalVariable(ObjCTypes.CategorynfABITy,
4501                               false,
4502                               llvm::GlobalValue::InternalLinkage,
4503                               Init,
4504                               ExtCatName,
4505                               &CGM.getModule());
4506  GCATV->setAlignment(
4507    CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.CategorynfABITy));
4508  GCATV->setSection("__DATA, __objc_const");
4509  UsedGlobals.push_back(GCATV);
4510  DefinedCategories.push_back(GCATV);
4511}
4512
4513/// GetMethodConstant - Return a struct objc_method constant for the
4514/// given method if it has been defined. The result is null if the
4515/// method has not been defined. The return value has type MethodPtrTy.
4516llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
4517                                                    const ObjCMethodDecl *MD) {
4518  // FIXME: Use DenseMap::lookup
4519  llvm::Function *Fn = MethodDefinitions[MD];
4520  if (!Fn)
4521    return 0;
4522
4523  std::vector<llvm::Constant*> Method(3);
4524  Method[0] =
4525  llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4526                                 ObjCTypes.SelectorPtrTy);
4527  Method[1] = GetMethodVarType(MD);
4528  Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
4529  return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
4530}
4531
4532/// EmitMethodList - Build meta-data for method declarations
4533/// struct _method_list_t {
4534///   uint32_t entsize;  // sizeof(struct _objc_method)
4535///   uint32_t method_count;
4536///   struct _objc_method method_list[method_count];
4537/// }
4538///
4539llvm::Constant *CGObjCNonFragileABIMac::EmitMethodList(
4540                                              const std::string &Name,
4541                                              const char *Section,
4542                                              const ConstantVector &Methods) {
4543  // Return null for empty list.
4544  if (Methods.empty())
4545    return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
4546
4547  std::vector<llvm::Constant*> Values(3);
4548  // sizeof(struct _objc_method)
4549  unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.MethodTy);
4550  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4551  // method_count
4552  Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
4553  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
4554                                             Methods.size());
4555  Values[2] = llvm::ConstantArray::get(AT, Methods);
4556  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4557
4558  llvm::GlobalVariable *GV =
4559    new llvm::GlobalVariable(Init->getType(), false,
4560                             llvm::GlobalValue::InternalLinkage,
4561                             Init,
4562                             Name,
4563                             &CGM.getModule());
4564  GV->setAlignment(
4565    CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
4566  GV->setSection(Section);
4567  UsedGlobals.push_back(GV);
4568  return llvm::ConstantExpr::getBitCast(GV,
4569                                        ObjCTypes.MethodListnfABIPtrTy);
4570}
4571
4572/// ObjCIvarOffsetVariable - Returns the ivar offset variable for
4573/// the given ivar.
4574///
4575llvm::GlobalVariable * CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(
4576                              const ObjCInterfaceDecl *ID,
4577                              const ObjCIvarDecl *Ivar) {
4578  std::string Name = "OBJC_IVAR_$_" +
4579    getInterfaceDeclForIvar(ID, Ivar, CGM.getContext())->getNameAsString() +
4580    '.' + Ivar->getNameAsString();
4581  llvm::GlobalVariable *IvarOffsetGV =
4582    CGM.getModule().getGlobalVariable(Name);
4583  if (!IvarOffsetGV)
4584    IvarOffsetGV =
4585      new llvm::GlobalVariable(ObjCTypes.LongTy,
4586                               false,
4587                               llvm::GlobalValue::ExternalLinkage,
4588                               0,
4589                               Name,
4590                               &CGM.getModule());
4591  return IvarOffsetGV;
4592}
4593
4594llvm::Constant * CGObjCNonFragileABIMac::EmitIvarOffsetVar(
4595                                              const ObjCInterfaceDecl *ID,
4596                                              const ObjCIvarDecl *Ivar,
4597                                              unsigned long int Offset) {
4598  llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
4599  IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
4600                                                      Offset));
4601  IvarOffsetGV->setAlignment(
4602    CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.LongTy));
4603
4604  // FIXME: This matches gcc, but shouldn't the visibility be set on
4605  // the use as well (i.e., in ObjCIvarOffsetVariable).
4606  if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
4607      Ivar->getAccessControl() == ObjCIvarDecl::Package ||
4608      CGM.getDeclVisibilityMode(ID) == LangOptions::Hidden)
4609    IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4610  else
4611    IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
4612  IvarOffsetGV->setSection("__DATA, __objc_const");
4613  return IvarOffsetGV;
4614}
4615
4616/// EmitIvarList - Emit the ivar list for the given
4617/// implementation. The return value has type
4618/// IvarListnfABIPtrTy.
4619///  struct _ivar_t {
4620///   unsigned long int *offset;  // pointer to ivar offset location
4621///   char *name;
4622///   char *type;
4623///   uint32_t alignment;
4624///   uint32_t size;
4625/// }
4626/// struct _ivar_list_t {
4627///   uint32 entsize;  // sizeof(struct _ivar_t)
4628///   uint32 count;
4629///   struct _iver_t list[count];
4630/// }
4631///
4632
4633void CGObjCCommonMac::GetNamedIvarList(const ObjCInterfaceDecl *OID,
4634                              llvm::SmallVector<ObjCIvarDecl*, 16> &Res) const {
4635  for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
4636         E = OID->ivar_end(); I != E; ++I) {
4637    // Ignore unnamed bit-fields.
4638    if (!(*I)->getDeclName())
4639      continue;
4640
4641     Res.push_back(*I);
4642  }
4643
4644  for (ObjCInterfaceDecl::prop_iterator I = OID->prop_begin(CGM.getContext()),
4645         E = OID->prop_end(CGM.getContext()); I != E; ++I)
4646    if (ObjCIvarDecl *IV = (*I)->getPropertyIvarDecl())
4647      Res.push_back(IV);
4648}
4649
4650llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
4651                                            const ObjCImplementationDecl *ID) {
4652
4653  std::vector<llvm::Constant*> Ivars, Ivar(5);
4654
4655  const ObjCInterfaceDecl *OID = ID->getClassInterface();
4656  assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
4657
4658  // FIXME. Consolidate this with similar code in GenerateClass.
4659
4660  // Collect declared and synthesized ivars in a small vector.
4661  llvm::SmallVector<ObjCIvarDecl*, 16> OIvars;
4662  GetNamedIvarList(OID, OIvars);
4663
4664  for (unsigned i = 0, e = OIvars.size(); i != e; ++i) {
4665    ObjCIvarDecl *IVD = OIvars[i];
4666    Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
4667                                ComputeIvarBaseOffset(CGM, OID, IVD));
4668    Ivar[1] = GetMethodVarName(IVD->getIdentifier());
4669    Ivar[2] = GetMethodVarType(IVD);
4670    const llvm::Type *FieldTy =
4671      CGM.getTypes().ConvertTypeForMem(IVD->getType());
4672    unsigned Size = CGM.getTargetData().getTypePaddedSize(FieldTy);
4673    unsigned Align = CGM.getContext().getPreferredTypeAlign(
4674                       IVD->getType().getTypePtr()) >> 3;
4675    Align = llvm::Log2_32(Align);
4676    Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
4677    // NOTE. Size of a bitfield does not match gcc's, because of the
4678    // way bitfields are treated special in each. But I am told that
4679    // 'size' for bitfield ivars is ignored by the runtime so it does
4680    // not matter.  If it matters, there is enough info to get the
4681    // bitfield right!
4682    Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4683    Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
4684  }
4685  // Return null for empty list.
4686  if (Ivars.empty())
4687    return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
4688  std::vector<llvm::Constant*> Values(3);
4689  unsigned Size = CGM.getTargetData().getTypePaddedSize(ObjCTypes.IvarnfABITy);
4690  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4691  Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
4692  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
4693                                             Ivars.size());
4694  Values[2] = llvm::ConstantArray::get(AT, Ivars);
4695  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4696  const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
4697  llvm::GlobalVariable *GV =
4698    new llvm::GlobalVariable(Init->getType(), false,
4699                             llvm::GlobalValue::InternalLinkage,
4700                             Init,
4701                             Prefix + OID->getNameAsString(),
4702                             &CGM.getModule());
4703  GV->setAlignment(
4704    CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
4705  GV->setSection("__DATA, __objc_const");
4706
4707  UsedGlobals.push_back(GV);
4708  return llvm::ConstantExpr::getBitCast(GV,
4709                                        ObjCTypes.IvarListnfABIPtrTy);
4710}
4711
4712llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
4713                                                  const ObjCProtocolDecl *PD) {
4714  llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4715
4716  if (!Entry) {
4717    // We use the initializer as a marker of whether this is a forward
4718    // reference or not. At module finalization we add the empty
4719    // contents for protocols which were referenced but never defined.
4720    Entry =
4721    new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4722                             llvm::GlobalValue::ExternalLinkage,
4723                             0,
4724                             "\01l_OBJC_PROTOCOL_$_" + PD->getNameAsString(),
4725                             &CGM.getModule());
4726    Entry->setSection("__DATA,__datacoal_nt,coalesced");
4727    UsedGlobals.push_back(Entry);
4728  }
4729
4730  return Entry;
4731}
4732
4733/// GetOrEmitProtocol - Generate the protocol meta-data:
4734/// @code
4735/// struct _protocol_t {
4736///   id isa;  // NULL
4737///   const char * const protocol_name;
4738///   const struct _protocol_list_t * protocol_list; // super protocols
4739///   const struct method_list_t * const instance_methods;
4740///   const struct method_list_t * const class_methods;
4741///   const struct method_list_t *optionalInstanceMethods;
4742///   const struct method_list_t *optionalClassMethods;
4743///   const struct _prop_list_t * properties;
4744///   const uint32_t size;  // sizeof(struct _protocol_t)
4745///   const uint32_t flags;  // = 0
4746/// }
4747/// @endcode
4748///
4749
4750llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
4751                                                  const ObjCProtocolDecl *PD) {
4752  llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
4753
4754  // Early exit if a defining object has already been generated.
4755  if (Entry && Entry->hasInitializer())
4756    return Entry;
4757
4758  const char *ProtocolName = PD->getNameAsCString();
4759
4760  // Construct method lists.
4761  std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
4762  std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
4763  for (ObjCProtocolDecl::instmeth_iterator
4764         i = PD->instmeth_begin(CGM.getContext()),
4765         e = PD->instmeth_end(CGM.getContext());
4766       i != e; ++i) {
4767    ObjCMethodDecl *MD = *i;
4768    llvm::Constant *C = GetMethodDescriptionConstant(MD);
4769    if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4770      OptInstanceMethods.push_back(C);
4771    } else {
4772      InstanceMethods.push_back(C);
4773    }
4774  }
4775
4776  for (ObjCProtocolDecl::classmeth_iterator
4777         i = PD->classmeth_begin(CGM.getContext()),
4778         e = PD->classmeth_end(CGM.getContext());
4779       i != e; ++i) {
4780    ObjCMethodDecl *MD = *i;
4781    llvm::Constant *C = GetMethodDescriptionConstant(MD);
4782    if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
4783      OptClassMethods.push_back(C);
4784    } else {
4785      ClassMethods.push_back(C);
4786    }
4787  }
4788
4789  std::vector<llvm::Constant*> Values(10);
4790  // isa is NULL
4791  Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
4792  Values[1] = GetClassName(PD->getIdentifier());
4793  Values[2] = EmitProtocolList(
4794                          "\01l_OBJC_$_PROTOCOL_REFS_" + PD->getNameAsString(),
4795                          PD->protocol_begin(),
4796                          PD->protocol_end());
4797
4798  Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
4799                             + PD->getNameAsString(),
4800                             "__DATA, __objc_const",
4801                             InstanceMethods);
4802  Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
4803                             + PD->getNameAsString(),
4804                             "__DATA, __objc_const",
4805                             ClassMethods);
4806  Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
4807                             + PD->getNameAsString(),
4808                             "__DATA, __objc_const",
4809                             OptInstanceMethods);
4810  Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
4811                             + PD->getNameAsString(),
4812                             "__DATA, __objc_const",
4813                             OptClassMethods);
4814  Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getNameAsString(),
4815                               0, PD, ObjCTypes);
4816  uint32_t Size =
4817    CGM.getTargetData().getTypePaddedSize(ObjCTypes.ProtocolnfABITy);
4818  Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
4819  Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
4820  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
4821                                                   Values);
4822
4823  if (Entry) {
4824    // Already created, fix the linkage and update the initializer.
4825    Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
4826    Entry->setInitializer(Init);
4827  } else {
4828    Entry =
4829    new llvm::GlobalVariable(ObjCTypes.ProtocolnfABITy, false,
4830                             llvm::GlobalValue::WeakAnyLinkage,
4831                             Init,
4832                             std::string("\01l_OBJC_PROTOCOL_$_")+ProtocolName,
4833                             &CGM.getModule());
4834    Entry->setAlignment(
4835      CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABITy));
4836    Entry->setSection("__DATA,__datacoal_nt,coalesced");
4837  }
4838  Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
4839
4840  // Use this protocol meta-data to build protocol list table in section
4841  // __DATA, __objc_protolist
4842  llvm::GlobalVariable *PTGV = new llvm::GlobalVariable(
4843                                      ObjCTypes.ProtocolnfABIPtrTy, false,
4844                                      llvm::GlobalValue::WeakAnyLinkage,
4845                                      Entry,
4846                                      std::string("\01l_OBJC_LABEL_PROTOCOL_$_")
4847                                                  +ProtocolName,
4848                                      &CGM.getModule());
4849  PTGV->setAlignment(
4850    CGM.getTargetData().getPrefTypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
4851  PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
4852  PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
4853  UsedGlobals.push_back(PTGV);
4854  return Entry;
4855}
4856
4857/// EmitProtocolList - Generate protocol list meta-data:
4858/// @code
4859/// struct _protocol_list_t {
4860///   long protocol_count;   // Note, this is 32/64 bit
4861///   struct _protocol_t[protocol_count];
4862/// }
4863/// @endcode
4864///
4865llvm::Constant *
4866CGObjCNonFragileABIMac::EmitProtocolList(const std::string &Name,
4867                            ObjCProtocolDecl::protocol_iterator begin,
4868                            ObjCProtocolDecl::protocol_iterator end) {
4869  std::vector<llvm::Constant*> ProtocolRefs;
4870
4871  // Just return null for empty protocol lists
4872  if (begin == end)
4873    return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
4874
4875  // FIXME: We shouldn't need to do this lookup here, should we?
4876  llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
4877  if (GV)
4878    return llvm::ConstantExpr::getBitCast(GV,
4879                                          ObjCTypes.ProtocolListnfABIPtrTy);
4880
4881  for (; begin != end; ++begin)
4882    ProtocolRefs.push_back(GetProtocolRef(*begin));  // Implemented???
4883
4884  // This list is null terminated.
4885  ProtocolRefs.push_back(llvm::Constant::getNullValue(
4886                                            ObjCTypes.ProtocolnfABIPtrTy));
4887
4888  std::vector<llvm::Constant*> Values(2);
4889  Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
4890  Values[1] =
4891    llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
4892                                                  ProtocolRefs.size()),
4893                                                  ProtocolRefs);
4894
4895  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
4896  GV = new llvm::GlobalVariable(Init->getType(), false,
4897                                llvm::GlobalValue::InternalLinkage,
4898                                Init,
4899                                Name,
4900                                &CGM.getModule());
4901  GV->setSection("__DATA, __objc_const");
4902  GV->setAlignment(
4903    CGM.getTargetData().getPrefTypeAlignment(Init->getType()));
4904  UsedGlobals.push_back(GV);
4905  return llvm::ConstantExpr::getBitCast(GV,
4906                                        ObjCTypes.ProtocolListnfABIPtrTy);
4907}
4908
4909/// GetMethodDescriptionConstant - This routine build following meta-data:
4910/// struct _objc_method {
4911///   SEL _cmd;
4912///   char *method_type;
4913///   char *_imp;
4914/// }
4915
4916llvm::Constant *
4917CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
4918  std::vector<llvm::Constant*> Desc(3);
4919  Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
4920                                           ObjCTypes.SelectorPtrTy);
4921  Desc[1] = GetMethodVarType(MD);
4922  // Protocol methods have no implementation. So, this entry is always NULL.
4923  Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
4924  return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
4925}
4926
4927/// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
4928/// This code gen. amounts to generating code for:
4929/// @code
4930/// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
4931/// @encode
4932///
4933LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
4934                                             CodeGen::CodeGenFunction &CGF,
4935                                             QualType ObjectTy,
4936                                             llvm::Value *BaseValue,
4937                                             const ObjCIvarDecl *Ivar,
4938                                             unsigned CVRQualifiers) {
4939  const ObjCInterfaceDecl *ID = ObjectTy->getAsObjCInterfaceType()->getDecl();
4940  return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4941                                  EmitIvarOffset(CGF, ID, Ivar));
4942}
4943
4944llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
4945                                       CodeGen::CodeGenFunction &CGF,
4946                                       const ObjCInterfaceDecl *Interface,
4947                                       const ObjCIvarDecl *Ivar) {
4948  return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),
4949                                false, "ivar");
4950}
4951
4952CodeGen::RValue CGObjCNonFragileABIMac::EmitMessageSend(
4953                                           CodeGen::CodeGenFunction &CGF,
4954                                           QualType ResultType,
4955                                           Selector Sel,
4956                                           llvm::Value *Receiver,
4957                                           QualType Arg0Ty,
4958                                           bool IsSuper,
4959                                           const CallArgList &CallArgs) {
4960  // FIXME. Even though IsSuper is passes. This function doese not
4961  // handle calls to 'super' receivers.
4962  CodeGenTypes &Types = CGM.getTypes();
4963  llvm::Value *Arg0 = Receiver;
4964  if (!IsSuper)
4965    Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy, "tmp");
4966
4967  // Find the message function name.
4968  // FIXME. This is too much work to get the ABI-specific result type
4969  // needed to find the message name.
4970  const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType,
4971                                        llvm::SmallVector<QualType, 16>());
4972  llvm::Constant *Fn = 0;
4973  std::string Name("\01l_");
4974  if (CGM.ReturnTypeUsesSret(FnInfo)) {
4975#if 0
4976    // unlike what is documented. gcc never generates this API!!
4977    if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
4978      Fn = ObjCTypes.getMessageSendIdStretFixupFn();
4979      // FIXME. Is there a better way of getting these names.
4980      // They are available in RuntimeFunctions vector pair.
4981      Name += "objc_msgSendId_stret_fixup";
4982    }
4983    else
4984#endif
4985    if (IsSuper) {
4986        Fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
4987        Name += "objc_msgSendSuper2_stret_fixup";
4988    }
4989    else
4990    {
4991      Fn = ObjCTypes.getMessageSendStretFixupFn();
4992      Name += "objc_msgSend_stret_fixup";
4993    }
4994  }
4995  else if (!IsSuper && ResultType->isFloatingType()) {
4996    if (const BuiltinType *BT = ResultType->getAsBuiltinType()) {
4997      BuiltinType::Kind k = BT->getKind();
4998      if (k == BuiltinType::LongDouble) {
4999        Fn = ObjCTypes.getMessageSendFpretFixupFn();
5000        Name += "objc_msgSend_fpret_fixup";
5001      }
5002      else {
5003        Fn = ObjCTypes.getMessageSendFixupFn();
5004        Name += "objc_msgSend_fixup";
5005      }
5006    }
5007  }
5008  else {
5009#if 0
5010// unlike what is documented. gcc never generates this API!!
5011    if (Receiver->getType() == ObjCTypes.ObjectPtrTy) {
5012      Fn = ObjCTypes.getMessageSendIdFixupFn();
5013      Name += "objc_msgSendId_fixup";
5014    }
5015    else
5016#endif
5017    if (IsSuper) {
5018        Fn = ObjCTypes.getMessageSendSuper2FixupFn();
5019        Name += "objc_msgSendSuper2_fixup";
5020    }
5021    else
5022    {
5023      Fn = ObjCTypes.getMessageSendFixupFn();
5024      Name += "objc_msgSend_fixup";
5025    }
5026  }
5027  assert(Fn && "CGObjCNonFragileABIMac::EmitMessageSend");
5028  Name += '_';
5029  std::string SelName(Sel.getAsString());
5030  // Replace all ':' in selector name with '_'  ouch!
5031  for(unsigned i = 0; i < SelName.size(); i++)
5032    if (SelName[i] == ':')
5033      SelName[i] = '_';
5034  Name += SelName;
5035  llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5036  if (!GV) {
5037    // Build message ref table entry.
5038    std::vector<llvm::Constant*> Values(2);
5039    Values[0] = Fn;
5040    Values[1] = GetMethodVarName(Sel);
5041    llvm::Constant *Init = llvm::ConstantStruct::get(Values);
5042    GV =  new llvm::GlobalVariable(Init->getType(), false,
5043                                   llvm::GlobalValue::WeakAnyLinkage,
5044                                   Init,
5045                                   Name,
5046                                   &CGM.getModule());
5047    GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
5048    GV->setAlignment(16);
5049    GV->setSection("__DATA, __objc_msgrefs, coalesced");
5050  }
5051  llvm::Value *Arg1 = CGF.Builder.CreateBitCast(GV, ObjCTypes.MessageRefPtrTy);
5052
5053  CallArgList ActualArgs;
5054  ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
5055  ActualArgs.push_back(std::make_pair(RValue::get(Arg1),
5056                                      ObjCTypes.MessageRefCPtrTy));
5057  ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
5058  const CGFunctionInfo &FnInfo1 = Types.getFunctionInfo(ResultType, ActualArgs);
5059  llvm::Value *Callee = CGF.Builder.CreateStructGEP(Arg1, 0);
5060  Callee = CGF.Builder.CreateLoad(Callee);
5061  const llvm::FunctionType *FTy = Types.GetFunctionType(FnInfo1, true);
5062  Callee = CGF.Builder.CreateBitCast(Callee,
5063                                     llvm::PointerType::getUnqual(FTy));
5064  return CGF.EmitCall(FnInfo1, Callee, ActualArgs);
5065}
5066
5067/// Generate code for a message send expression in the nonfragile abi.
5068CodeGen::RValue CGObjCNonFragileABIMac::GenerateMessageSend(
5069                                               CodeGen::CodeGenFunction &CGF,
5070                                               QualType ResultType,
5071                                               Selector Sel,
5072                                               llvm::Value *Receiver,
5073                                               bool IsClassMessage,
5074                                               const CallArgList &CallArgs) {
5075  return EmitMessageSend(CGF, ResultType, Sel,
5076                         Receiver, CGF.getContext().getObjCIdType(),
5077                         false, CallArgs);
5078}
5079
5080llvm::GlobalVariable *
5081CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
5082  llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
5083
5084  if (!GV) {
5085    GV = new llvm::GlobalVariable(ObjCTypes.ClassnfABITy, false,
5086                                  llvm::GlobalValue::ExternalLinkage,
5087                                  0, Name, &CGM.getModule());
5088  }
5089
5090  return GV;
5091}
5092
5093llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CGBuilderTy &Builder,
5094                                     const ObjCInterfaceDecl *ID) {
5095  llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
5096
5097  if (!Entry) {
5098    std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5099    llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5100    Entry =
5101      new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5102                               llvm::GlobalValue::InternalLinkage,
5103                               ClassGV,
5104                               "\01L_OBJC_CLASSLIST_REFERENCES_$_",
5105                               &CGM.getModule());
5106    Entry->setAlignment(
5107                     CGM.getTargetData().getPrefTypeAlignment(
5108                                                  ObjCTypes.ClassnfABIPtrTy));
5109    Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
5110    UsedGlobals.push_back(Entry);
5111  }
5112
5113  return Builder.CreateLoad(Entry, false, "tmp");
5114}
5115
5116llvm::Value *
5117CGObjCNonFragileABIMac::EmitSuperClassRef(CGBuilderTy &Builder,
5118                                          const ObjCInterfaceDecl *ID) {
5119  llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
5120
5121  if (!Entry) {
5122    std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5123    llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
5124    Entry =
5125      new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5126                               llvm::GlobalValue::InternalLinkage,
5127                               ClassGV,
5128                               "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5129                               &CGM.getModule());
5130    Entry->setAlignment(
5131                     CGM.getTargetData().getPrefTypeAlignment(
5132                                                  ObjCTypes.ClassnfABIPtrTy));
5133    Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
5134    UsedGlobals.push_back(Entry);
5135  }
5136
5137  return Builder.CreateLoad(Entry, false, "tmp");
5138}
5139
5140/// EmitMetaClassRef - Return a Value * of the address of _class_t
5141/// meta-data
5142///
5143llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CGBuilderTy &Builder,
5144                                                  const ObjCInterfaceDecl *ID) {
5145  llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
5146  if (Entry)
5147    return Builder.CreateLoad(Entry, false, "tmp");
5148
5149  std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
5150  llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
5151  Entry =
5152    new llvm::GlobalVariable(ObjCTypes.ClassnfABIPtrTy, false,
5153                             llvm::GlobalValue::InternalLinkage,
5154                             MetaClassGV,
5155                             "\01L_OBJC_CLASSLIST_SUP_REFS_$_",
5156                             &CGM.getModule());
5157  Entry->setAlignment(
5158                      CGM.getTargetData().getPrefTypeAlignment(
5159                                                  ObjCTypes.ClassnfABIPtrTy));
5160
5161  Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
5162  UsedGlobals.push_back(Entry);
5163
5164  return Builder.CreateLoad(Entry, false, "tmp");
5165}
5166
5167/// GetClass - Return a reference to the class for the given interface
5168/// decl.
5169llvm::Value *CGObjCNonFragileABIMac::GetClass(CGBuilderTy &Builder,
5170                                              const ObjCInterfaceDecl *ID) {
5171  return EmitClassRef(Builder, ID);
5172}
5173
5174/// Generates a message send where the super is the receiver.  This is
5175/// a message send to self with special delivery semantics indicating
5176/// which class's method should be called.
5177CodeGen::RValue
5178CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
5179                                    QualType ResultType,
5180                                    Selector Sel,
5181                                    const ObjCInterfaceDecl *Class,
5182                                    bool isCategoryImpl,
5183                                    llvm::Value *Receiver,
5184                                    bool IsClassMessage,
5185                                    const CodeGen::CallArgList &CallArgs) {
5186  // ...
5187  // Create and init a super structure; this is a (receiver, class)
5188  // pair we will pass to objc_msgSendSuper.
5189  llvm::Value *ObjCSuper =
5190    CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
5191
5192  llvm::Value *ReceiverAsObject =
5193    CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
5194  CGF.Builder.CreateStore(ReceiverAsObject,
5195                          CGF.Builder.CreateStructGEP(ObjCSuper, 0));
5196
5197  // If this is a class message the metaclass is passed as the target.
5198  llvm::Value *Target;
5199  if (IsClassMessage) {
5200    if (isCategoryImpl) {
5201      // Message sent to "super' in a class method defined in
5202      // a category implementation.
5203      Target = EmitClassRef(CGF.Builder, Class);
5204      Target = CGF.Builder.CreateStructGEP(Target, 0);
5205      Target = CGF.Builder.CreateLoad(Target);
5206    }
5207    else
5208      Target = EmitMetaClassRef(CGF.Builder, Class);
5209  }
5210  else
5211    Target = EmitSuperClassRef(CGF.Builder, Class);
5212
5213  // FIXME: We shouldn't need to do this cast, rectify the ASTContext
5214  // and ObjCTypes types.
5215  const llvm::Type *ClassTy =
5216    CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
5217  Target = CGF.Builder.CreateBitCast(Target, ClassTy);
5218  CGF.Builder.CreateStore(Target,
5219                          CGF.Builder.CreateStructGEP(ObjCSuper, 1));
5220
5221  return EmitMessageSend(CGF, ResultType, Sel,
5222                         ObjCSuper, ObjCTypes.SuperPtrCTy,
5223                         true, CallArgs);
5224}
5225
5226llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CGBuilderTy &Builder,
5227                                                  Selector Sel) {
5228  llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
5229
5230  if (!Entry) {
5231    llvm::Constant *Casted =
5232    llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
5233                                   ObjCTypes.SelectorPtrTy);
5234    Entry =
5235    new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
5236                             llvm::GlobalValue::InternalLinkage,
5237                             Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
5238                             &CGM.getModule());
5239    Entry->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
5240    UsedGlobals.push_back(Entry);
5241  }
5242
5243  return Builder.CreateLoad(Entry, false, "tmp");
5244}
5245/// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
5246/// objc_assign_ivar (id src, id *dst)
5247///
5248void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
5249                                   llvm::Value *src, llvm::Value *dst)
5250{
5251  const llvm::Type * SrcTy = src->getType();
5252  if (!isa<llvm::PointerType>(SrcTy)) {
5253    unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5254    assert(Size <= 8 && "does not support size > 8");
5255    src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5256           : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
5257    src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5258  }
5259  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5260  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5261  CGF.Builder.CreateCall2(ObjCTypes.getGcAssignIvarFn(),
5262                          src, dst, "assignivar");
5263  return;
5264}
5265
5266/// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
5267/// objc_assign_strongCast (id src, id *dst)
5268///
5269void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
5270                                         CodeGen::CodeGenFunction &CGF,
5271                                         llvm::Value *src, llvm::Value *dst)
5272{
5273  const llvm::Type * SrcTy = src->getType();
5274  if (!isa<llvm::PointerType>(SrcTy)) {
5275    unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5276    assert(Size <= 8 && "does not support size > 8");
5277    src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5278                     : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
5279    src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5280  }
5281  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5282  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5283  CGF.Builder.CreateCall2(ObjCTypes.getGcAssignStrongCastFn(),
5284                          src, dst, "weakassign");
5285  return;
5286}
5287
5288/// EmitObjCWeakRead - Code gen for loading value of a __weak
5289/// object: objc_read_weak (id *src)
5290///
5291llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
5292                                          CodeGen::CodeGenFunction &CGF,
5293                                          llvm::Value *AddrWeakObj)
5294{
5295  const llvm::Type* DestTy =
5296      cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
5297  AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
5298  llvm::Value *read_weak = CGF.Builder.CreateCall(ObjCTypes.getGcReadWeakFn(),
5299                                                  AddrWeakObj, "weakread");
5300  read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
5301  return read_weak;
5302}
5303
5304/// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
5305/// objc_assign_weak (id src, id *dst)
5306///
5307void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
5308                                   llvm::Value *src, llvm::Value *dst)
5309{
5310  const llvm::Type * SrcTy = src->getType();
5311  if (!isa<llvm::PointerType>(SrcTy)) {
5312    unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5313    assert(Size <= 8 && "does not support size > 8");
5314    src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5315           : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
5316    src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5317  }
5318  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5319  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5320  CGF.Builder.CreateCall2(ObjCTypes.getGcAssignWeakFn(),
5321                          src, dst, "weakassign");
5322  return;
5323}
5324
5325/// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
5326/// objc_assign_global (id src, id *dst)
5327///
5328void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
5329                                     llvm::Value *src, llvm::Value *dst)
5330{
5331  const llvm::Type * SrcTy = src->getType();
5332  if (!isa<llvm::PointerType>(SrcTy)) {
5333    unsigned Size = CGM.getTargetData().getTypePaddedSize(SrcTy);
5334    assert(Size <= 8 && "does not support size > 8");
5335    src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
5336           : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
5337    src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
5338  }
5339  src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
5340  dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
5341  CGF.Builder.CreateCall2(ObjCTypes.getGcAssignGlobalFn(),
5342                          src, dst, "globalassign");
5343  return;
5344}
5345
5346void
5347CGObjCNonFragileABIMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
5348                                                  const Stmt &S) {
5349  bool isTry = isa<ObjCAtTryStmt>(S);
5350  llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
5351  llvm::BasicBlock *PrevLandingPad = CGF.getInvokeDest();
5352  llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
5353  llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
5354  llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
5355  llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
5356
5357  // For @synchronized, call objc_sync_enter(sync.expr). The
5358  // evaluation of the expression must occur before we enter the
5359  // @synchronized. We can safely avoid a temp here because jumps into
5360  // @synchronized are illegal & this will dominate uses.
5361  llvm::Value *SyncArg = 0;
5362  if (!isTry) {
5363    SyncArg =
5364      CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
5365    SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
5366    CGF.Builder.CreateCall(ObjCTypes.getSyncEnterFn(), SyncArg);
5367  }
5368
5369  // Push an EH context entry, used for handling rethrows and jumps
5370  // through finally.
5371  CGF.PushCleanupBlock(FinallyBlock);
5372
5373  CGF.setInvokeDest(TryHandler);
5374
5375  CGF.EmitBlock(TryBlock);
5376  CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
5377                     : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
5378  CGF.EmitBranchThroughCleanup(FinallyEnd);
5379
5380  // Emit the exception handler.
5381
5382  CGF.EmitBlock(TryHandler);
5383
5384  llvm::Value *llvm_eh_exception =
5385    CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_exception);
5386  llvm::Value *llvm_eh_selector_i64 =
5387    CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_selector_i64);
5388  llvm::Value *llvm_eh_typeid_for_i64 =
5389    CGF.CGM.getIntrinsic(llvm::Intrinsic::eh_typeid_for_i64);
5390  llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5391  llvm::Value *RethrowPtr = CGF.CreateTempAlloca(Exc->getType(), "_rethrow");
5392
5393  llvm::SmallVector<llvm::Value*, 8> SelectorArgs;
5394  SelectorArgs.push_back(Exc);
5395  SelectorArgs.push_back(ObjCTypes.getEHPersonalityPtr());
5396
5397  // Construct the lists of (type, catch body) to handle.
5398  llvm::SmallVector<std::pair<const ParmVarDecl*, const Stmt*>, 8> Handlers;
5399  bool HasCatchAll = false;
5400  if (isTry) {
5401    if (const ObjCAtCatchStmt* CatchStmt =
5402        cast<ObjCAtTryStmt>(S).getCatchStmts())  {
5403      for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
5404        const ParmVarDecl *CatchDecl = CatchStmt->getCatchParamDecl();
5405        Handlers.push_back(std::make_pair(CatchDecl, CatchStmt->getCatchBody()));
5406
5407        // catch(...) always matches.
5408        if (!CatchDecl) {
5409          // Use i8* null here to signal this is a catch all, not a cleanup.
5410          llvm::Value *Null = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
5411          SelectorArgs.push_back(Null);
5412          HasCatchAll = true;
5413          break;
5414        }
5415
5416        if (CGF.getContext().isObjCIdType(CatchDecl->getType()) ||
5417            CatchDecl->getType()->isObjCQualifiedIdType()) {
5418          llvm::Value *IDEHType =
5419            CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
5420          if (!IDEHType)
5421            IDEHType =
5422              new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5423                                       llvm::GlobalValue::ExternalLinkage,
5424                                       0, "OBJC_EHTYPE_id", &CGM.getModule());
5425          SelectorArgs.push_back(IDEHType);
5426          HasCatchAll = true;
5427          break;
5428        }
5429
5430        // All other types should be Objective-C interface pointer types.
5431        const PointerType *PT = CatchDecl->getType()->getAsPointerType();
5432        assert(PT && "Invalid @catch type.");
5433        const ObjCInterfaceType *IT =
5434          PT->getPointeeType()->getAsObjCInterfaceType();
5435        assert(IT && "Invalid @catch type.");
5436        llvm::Value *EHType = GetInterfaceEHType(IT->getDecl(), false);
5437        SelectorArgs.push_back(EHType);
5438      }
5439    }
5440  }
5441
5442  // We use a cleanup unless there was already a catch all.
5443  if (!HasCatchAll) {
5444    SelectorArgs.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
5445    Handlers.push_back(std::make_pair((const ParmVarDecl*) 0, (const Stmt*) 0));
5446  }
5447
5448  llvm::Value *Selector =
5449    CGF.Builder.CreateCall(llvm_eh_selector_i64,
5450                           SelectorArgs.begin(), SelectorArgs.end(),
5451                           "selector");
5452  for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
5453    const ParmVarDecl *CatchParam = Handlers[i].first;
5454    const Stmt *CatchBody = Handlers[i].second;
5455
5456    llvm::BasicBlock *Next = 0;
5457
5458    // The last handler always matches.
5459    if (i + 1 != e) {
5460      assert(CatchParam && "Only last handler can be a catch all.");
5461
5462      llvm::BasicBlock *Match = CGF.createBasicBlock("match");
5463      Next = CGF.createBasicBlock("catch.next");
5464      llvm::Value *Id =
5465        CGF.Builder.CreateCall(llvm_eh_typeid_for_i64,
5466                               CGF.Builder.CreateBitCast(SelectorArgs[i+2],
5467                                                         ObjCTypes.Int8PtrTy));
5468      CGF.Builder.CreateCondBr(CGF.Builder.CreateICmpEQ(Selector, Id),
5469                               Match, Next);
5470
5471      CGF.EmitBlock(Match);
5472    }
5473
5474    if (CatchBody) {
5475      llvm::BasicBlock *MatchEnd = CGF.createBasicBlock("match.end");
5476      llvm::BasicBlock *MatchHandler = CGF.createBasicBlock("match.handler");
5477
5478      // Cleanups must call objc_end_catch.
5479      //
5480      // FIXME: It seems incorrect for objc_begin_catch to be inside
5481      // this context, but this matches gcc.
5482      CGF.PushCleanupBlock(MatchEnd);
5483      CGF.setInvokeDest(MatchHandler);
5484
5485      llvm::Value *ExcObject =
5486        CGF.Builder.CreateCall(ObjCTypes.getObjCBeginCatchFn(), Exc);
5487
5488      // Bind the catch parameter if it exists.
5489      if (CatchParam) {
5490        ExcObject =
5491          CGF.Builder.CreateBitCast(ExcObject,
5492                                    CGF.ConvertType(CatchParam->getType()));
5493        // CatchParam is a ParmVarDecl because of the grammar
5494        // construction used to handle this, but for codegen purposes
5495        // we treat this as a local decl.
5496        CGF.EmitLocalBlockVarDecl(*CatchParam);
5497        CGF.Builder.CreateStore(ExcObject, CGF.GetAddrOfLocalVar(CatchParam));
5498      }
5499
5500      CGF.ObjCEHValueStack.push_back(ExcObject);
5501      CGF.EmitStmt(CatchBody);
5502      CGF.ObjCEHValueStack.pop_back();
5503
5504      CGF.EmitBranchThroughCleanup(FinallyEnd);
5505
5506      CGF.EmitBlock(MatchHandler);
5507
5508      llvm::Value *Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5509      // We are required to emit this call to satisfy LLVM, even
5510      // though we don't use the result.
5511      llvm::SmallVector<llvm::Value*, 8> Args;
5512      Args.push_back(Exc);
5513      Args.push_back(ObjCTypes.getEHPersonalityPtr());
5514      Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5515                                            0));
5516      CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5517      CGF.Builder.CreateStore(Exc, RethrowPtr);
5518      CGF.EmitBranchThroughCleanup(FinallyRethrow);
5519
5520      CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5521
5522      CGF.EmitBlock(MatchEnd);
5523
5524      // Unfortunately, we also have to generate another EH frame here
5525      // in case this throws.
5526      llvm::BasicBlock *MatchEndHandler =
5527        CGF.createBasicBlock("match.end.handler");
5528      llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5529      CGF.Builder.CreateInvoke(ObjCTypes.getObjCEndCatchFn(),
5530                               Cont, MatchEndHandler,
5531                               Args.begin(), Args.begin());
5532
5533      CGF.EmitBlock(Cont);
5534      if (Info.SwitchBlock)
5535        CGF.EmitBlock(Info.SwitchBlock);
5536      if (Info.EndBlock)
5537        CGF.EmitBlock(Info.EndBlock);
5538
5539      CGF.EmitBlock(MatchEndHandler);
5540      Exc = CGF.Builder.CreateCall(llvm_eh_exception, "exc");
5541      // We are required to emit this call to satisfy LLVM, even
5542      // though we don't use the result.
5543      Args.clear();
5544      Args.push_back(Exc);
5545      Args.push_back(ObjCTypes.getEHPersonalityPtr());
5546      Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty,
5547                                            0));
5548      CGF.Builder.CreateCall(llvm_eh_selector_i64, Args.begin(), Args.end());
5549      CGF.Builder.CreateStore(Exc, RethrowPtr);
5550      CGF.EmitBranchThroughCleanup(FinallyRethrow);
5551
5552      if (Next)
5553        CGF.EmitBlock(Next);
5554    } else {
5555      assert(!Next && "catchup should be last handler.");
5556
5557      CGF.Builder.CreateStore(Exc, RethrowPtr);
5558      CGF.EmitBranchThroughCleanup(FinallyRethrow);
5559    }
5560  }
5561
5562  // Pop the cleanup entry, the @finally is outside this cleanup
5563  // scope.
5564  CodeGenFunction::CleanupBlockInfo Info = CGF.PopCleanupBlock();
5565  CGF.setInvokeDest(PrevLandingPad);
5566
5567  CGF.EmitBlock(FinallyBlock);
5568
5569  if (isTry) {
5570    if (const ObjCAtFinallyStmt* FinallyStmt =
5571        cast<ObjCAtTryStmt>(S).getFinallyStmt())
5572      CGF.EmitStmt(FinallyStmt->getFinallyBody());
5573  } else {
5574    // Emit 'objc_sync_exit(expr)' as finally's sole statement for
5575    // @synchronized.
5576    CGF.Builder.CreateCall(ObjCTypes.getSyncExitFn(), SyncArg);
5577  }
5578
5579  if (Info.SwitchBlock)
5580    CGF.EmitBlock(Info.SwitchBlock);
5581  if (Info.EndBlock)
5582    CGF.EmitBlock(Info.EndBlock);
5583
5584  // Branch around the rethrow code.
5585  CGF.EmitBranch(FinallyEnd);
5586
5587  CGF.EmitBlock(FinallyRethrow);
5588  CGF.Builder.CreateCall(ObjCTypes.getUnwindResumeOrRethrowFn(),
5589                         CGF.Builder.CreateLoad(RethrowPtr));
5590  CGF.Builder.CreateUnreachable();
5591
5592  CGF.EmitBlock(FinallyEnd);
5593}
5594
5595/// EmitThrowStmt - Generate code for a throw statement.
5596void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
5597                                           const ObjCAtThrowStmt &S) {
5598  llvm::Value *Exception;
5599  if (const Expr *ThrowExpr = S.getThrowExpr()) {
5600    Exception = CGF.EmitScalarExpr(ThrowExpr);
5601  } else {
5602    assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
5603           "Unexpected rethrow outside @catch block.");
5604    Exception = CGF.ObjCEHValueStack.back();
5605  }
5606
5607  llvm::Value *ExceptionAsObject =
5608    CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
5609  llvm::BasicBlock *InvokeDest = CGF.getInvokeDest();
5610  if (InvokeDest) {
5611    llvm::BasicBlock *Cont = CGF.createBasicBlock("invoke.cont");
5612    CGF.Builder.CreateInvoke(ObjCTypes.getExceptionThrowFn(),
5613                             Cont, InvokeDest,
5614                             &ExceptionAsObject, &ExceptionAsObject + 1);
5615    CGF.EmitBlock(Cont);
5616  } else
5617    CGF.Builder.CreateCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject);
5618  CGF.Builder.CreateUnreachable();
5619
5620  // Clear the insertion point to indicate we are in unreachable code.
5621  CGF.Builder.ClearInsertionPoint();
5622}
5623
5624llvm::Value *
5625CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
5626                                           bool ForDefinition) {
5627  llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
5628
5629  // If we don't need a definition, return the entry if found or check
5630  // if we use an external reference.
5631  if (!ForDefinition) {
5632    if (Entry)
5633      return Entry;
5634
5635    // If this type (or a super class) has the __objc_exception__
5636    // attribute, emit an external reference.
5637    if (hasObjCExceptionAttribute(ID))
5638      return Entry =
5639        new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5640                                 llvm::GlobalValue::ExternalLinkage,
5641                                 0,
5642                                 (std::string("OBJC_EHTYPE_$_") +
5643                                  ID->getIdentifier()->getName()),
5644                                 &CGM.getModule());
5645  }
5646
5647  // Otherwise we need to either make a new entry or fill in the
5648  // initializer.
5649  assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
5650  std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
5651  std::string VTableName = "objc_ehtype_vtable";
5652  llvm::GlobalVariable *VTableGV =
5653    CGM.getModule().getGlobalVariable(VTableName);
5654  if (!VTableGV)
5655    VTableGV = new llvm::GlobalVariable(ObjCTypes.Int8PtrTy, false,
5656                                        llvm::GlobalValue::ExternalLinkage,
5657                                        0, VTableName, &CGM.getModule());
5658
5659  llvm::Value *VTableIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 2);
5660
5661  std::vector<llvm::Constant*> Values(3);
5662  Values[0] = llvm::ConstantExpr::getGetElementPtr(VTableGV, &VTableIdx, 1);
5663  Values[1] = GetClassName(ID->getIdentifier());
5664  Values[2] = GetClassGlobal(ClassName);
5665  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
5666
5667  if (Entry) {
5668    Entry->setInitializer(Init);
5669  } else {
5670    Entry = new llvm::GlobalVariable(ObjCTypes.EHTypeTy, false,
5671                                     llvm::GlobalValue::WeakAnyLinkage,
5672                                     Init,
5673                                     (std::string("OBJC_EHTYPE_$_") +
5674                                      ID->getIdentifier()->getName()),
5675                                     &CGM.getModule());
5676  }
5677
5678  if (CGM.getLangOptions().getVisibilityMode() == LangOptions::Hidden)
5679    Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
5680  Entry->setAlignment(8);
5681
5682  if (ForDefinition) {
5683    Entry->setSection("__DATA,__objc_const");
5684    Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
5685  } else {
5686    Entry->setSection("__DATA,__datacoal_nt,coalesced");
5687  }
5688
5689  return Entry;
5690}
5691
5692/* *** */
5693
5694CodeGen::CGObjCRuntime *
5695CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
5696  return new CGObjCMac(CGM);
5697}
5698
5699CodeGen::CGObjCRuntime *
5700CodeGen::CreateMacNonFragileABIObjCRuntime(CodeGen::CodeGenModule &CGM) {
5701  return new CGObjCNonFragileABIMac(CGM);
5702}
5703