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