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