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