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