Home | History | Annotate | Download | only in CodeGen
      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 targeting the Apple runtime.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "CGObjCRuntime.h"
     15 #include "CGBlocks.h"
     16 #include "CGCleanup.h"
     17 #include "CGRecordLayout.h"
     18 #include "CodeGenFunction.h"
     19 #include "CodeGenModule.h"
     20 #include "clang/AST/ASTContext.h"
     21 #include "clang/AST/Decl.h"
     22 #include "clang/AST/DeclObjC.h"
     23 #include "clang/AST/RecordLayout.h"
     24 #include "clang/AST/StmtObjC.h"
     25 #include "clang/Basic/LangOptions.h"
     26 #include "clang/Frontend/CodeGenOptions.h"
     27 #include "llvm/ADT/DenseSet.h"
     28 #include "llvm/ADT/SetVector.h"
     29 #include "llvm/ADT/SmallPtrSet.h"
     30 #include "llvm/ADT/SmallString.h"
     31 #include "llvm/IR/DataLayout.h"
     32 #include "llvm/IR/InlineAsm.h"
     33 #include "llvm/IR/IntrinsicInst.h"
     34 #include "llvm/IR/LLVMContext.h"
     35 #include "llvm/IR/Module.h"
     36 #include "llvm/Support/CallSite.h"
     37 #include "llvm/Support/raw_ostream.h"
     38 #include <cstdio>
     39 
     40 using namespace clang;
     41 using namespace CodeGen;
     42 
     43 namespace {
     44 
     45 // FIXME: We should find a nicer way to make the labels for metadata, string
     46 // concatenation is lame.
     47 
     48 class ObjCCommonTypesHelper {
     49 protected:
     50   llvm::LLVMContext &VMContext;
     51 
     52 private:
     53   // The types of these functions don't really matter because we
     54   // should always bitcast before calling them.
     55 
     56   /// id objc_msgSend (id, SEL, ...)
     57   ///
     58   /// The default messenger, used for sends whose ABI is unchanged from
     59   /// the all-integer/pointer case.
     60   llvm::Constant *getMessageSendFn() const {
     61     // Add the non-lazy-bind attribute, since objc_msgSend is likely to
     62     // be called a lot.
     63     llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
     64     return
     65       CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
     66                                                         params, true),
     67                                 "objc_msgSend",
     68                                 llvm::AttributeSet::get(CGM.getLLVMContext(),
     69                                               llvm::AttributeSet::FunctionIndex,
     70                                                  llvm::Attribute::NonLazyBind));
     71   }
     72 
     73   /// void objc_msgSend_stret (id, SEL, ...)
     74   ///
     75   /// The messenger used when the return value is an aggregate returned
     76   /// by indirect reference in the first argument, and therefore the
     77   /// self and selector parameters are shifted over by one.
     78   llvm::Constant *getMessageSendStretFn() const {
     79     llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
     80     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy,
     81                                                              params, true),
     82                                      "objc_msgSend_stret");
     83 
     84   }
     85 
     86   /// [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
     87   ///
     88   /// The messenger used when the return value is returned on the x87
     89   /// floating-point stack; without a special entrypoint, the nil case
     90   /// would be unbalanced.
     91   llvm::Constant *getMessageSendFpretFn() const {
     92     llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
     93     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.DoubleTy,
     94                                                              params, true),
     95                                      "objc_msgSend_fpret");
     96 
     97   }
     98 
     99   /// _Complex long double objc_msgSend_fp2ret(id self, SEL op, ...)
    100   ///
    101   /// The messenger used when the return value is returned in two values on the
    102   /// x87 floating point stack; without a special entrypoint, the nil case
    103   /// would be unbalanced. Only used on 64-bit X86.
    104   llvm::Constant *getMessageSendFp2retFn() const {
    105     llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
    106     llvm::Type *longDoubleType = llvm::Type::getX86_FP80Ty(VMContext);
    107     llvm::Type *resultType =
    108       llvm::StructType::get(longDoubleType, longDoubleType, NULL);
    109 
    110     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(resultType,
    111                                                              params, true),
    112                                      "objc_msgSend_fp2ret");
    113   }
    114 
    115   /// id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
    116   ///
    117   /// The messenger used for super calls, which have different dispatch
    118   /// semantics.  The class passed is the superclass of the current
    119   /// class.
    120   llvm::Constant *getMessageSendSuperFn() const {
    121     llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy };
    122     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
    123                                                              params, true),
    124                                      "objc_msgSendSuper");
    125   }
    126 
    127   /// id objc_msgSendSuper2(struct objc_super *super, SEL op, ...)
    128   ///
    129   /// A slightly different messenger used for super calls.  The class
    130   /// passed is the current class.
    131   llvm::Constant *getMessageSendSuperFn2() const {
    132     llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy };
    133     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
    134                                                              params, true),
    135                                      "objc_msgSendSuper2");
    136   }
    137 
    138   /// void objc_msgSendSuper_stret(void *stretAddr, struct objc_super *super,
    139   ///                              SEL op, ...)
    140   ///
    141   /// The messenger used for super calls which return an aggregate indirectly.
    142   llvm::Constant *getMessageSendSuperStretFn() const {
    143     llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy };
    144     return CGM.CreateRuntimeFunction(
    145       llvm::FunctionType::get(CGM.VoidTy, params, true),
    146       "objc_msgSendSuper_stret");
    147   }
    148 
    149   /// void objc_msgSendSuper2_stret(void * stretAddr, struct objc_super *super,
    150   ///                               SEL op, ...)
    151   ///
    152   /// objc_msgSendSuper_stret with the super2 semantics.
    153   llvm::Constant *getMessageSendSuperStretFn2() const {
    154     llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy };
    155     return CGM.CreateRuntimeFunction(
    156       llvm::FunctionType::get(CGM.VoidTy, params, true),
    157       "objc_msgSendSuper2_stret");
    158   }
    159 
    160   llvm::Constant *getMessageSendSuperFpretFn() const {
    161     // There is no objc_msgSendSuper_fpret? How can that work?
    162     return getMessageSendSuperFn();
    163   }
    164 
    165   llvm::Constant *getMessageSendSuperFpretFn2() const {
    166     // There is no objc_msgSendSuper_fpret? How can that work?
    167     return getMessageSendSuperFn2();
    168   }
    169 
    170 protected:
    171   CodeGen::CodeGenModule &CGM;
    172 
    173 public:
    174   llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
    175   llvm::Type *Int8PtrTy, *Int8PtrPtrTy;
    176 
    177   /// ObjectPtrTy - LLVM type for object handles (typeof(id))
    178   llvm::Type *ObjectPtrTy;
    179 
    180   /// PtrObjectPtrTy - LLVM type for id *
    181   llvm::Type *PtrObjectPtrTy;
    182 
    183   /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
    184   llvm::Type *SelectorPtrTy;
    185 
    186 private:
    187   /// ProtocolPtrTy - LLVM type for external protocol handles
    188   /// (typeof(Protocol))
    189   llvm::Type *ExternalProtocolPtrTy;
    190 
    191 public:
    192   llvm::Type *getExternalProtocolPtrTy() {
    193     if (!ExternalProtocolPtrTy) {
    194       // FIXME: It would be nice to unify this with the opaque type, so that the
    195       // IR comes out a bit cleaner.
    196       CodeGen::CodeGenTypes &Types = CGM.getTypes();
    197       ASTContext &Ctx = CGM.getContext();
    198       llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
    199       ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
    200     }
    201 
    202     return ExternalProtocolPtrTy;
    203   }
    204 
    205   // SuperCTy - clang type for struct objc_super.
    206   QualType SuperCTy;
    207   // SuperPtrCTy - clang type for struct objc_super *.
    208   QualType SuperPtrCTy;
    209 
    210   /// SuperTy - LLVM type for struct objc_super.
    211   llvm::StructType *SuperTy;
    212   /// SuperPtrTy - LLVM type for struct objc_super *.
    213   llvm::Type *SuperPtrTy;
    214 
    215   /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
    216   /// in GCC parlance).
    217   llvm::StructType *PropertyTy;
    218 
    219   /// PropertyListTy - LLVM type for struct objc_property_list
    220   /// (_prop_list_t in GCC parlance).
    221   llvm::StructType *PropertyListTy;
    222   /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
    223   llvm::Type *PropertyListPtrTy;
    224 
    225   // MethodTy - LLVM type for struct objc_method.
    226   llvm::StructType *MethodTy;
    227 
    228   /// CacheTy - LLVM type for struct objc_cache.
    229   llvm::Type *CacheTy;
    230   /// CachePtrTy - LLVM type for struct objc_cache *.
    231   llvm::Type *CachePtrTy;
    232 
    233   llvm::Constant *getGetPropertyFn() {
    234     CodeGen::CodeGenTypes &Types = CGM.getTypes();
    235     ASTContext &Ctx = CGM.getContext();
    236     // id objc_getProperty (id, SEL, ptrdiff_t, bool)
    237     SmallVector<CanQualType,4> Params;
    238     CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
    239     CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
    240     Params.push_back(IdType);
    241     Params.push_back(SelType);
    242     Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified());
    243     Params.push_back(Ctx.BoolTy);
    244     llvm::FunctionType *FTy =
    245       Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(IdType, Params,
    246                                                     FunctionType::ExtInfo(),
    247                                                           RequiredArgs::All));
    248     return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
    249   }
    250 
    251   llvm::Constant *getSetPropertyFn() {
    252     CodeGen::CodeGenTypes &Types = CGM.getTypes();
    253     ASTContext &Ctx = CGM.getContext();
    254     // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
    255     SmallVector<CanQualType,6> Params;
    256     CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
    257     CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
    258     Params.push_back(IdType);
    259     Params.push_back(SelType);
    260     Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified());
    261     Params.push_back(IdType);
    262     Params.push_back(Ctx.BoolTy);
    263     Params.push_back(Ctx.BoolTy);
    264     llvm::FunctionType *FTy =
    265       Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(Ctx.VoidTy, Params,
    266                                                      FunctionType::ExtInfo(),
    267                                                           RequiredArgs::All));
    268     return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
    269   }
    270 
    271   llvm::Constant *getOptimizedSetPropertyFn(bool atomic, bool copy) {
    272     CodeGen::CodeGenTypes &Types = CGM.getTypes();
    273     ASTContext &Ctx = CGM.getContext();
    274     // void objc_setProperty_atomic(id self, SEL _cmd,
    275     //                              id newValue, ptrdiff_t offset);
    276     // void objc_setProperty_nonatomic(id self, SEL _cmd,
    277     //                                 id newValue, ptrdiff_t offset);
    278     // void objc_setProperty_atomic_copy(id self, SEL _cmd,
    279     //                                   id newValue, ptrdiff_t offset);
    280     // void objc_setProperty_nonatomic_copy(id self, SEL _cmd,
    281     //                                      id newValue, ptrdiff_t offset);
    282 
    283     SmallVector<CanQualType,4> Params;
    284     CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
    285     CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
    286     Params.push_back(IdType);
    287     Params.push_back(SelType);
    288     Params.push_back(IdType);
    289     Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified());
    290     llvm::FunctionType *FTy =
    291     Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(Ctx.VoidTy, Params,
    292                                                         FunctionType::ExtInfo(),
    293                                                         RequiredArgs::All));
    294     const char *name;
    295     if (atomic && copy)
    296       name = "objc_setProperty_atomic_copy";
    297     else if (atomic && !copy)
    298       name = "objc_setProperty_atomic";
    299     else if (!atomic && copy)
    300       name = "objc_setProperty_nonatomic_copy";
    301     else
    302       name = "objc_setProperty_nonatomic";
    303 
    304     return CGM.CreateRuntimeFunction(FTy, name);
    305   }
    306 
    307   llvm::Constant *getCopyStructFn() {
    308     CodeGen::CodeGenTypes &Types = CGM.getTypes();
    309     ASTContext &Ctx = CGM.getContext();
    310     // void objc_copyStruct (void *, const void *, size_t, bool, bool)
    311     SmallVector<CanQualType,5> Params;
    312     Params.push_back(Ctx.VoidPtrTy);
    313     Params.push_back(Ctx.VoidPtrTy);
    314     Params.push_back(Ctx.LongTy);
    315     Params.push_back(Ctx.BoolTy);
    316     Params.push_back(Ctx.BoolTy);
    317     llvm::FunctionType *FTy =
    318       Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(Ctx.VoidTy, Params,
    319                                                      FunctionType::ExtInfo(),
    320                                                           RequiredArgs::All));
    321     return CGM.CreateRuntimeFunction(FTy, "objc_copyStruct");
    322   }
    323 
    324   /// This routine declares and returns address of:
    325   /// void objc_copyCppObjectAtomic(
    326   ///         void *dest, const void *src,
    327   ///         void (*copyHelper) (void *dest, const void *source));
    328   llvm::Constant *getCppAtomicObjectFunction() {
    329     CodeGen::CodeGenTypes &Types = CGM.getTypes();
    330     ASTContext &Ctx = CGM.getContext();
    331     /// void objc_copyCppObjectAtomic(void *dest, const void *src, void *helper);
    332     SmallVector<CanQualType,3> Params;
    333     Params.push_back(Ctx.VoidPtrTy);
    334     Params.push_back(Ctx.VoidPtrTy);
    335     Params.push_back(Ctx.VoidPtrTy);
    336     llvm::FunctionType *FTy =
    337       Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(Ctx.VoidTy, Params,
    338                                                      FunctionType::ExtInfo(),
    339                                                           RequiredArgs::All));
    340     return CGM.CreateRuntimeFunction(FTy, "objc_copyCppObjectAtomic");
    341   }
    342 
    343   llvm::Constant *getEnumerationMutationFn() {
    344     CodeGen::CodeGenTypes &Types = CGM.getTypes();
    345     ASTContext &Ctx = CGM.getContext();
    346     // void objc_enumerationMutation (id)
    347     SmallVector<CanQualType,1> Params;
    348     Params.push_back(Ctx.getCanonicalParamType(Ctx.getObjCIdType()));
    349     llvm::FunctionType *FTy =
    350       Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(Ctx.VoidTy, Params,
    351                                                       FunctionType::ExtInfo(),
    352                                                       RequiredArgs::All));
    353     return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
    354   }
    355 
    356   /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
    357   llvm::Constant *getGcReadWeakFn() {
    358     // id objc_read_weak (id *)
    359     llvm::Type *args[] = { ObjectPtrTy->getPointerTo() };
    360     llvm::FunctionType *FTy =
    361       llvm::FunctionType::get(ObjectPtrTy, args, false);
    362     return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
    363   }
    364 
    365   /// GcAssignWeakFn -- LLVM objc_assign_weak function.
    366   llvm::Constant *getGcAssignWeakFn() {
    367     // id objc_assign_weak (id, id *)
    368     llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
    369     llvm::FunctionType *FTy =
    370       llvm::FunctionType::get(ObjectPtrTy, args, false);
    371     return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
    372   }
    373 
    374   /// GcAssignGlobalFn -- LLVM objc_assign_global function.
    375   llvm::Constant *getGcAssignGlobalFn() {
    376     // id objc_assign_global(id, id *)
    377     llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
    378     llvm::FunctionType *FTy =
    379       llvm::FunctionType::get(ObjectPtrTy, args, false);
    380     return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
    381   }
    382 
    383   /// GcAssignThreadLocalFn -- LLVM objc_assign_threadlocal function.
    384   llvm::Constant *getGcAssignThreadLocalFn() {
    385     // id objc_assign_threadlocal(id src, id * dest)
    386     llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
    387     llvm::FunctionType *FTy =
    388       llvm::FunctionType::get(ObjectPtrTy, args, false);
    389     return CGM.CreateRuntimeFunction(FTy, "objc_assign_threadlocal");
    390   }
    391 
    392   /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
    393   llvm::Constant *getGcAssignIvarFn() {
    394     // id objc_assign_ivar(id, id *, ptrdiff_t)
    395     llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo(),
    396                            CGM.PtrDiffTy };
    397     llvm::FunctionType *FTy =
    398       llvm::FunctionType::get(ObjectPtrTy, args, false);
    399     return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
    400   }
    401 
    402   /// GcMemmoveCollectableFn -- LLVM objc_memmove_collectable function.
    403   llvm::Constant *GcMemmoveCollectableFn() {
    404     // void *objc_memmove_collectable(void *dst, const void *src, size_t size)
    405     llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, LongTy };
    406     llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, args, false);
    407     return CGM.CreateRuntimeFunction(FTy, "objc_memmove_collectable");
    408   }
    409 
    410   /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
    411   llvm::Constant *getGcAssignStrongCastFn() {
    412     // id objc_assign_strongCast(id, id *)
    413     llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
    414     llvm::FunctionType *FTy =
    415       llvm::FunctionType::get(ObjectPtrTy, args, false);
    416     return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
    417   }
    418 
    419   /// ExceptionThrowFn - LLVM objc_exception_throw function.
    420   llvm::Constant *getExceptionThrowFn() {
    421     // void objc_exception_throw(id)
    422     llvm::Type *args[] = { ObjectPtrTy };
    423     llvm::FunctionType *FTy =
    424       llvm::FunctionType::get(CGM.VoidTy, args, false);
    425     return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
    426   }
    427 
    428   /// ExceptionRethrowFn - LLVM objc_exception_rethrow function.
    429   llvm::Constant *getExceptionRethrowFn() {
    430     // void objc_exception_rethrow(void)
    431     llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false);
    432     return CGM.CreateRuntimeFunction(FTy, "objc_exception_rethrow");
    433   }
    434 
    435   /// SyncEnterFn - LLVM object_sync_enter function.
    436   llvm::Constant *getSyncEnterFn() {
    437     // int objc_sync_enter (id)
    438     llvm::Type *args[] = { ObjectPtrTy };
    439     llvm::FunctionType *FTy =
    440       llvm::FunctionType::get(CGM.IntTy, args, false);
    441     return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
    442   }
    443 
    444   /// SyncExitFn - LLVM object_sync_exit function.
    445   llvm::Constant *getSyncExitFn() {
    446     // int objc_sync_exit (id)
    447     llvm::Type *args[] = { ObjectPtrTy };
    448     llvm::FunctionType *FTy =
    449       llvm::FunctionType::get(CGM.IntTy, args, false);
    450     return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
    451   }
    452 
    453   llvm::Constant *getSendFn(bool IsSuper) const {
    454     return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
    455   }
    456 
    457   llvm::Constant *getSendFn2(bool IsSuper) const {
    458     return IsSuper ? getMessageSendSuperFn2() : getMessageSendFn();
    459   }
    460 
    461   llvm::Constant *getSendStretFn(bool IsSuper) const {
    462     return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
    463   }
    464 
    465   llvm::Constant *getSendStretFn2(bool IsSuper) const {
    466     return IsSuper ? getMessageSendSuperStretFn2() : getMessageSendStretFn();
    467   }
    468 
    469   llvm::Constant *getSendFpretFn(bool IsSuper) const {
    470     return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
    471   }
    472 
    473   llvm::Constant *getSendFpretFn2(bool IsSuper) const {
    474     return IsSuper ? getMessageSendSuperFpretFn2() : getMessageSendFpretFn();
    475   }
    476 
    477   llvm::Constant *getSendFp2retFn(bool IsSuper) const {
    478     return IsSuper ? getMessageSendSuperFn() : getMessageSendFp2retFn();
    479   }
    480 
    481   llvm::Constant *getSendFp2RetFn2(bool IsSuper) const {
    482     return IsSuper ? getMessageSendSuperFn2() : getMessageSendFp2retFn();
    483   }
    484 
    485   ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
    486   ~ObjCCommonTypesHelper(){}
    487 };
    488 
    489 /// ObjCTypesHelper - Helper class that encapsulates lazy
    490 /// construction of varies types used during ObjC generation.
    491 class ObjCTypesHelper : public ObjCCommonTypesHelper {
    492 public:
    493   /// SymtabTy - LLVM type for struct objc_symtab.
    494   llvm::StructType *SymtabTy;
    495   /// SymtabPtrTy - LLVM type for struct objc_symtab *.
    496   llvm::Type *SymtabPtrTy;
    497   /// ModuleTy - LLVM type for struct objc_module.
    498   llvm::StructType *ModuleTy;
    499 
    500   /// ProtocolTy - LLVM type for struct objc_protocol.
    501   llvm::StructType *ProtocolTy;
    502   /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
    503   llvm::Type *ProtocolPtrTy;
    504   /// ProtocolExtensionTy - LLVM type for struct
    505   /// objc_protocol_extension.
    506   llvm::StructType *ProtocolExtensionTy;
    507   /// ProtocolExtensionTy - LLVM type for struct
    508   /// objc_protocol_extension *.
    509   llvm::Type *ProtocolExtensionPtrTy;
    510   /// MethodDescriptionTy - LLVM type for struct
    511   /// objc_method_description.
    512   llvm::StructType *MethodDescriptionTy;
    513   /// MethodDescriptionListTy - LLVM type for struct
    514   /// objc_method_description_list.
    515   llvm::StructType *MethodDescriptionListTy;
    516   /// MethodDescriptionListPtrTy - LLVM type for struct
    517   /// objc_method_description_list *.
    518   llvm::Type *MethodDescriptionListPtrTy;
    519   /// ProtocolListTy - LLVM type for struct objc_property_list.
    520   llvm::StructType *ProtocolListTy;
    521   /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
    522   llvm::Type *ProtocolListPtrTy;
    523   /// CategoryTy - LLVM type for struct objc_category.
    524   llvm::StructType *CategoryTy;
    525   /// ClassTy - LLVM type for struct objc_class.
    526   llvm::StructType *ClassTy;
    527   /// ClassPtrTy - LLVM type for struct objc_class *.
    528   llvm::Type *ClassPtrTy;
    529   /// ClassExtensionTy - LLVM type for struct objc_class_ext.
    530   llvm::StructType *ClassExtensionTy;
    531   /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
    532   llvm::Type *ClassExtensionPtrTy;
    533   // IvarTy - LLVM type for struct objc_ivar.
    534   llvm::StructType *IvarTy;
    535   /// IvarListTy - LLVM type for struct objc_ivar_list.
    536   llvm::Type *IvarListTy;
    537   /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
    538   llvm::Type *IvarListPtrTy;
    539   /// MethodListTy - LLVM type for struct objc_method_list.
    540   llvm::Type *MethodListTy;
    541   /// MethodListPtrTy - LLVM type for struct objc_method_list *.
    542   llvm::Type *MethodListPtrTy;
    543 
    544   /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
    545   llvm::Type *ExceptionDataTy;
    546 
    547   /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
    548   llvm::Constant *getExceptionTryEnterFn() {
    549     llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
    550     return CGM.CreateRuntimeFunction(
    551       llvm::FunctionType::get(CGM.VoidTy, params, false),
    552       "objc_exception_try_enter");
    553   }
    554 
    555   /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
    556   llvm::Constant *getExceptionTryExitFn() {
    557     llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
    558     return CGM.CreateRuntimeFunction(
    559       llvm::FunctionType::get(CGM.VoidTy, params, false),
    560       "objc_exception_try_exit");
    561   }
    562 
    563   /// ExceptionExtractFn - LLVM objc_exception_extract function.
    564   llvm::Constant *getExceptionExtractFn() {
    565     llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
    566     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
    567                                                              params, false),
    568                                      "objc_exception_extract");
    569   }
    570 
    571   /// ExceptionMatchFn - LLVM objc_exception_match function.
    572   llvm::Constant *getExceptionMatchFn() {
    573     llvm::Type *params[] = { ClassPtrTy, ObjectPtrTy };
    574     return CGM.CreateRuntimeFunction(
    575       llvm::FunctionType::get(CGM.Int32Ty, params, false),
    576       "objc_exception_match");
    577 
    578   }
    579 
    580   /// SetJmpFn - LLVM _setjmp function.
    581   llvm::Constant *getSetJmpFn() {
    582     // This is specifically the prototype for x86.
    583     llvm::Type *params[] = { CGM.Int32Ty->getPointerTo() };
    584     return
    585       CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty,
    586                                                         params, false),
    587                                 "_setjmp",
    588                                 llvm::AttributeSet::get(CGM.getLLVMContext(),
    589                                               llvm::AttributeSet::FunctionIndex,
    590                                                  llvm::Attribute::NonLazyBind));
    591   }
    592 
    593 public:
    594   ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
    595   ~ObjCTypesHelper() {}
    596 };
    597 
    598 /// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
    599 /// modern abi
    600 class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
    601 public:
    602 
    603   // MethodListnfABITy - LLVM for struct _method_list_t
    604   llvm::StructType *MethodListnfABITy;
    605 
    606   // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
    607   llvm::Type *MethodListnfABIPtrTy;
    608 
    609   // ProtocolnfABITy = LLVM for struct _protocol_t
    610   llvm::StructType *ProtocolnfABITy;
    611 
    612   // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
    613   llvm::Type *ProtocolnfABIPtrTy;
    614 
    615   // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
    616   llvm::StructType *ProtocolListnfABITy;
    617 
    618   // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
    619   llvm::Type *ProtocolListnfABIPtrTy;
    620 
    621   // ClassnfABITy - LLVM for struct _class_t
    622   llvm::StructType *ClassnfABITy;
    623 
    624   // ClassnfABIPtrTy - LLVM for struct _class_t*
    625   llvm::Type *ClassnfABIPtrTy;
    626 
    627   // IvarnfABITy - LLVM for struct _ivar_t
    628   llvm::StructType *IvarnfABITy;
    629 
    630   // IvarListnfABITy - LLVM for struct _ivar_list_t
    631   llvm::StructType *IvarListnfABITy;
    632 
    633   // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
    634   llvm::Type *IvarListnfABIPtrTy;
    635 
    636   // ClassRonfABITy - LLVM for struct _class_ro_t
    637   llvm::StructType *ClassRonfABITy;
    638 
    639   // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
    640   llvm::Type *ImpnfABITy;
    641 
    642   // CategorynfABITy - LLVM for struct _category_t
    643   llvm::StructType *CategorynfABITy;
    644 
    645   // New types for nonfragile abi messaging.
    646 
    647   // MessageRefTy - LLVM for:
    648   // struct _message_ref_t {
    649   //   IMP messenger;
    650   //   SEL name;
    651   // };
    652   llvm::StructType *MessageRefTy;
    653   // MessageRefCTy - clang type for struct _message_ref_t
    654   QualType MessageRefCTy;
    655 
    656   // MessageRefPtrTy - LLVM for struct _message_ref_t*
    657   llvm::Type *MessageRefPtrTy;
    658   // MessageRefCPtrTy - clang type for struct _message_ref_t*
    659   QualType MessageRefCPtrTy;
    660 
    661   // MessengerTy - Type of the messenger (shown as IMP above)
    662   llvm::FunctionType *MessengerTy;
    663 
    664   // SuperMessageRefTy - LLVM for:
    665   // struct _super_message_ref_t {
    666   //   SUPER_IMP messenger;
    667   //   SEL name;
    668   // };
    669   llvm::StructType *SuperMessageRefTy;
    670 
    671   // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
    672   llvm::Type *SuperMessageRefPtrTy;
    673 
    674   llvm::Constant *getMessageSendFixupFn() {
    675     // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
    676     llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
    677     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
    678                                                              params, true),
    679                                      "objc_msgSend_fixup");
    680   }
    681 
    682   llvm::Constant *getMessageSendFpretFixupFn() {
    683     // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
    684     llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
    685     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
    686                                                              params, true),
    687                                      "objc_msgSend_fpret_fixup");
    688   }
    689 
    690   llvm::Constant *getMessageSendStretFixupFn() {
    691     // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
    692     llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
    693     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
    694                                                              params, true),
    695                                      "objc_msgSend_stret_fixup");
    696   }
    697 
    698   llvm::Constant *getMessageSendSuper2FixupFn() {
    699     // id objc_msgSendSuper2_fixup (struct objc_super *,
    700     //                              struct _super_message_ref_t*, ...)
    701     llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy };
    702     return  CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
    703                                                               params, true),
    704                                       "objc_msgSendSuper2_fixup");
    705   }
    706 
    707   llvm::Constant *getMessageSendSuper2StretFixupFn() {
    708     // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
    709     //                                   struct _super_message_ref_t*, ...)
    710     llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy };
    711     return  CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
    712                                                               params, true),
    713                                       "objc_msgSendSuper2_stret_fixup");
    714   }
    715 
    716   llvm::Constant *getObjCEndCatchFn() {
    717     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy, false),
    718                                      "objc_end_catch");
    719 
    720   }
    721 
    722   llvm::Constant *getObjCBeginCatchFn() {
    723     llvm::Type *params[] = { Int8PtrTy };
    724     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
    725                                                              params, false),
    726                                      "objc_begin_catch");
    727   }
    728 
    729   llvm::StructType *EHTypeTy;
    730   llvm::Type *EHTypePtrTy;
    731 
    732   ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
    733   ~ObjCNonFragileABITypesHelper(){}
    734 };
    735 
    736 class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
    737 public:
    738   // FIXME - accessibility
    739   class GC_IVAR {
    740   public:
    741     unsigned ivar_bytepos;
    742     unsigned ivar_size;
    743     GC_IVAR(unsigned bytepos = 0, unsigned size = 0)
    744       : ivar_bytepos(bytepos), ivar_size(size) {}
    745 
    746     // Allow sorting based on byte pos.
    747     bool operator<(const GC_IVAR &b) const {
    748       return ivar_bytepos < b.ivar_bytepos;
    749     }
    750   };
    751 
    752   class SKIP_SCAN {
    753   public:
    754     unsigned skip;
    755     unsigned scan;
    756     SKIP_SCAN(unsigned _skip = 0, unsigned _scan = 0)
    757       : skip(_skip), scan(_scan) {}
    758   };
    759 
    760   /// opcode for captured block variables layout 'instructions'.
    761   /// In the following descriptions, 'I' is the value of the immediate field.
    762   /// (field following the opcode).
    763   ///
    764   enum BLOCK_LAYOUT_OPCODE {
    765     /// An operator which affects how the following layout should be
    766     /// interpreted.
    767     ///   I == 0: Halt interpretation and treat everything else as
    768     ///           a non-pointer.  Note that this instruction is equal
    769     ///           to '\0'.
    770     ///   I != 0: Currently unused.
    771     BLOCK_LAYOUT_OPERATOR            = 0,
    772 
    773     /// The next I+1 bytes do not contain a value of object pointer type.
    774     /// Note that this can leave the stream unaligned, meaning that
    775     /// subsequent word-size instructions do not begin at a multiple of
    776     /// the pointer size.
    777     BLOCK_LAYOUT_NON_OBJECT_BYTES    = 1,
    778 
    779     /// The next I+1 words do not contain a value of object pointer type.
    780     /// This is simply an optimized version of BLOCK_LAYOUT_BYTES for
    781     /// when the required skip quantity is a multiple of the pointer size.
    782     BLOCK_LAYOUT_NON_OBJECT_WORDS    = 2,
    783 
    784     /// The next I+1 words are __strong pointers to Objective-C
    785     /// objects or blocks.
    786     BLOCK_LAYOUT_STRONG              = 3,
    787 
    788     /// The next I+1 words are pointers to __block variables.
    789     BLOCK_LAYOUT_BYREF               = 4,
    790 
    791     /// The next I+1 words are __weak pointers to Objective-C
    792     /// objects or blocks.
    793     BLOCK_LAYOUT_WEAK                = 5,
    794 
    795     /// The next I+1 words are __unsafe_unretained pointers to
    796     /// Objective-C objects or blocks.
    797     BLOCK_LAYOUT_UNRETAINED          = 6
    798 
    799     /// The next I+1 words are block or object pointers with some
    800     /// as-yet-unspecified ownership semantics.  If we add more
    801     /// flavors of ownership semantics, values will be taken from
    802     /// this range.
    803     ///
    804     /// This is included so that older tools can at least continue
    805     /// processing the layout past such things.
    806     //BLOCK_LAYOUT_OWNERSHIP_UNKNOWN = 7..10,
    807 
    808     /// All other opcodes are reserved.  Halt interpretation and
    809     /// treat everything else as opaque.
    810   };
    811 
    812   class RUN_SKIP {
    813   public:
    814     enum BLOCK_LAYOUT_OPCODE opcode;
    815     CharUnits block_var_bytepos;
    816     CharUnits block_var_size;
    817     RUN_SKIP(enum BLOCK_LAYOUT_OPCODE Opcode = BLOCK_LAYOUT_OPERATOR,
    818              CharUnits BytePos = CharUnits::Zero(),
    819              CharUnits Size = CharUnits::Zero())
    820     : opcode(Opcode), block_var_bytepos(BytePos),  block_var_size(Size) {}
    821 
    822     // Allow sorting based on byte pos.
    823     bool operator<(const RUN_SKIP &b) const {
    824       return block_var_bytepos < b.block_var_bytepos;
    825     }
    826   };
    827 
    828 protected:
    829   llvm::LLVMContext &VMContext;
    830   // FIXME! May not be needing this after all.
    831   unsigned ObjCABI;
    832 
    833   // gc ivar layout bitmap calculation helper caches.
    834   SmallVector<GC_IVAR, 16> SkipIvars;
    835   SmallVector<GC_IVAR, 16> IvarsInfo;
    836 
    837   // arc/mrr layout of captured block literal variables.
    838   SmallVector<RUN_SKIP, 16> RunSkipBlockVars;
    839 
    840   /// LazySymbols - Symbols to generate a lazy reference for. See
    841   /// DefinedSymbols and FinishModule().
    842   llvm::SetVector<IdentifierInfo*> LazySymbols;
    843 
    844   /// DefinedSymbols - External symbols which are defined by this
    845   /// module. The symbols in this list and LazySymbols are used to add
    846   /// special linker symbols which ensure that Objective-C modules are
    847   /// linked properly.
    848   llvm::SetVector<IdentifierInfo*> DefinedSymbols;
    849 
    850   /// ClassNames - uniqued class names.
    851   llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
    852 
    853   /// MethodVarNames - uniqued method variable names.
    854   llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
    855 
    856   /// DefinedCategoryNames - list of category names in form Class_Category.
    857   llvm::SetVector<std::string> DefinedCategoryNames;
    858 
    859   /// MethodVarTypes - uniqued method type signatures. We have to use
    860   /// a StringMap here because have no other unique reference.
    861   llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
    862 
    863   /// MethodDefinitions - map of methods which have been defined in
    864   /// this translation unit.
    865   llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
    866 
    867   /// PropertyNames - uniqued method variable names.
    868   llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
    869 
    870   /// ClassReferences - uniqued class references.
    871   llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
    872 
    873   /// SelectorReferences - uniqued selector references.
    874   llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
    875 
    876   /// Protocols - Protocols for which an objc_protocol structure has
    877   /// been emitted. Forward declarations are handled by creating an
    878   /// empty structure whose initializer is filled in when/if defined.
    879   llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
    880 
    881   /// DefinedProtocols - Protocols which have actually been
    882   /// defined. We should not need this, see FIXME in GenerateProtocol.
    883   llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
    884 
    885   /// DefinedClasses - List of defined classes.
    886   SmallVector<llvm::GlobalValue*, 16> DefinedClasses;
    887 
    888   /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
    889   SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyClasses;
    890 
    891   /// DefinedCategories - List of defined categories.
    892   SmallVector<llvm::GlobalValue*, 16> DefinedCategories;
    893 
    894   /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
    895   SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyCategories;
    896 
    897   /// GetNameForMethod - Return a name for the given method.
    898   /// \param[out] NameOut - The return value.
    899   void GetNameForMethod(const ObjCMethodDecl *OMD,
    900                         const ObjCContainerDecl *CD,
    901                         SmallVectorImpl<char> &NameOut);
    902 
    903   /// GetMethodVarName - Return a unique constant for the given
    904   /// selector's name. The return value has type char *.
    905   llvm::Constant *GetMethodVarName(Selector Sel);
    906   llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
    907 
    908   /// GetMethodVarType - Return a unique constant for the given
    909   /// method's type encoding string. The return value has type char *.
    910 
    911   // FIXME: This is a horrible name.
    912   llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D,
    913                                    bool Extended = false);
    914   llvm::Constant *GetMethodVarType(const FieldDecl *D);
    915 
    916   /// GetPropertyName - Return a unique constant for the given
    917   /// name. The return value has type char *.
    918   llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
    919 
    920   // FIXME: This can be dropped once string functions are unified.
    921   llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
    922                                         const Decl *Container);
    923 
    924   /// GetClassName - Return a unique constant for the given selector's
    925   /// name. The return value has type char *.
    926   llvm::Constant *GetClassName(IdentifierInfo *Ident);
    927 
    928   llvm::Function *GetMethodDefinition(const ObjCMethodDecl *MD);
    929 
    930   /// BuildIvarLayout - Builds ivar layout bitmap for the class
    931   /// implementation for the __strong or __weak case.
    932   ///
    933   llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
    934                                   bool ForStrongLayout);
    935 
    936   llvm::Constant *BuildIvarLayoutBitmap(std::string &BitMap);
    937 
    938   void BuildAggrIvarRecordLayout(const RecordType *RT,
    939                                  unsigned int BytePos, bool ForStrongLayout,
    940                                  bool &HasUnion);
    941   void BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
    942                            const llvm::StructLayout *Layout,
    943                            const RecordDecl *RD,
    944                            ArrayRef<const FieldDecl*> RecFields,
    945                            unsigned int BytePos, bool ForStrongLayout,
    946                            bool &HasUnion);
    947 
    948   Qualifiers::ObjCLifetime getBlockCaptureLifetime(QualType QT, bool ByrefLayout);
    949 
    950   void UpdateRunSkipBlockVars(bool IsByref,
    951                               Qualifiers::ObjCLifetime LifeTime,
    952                               CharUnits FieldOffset,
    953                               CharUnits FieldSize);
    954 
    955   void BuildRCBlockVarRecordLayout(const RecordType *RT,
    956                                    CharUnits BytePos, bool &HasUnion,
    957                                    bool ByrefLayout=false);
    958 
    959   void BuildRCRecordLayout(const llvm::StructLayout *RecLayout,
    960                            const RecordDecl *RD,
    961                            ArrayRef<const FieldDecl*> RecFields,
    962                            CharUnits BytePos, bool &HasUnion,
    963                            bool ByrefLayout);
    964 
    965   uint64_t InlineLayoutInstruction(SmallVectorImpl<unsigned char> &Layout);
    966 
    967   llvm::Constant *getBitmapBlockLayout(bool ComputeByrefLayout);
    968 
    969 
    970   /// GetIvarLayoutName - Returns a unique constant for the given
    971   /// ivar layout bitmap.
    972   llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
    973                                     const ObjCCommonTypesHelper &ObjCTypes);
    974 
    975   /// EmitPropertyList - Emit the given property list. The return
    976   /// value has type PropertyListPtrTy.
    977   llvm::Constant *EmitPropertyList(Twine Name,
    978                                    const Decl *Container,
    979                                    const ObjCContainerDecl *OCD,
    980                                    const ObjCCommonTypesHelper &ObjCTypes);
    981 
    982   /// EmitProtocolMethodTypes - Generate the array of extended method type
    983   /// strings. The return value has type Int8PtrPtrTy.
    984   llvm::Constant *EmitProtocolMethodTypes(Twine Name,
    985                                           ArrayRef<llvm::Constant*> MethodTypes,
    986                                        const ObjCCommonTypesHelper &ObjCTypes);
    987 
    988   /// PushProtocolProperties - Push protocol's property on the input stack.
    989   void PushProtocolProperties(
    990     llvm::SmallPtrSet<const IdentifierInfo*, 16> &PropertySet,
    991     SmallVectorImpl<llvm::Constant*> &Properties,
    992     const Decl *Container,
    993     const ObjCProtocolDecl *PROTO,
    994     const ObjCCommonTypesHelper &ObjCTypes);
    995 
    996   /// GetProtocolRef - Return a reference to the internal protocol
    997   /// description, creating an empty one if it has not been
    998   /// defined. The return value has type ProtocolPtrTy.
    999   llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
   1000 
   1001   /// CreateMetadataVar - Create a global variable with internal
   1002   /// linkage for use by the Objective-C runtime.
   1003   ///
   1004   /// This is a convenience wrapper which not only creates the
   1005   /// variable, but also sets the section and alignment and adds the
   1006   /// global to the "llvm.used" list.
   1007   ///
   1008   /// \param Name - The variable name.
   1009   /// \param Init - The variable initializer; this is also used to
   1010   /// define the type of the variable.
   1011   /// \param Section - The section the variable should go into, or 0.
   1012   /// \param Align - The alignment for the variable, or 0.
   1013   /// \param AddToUsed - Whether the variable should be added to
   1014   /// "llvm.used".
   1015   llvm::GlobalVariable *CreateMetadataVar(Twine Name,
   1016                                           llvm::Constant *Init,
   1017                                           const char *Section,
   1018                                           unsigned Align,
   1019                                           bool AddToUsed);
   1020 
   1021   CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
   1022                                   ReturnValueSlot Return,
   1023                                   QualType ResultType,
   1024                                   llvm::Value *Sel,
   1025                                   llvm::Value *Arg0,
   1026                                   QualType Arg0Ty,
   1027                                   bool IsSuper,
   1028                                   const CallArgList &CallArgs,
   1029                                   const ObjCMethodDecl *OMD,
   1030                                   const ObjCCommonTypesHelper &ObjCTypes);
   1031 
   1032   /// EmitImageInfo - Emit the image info marker used to encode some module
   1033   /// level information.
   1034   void EmitImageInfo();
   1035 
   1036 public:
   1037   CGObjCCommonMac(CodeGen::CodeGenModule &cgm) :
   1038     CGObjCRuntime(cgm), VMContext(cgm.getLLVMContext()) { }
   1039 
   1040   virtual llvm::Constant *GenerateConstantString(const StringLiteral *SL);
   1041 
   1042   virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
   1043                                          const ObjCContainerDecl *CD=0);
   1044 
   1045   virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
   1046 
   1047   /// GetOrEmitProtocol - Get the protocol object for the given
   1048   /// declaration, emitting it if necessary. The return value has type
   1049   /// ProtocolPtrTy.
   1050   virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
   1051 
   1052   /// GetOrEmitProtocolRef - Get a forward reference to the protocol
   1053   /// object for the given declaration, emitting it if needed. These
   1054   /// forward references will be filled in with empty bodies if no
   1055   /// definition is seen. The return value has type ProtocolPtrTy.
   1056   virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
   1057   virtual llvm::Constant *BuildGCBlockLayout(CodeGen::CodeGenModule &CGM,
   1058                                              const CGBlockInfo &blockInfo);
   1059   virtual llvm::Constant *BuildRCBlockLayout(CodeGen::CodeGenModule &CGM,
   1060                                              const CGBlockInfo &blockInfo);
   1061 
   1062   virtual llvm::Constant *BuildByrefLayout(CodeGen::CodeGenModule &CGM,
   1063                                            QualType T);
   1064 };
   1065 
   1066 class CGObjCMac : public CGObjCCommonMac {
   1067 private:
   1068   ObjCTypesHelper ObjCTypes;
   1069 
   1070   /// EmitModuleInfo - Another marker encoding module level
   1071   /// information.
   1072   void EmitModuleInfo();
   1073 
   1074   /// EmitModuleSymols - Emit module symbols, the list of defined
   1075   /// classes and categories. The result has type SymtabPtrTy.
   1076   llvm::Constant *EmitModuleSymbols();
   1077 
   1078   /// FinishModule - Write out global data structures at the end of
   1079   /// processing a translation unit.
   1080   void FinishModule();
   1081 
   1082   /// EmitClassExtension - Generate the class extension structure used
   1083   /// to store the weak ivar layout and properties. The return value
   1084   /// has type ClassExtensionPtrTy.
   1085   llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
   1086 
   1087   /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
   1088   /// for the given class.
   1089   llvm::Value *EmitClassRef(CodeGenFunction &CGF,
   1090                             const ObjCInterfaceDecl *ID);
   1091 
   1092   llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF,
   1093                                   IdentifierInfo *II);
   1094 
   1095   llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF);
   1096 
   1097   /// EmitSuperClassRef - Emits reference to class's main metadata class.
   1098   llvm::Value *EmitSuperClassRef(const ObjCInterfaceDecl *ID);
   1099 
   1100   /// EmitIvarList - Emit the ivar list for the given
   1101   /// implementation. If ForClass is true the list of class ivars
   1102   /// (i.e. metaclass ivars) is emitted, otherwise the list of
   1103   /// interface ivars will be emitted. The return value has type
   1104   /// IvarListPtrTy.
   1105   llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
   1106                                bool ForClass);
   1107 
   1108   /// EmitMetaClass - Emit a forward reference to the class structure
   1109   /// for the metaclass of the given interface. The return value has
   1110   /// type ClassPtrTy.
   1111   llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
   1112 
   1113   /// EmitMetaClass - Emit a class structure for the metaclass of the
   1114   /// given implementation. The return value has type ClassPtrTy.
   1115   llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
   1116                                 llvm::Constant *Protocols,
   1117                                 ArrayRef<llvm::Constant*> Methods);
   1118 
   1119   llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
   1120 
   1121   llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
   1122 
   1123   /// EmitMethodList - Emit the method list for the given
   1124   /// implementation. The return value has type MethodListPtrTy.
   1125   llvm::Constant *EmitMethodList(Twine Name,
   1126                                  const char *Section,
   1127                                  ArrayRef<llvm::Constant*> Methods);
   1128 
   1129   /// EmitMethodDescList - Emit a method description list for a list of
   1130   /// method declarations.
   1131   ///  - TypeName: The name for the type containing the methods.
   1132   ///  - IsProtocol: True iff these methods are for a protocol.
   1133   ///  - ClassMethds: True iff these are class methods.
   1134   ///  - Required: When true, only "required" methods are
   1135   ///    listed. Similarly, when false only "optional" methods are
   1136   ///    listed. For classes this should always be true.
   1137   ///  - begin, end: The method list to output.
   1138   ///
   1139   /// The return value has type MethodDescriptionListPtrTy.
   1140   llvm::Constant *EmitMethodDescList(Twine Name,
   1141                                      const char *Section,
   1142                                      ArrayRef<llvm::Constant*> Methods);
   1143 
   1144   /// GetOrEmitProtocol - Get the protocol object for the given
   1145   /// declaration, emitting it if necessary. The return value has type
   1146   /// ProtocolPtrTy.
   1147   virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
   1148 
   1149   /// GetOrEmitProtocolRef - Get a forward reference to the protocol
   1150   /// object for the given declaration, emitting it if needed. These
   1151   /// forward references will be filled in with empty bodies if no
   1152   /// definition is seen. The return value has type ProtocolPtrTy.
   1153   virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
   1154 
   1155   /// EmitProtocolExtension - Generate the protocol extension
   1156   /// structure used to store optional instance and class methods, and
   1157   /// protocol properties. The return value has type
   1158   /// ProtocolExtensionPtrTy.
   1159   llvm::Constant *
   1160   EmitProtocolExtension(const ObjCProtocolDecl *PD,
   1161                         ArrayRef<llvm::Constant*> OptInstanceMethods,
   1162                         ArrayRef<llvm::Constant*> OptClassMethods,
   1163                         ArrayRef<llvm::Constant*> MethodTypesExt);
   1164 
   1165   /// EmitProtocolList - Generate the list of referenced
   1166   /// protocols. The return value has type ProtocolListPtrTy.
   1167   llvm::Constant *EmitProtocolList(Twine Name,
   1168                                    ObjCProtocolDecl::protocol_iterator begin,
   1169                                    ObjCProtocolDecl::protocol_iterator end);
   1170 
   1171   /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
   1172   /// for the given selector.
   1173   llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel,
   1174                             bool lval=false);
   1175 
   1176 public:
   1177   CGObjCMac(CodeGen::CodeGenModule &cgm);
   1178 
   1179   virtual llvm::Function *ModuleInitFunction();
   1180 
   1181   virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
   1182                                               ReturnValueSlot Return,
   1183                                               QualType ResultType,
   1184                                               Selector Sel,
   1185                                               llvm::Value *Receiver,
   1186                                               const CallArgList &CallArgs,
   1187                                               const ObjCInterfaceDecl *Class,
   1188                                               const ObjCMethodDecl *Method);
   1189 
   1190   virtual CodeGen::RValue
   1191   GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
   1192                            ReturnValueSlot Return,
   1193                            QualType ResultType,
   1194                            Selector Sel,
   1195                            const ObjCInterfaceDecl *Class,
   1196                            bool isCategoryImpl,
   1197                            llvm::Value *Receiver,
   1198                            bool IsClassMessage,
   1199                            const CallArgList &CallArgs,
   1200                            const ObjCMethodDecl *Method);
   1201 
   1202   virtual llvm::Value *GetClass(CodeGenFunction &CGF,
   1203                                 const ObjCInterfaceDecl *ID);
   1204 
   1205   virtual llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
   1206                                    bool lval = false);
   1207 
   1208   /// The NeXT/Apple runtimes do not support typed selectors; just emit an
   1209   /// untyped one.
   1210   virtual llvm::Value *GetSelector(CodeGenFunction &CGF,
   1211                                    const ObjCMethodDecl *Method);
   1212 
   1213   virtual llvm::Constant *GetEHType(QualType T);
   1214 
   1215   virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
   1216 
   1217   virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
   1218 
   1219   virtual void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {}
   1220 
   1221   virtual llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
   1222                                            const ObjCProtocolDecl *PD);
   1223 
   1224   virtual llvm::Constant *GetPropertyGetFunction();
   1225   virtual llvm::Constant *GetPropertySetFunction();
   1226   virtual llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
   1227                                                           bool copy);
   1228   virtual llvm::Constant *GetGetStructFunction();
   1229   virtual llvm::Constant *GetSetStructFunction();
   1230   virtual llvm::Constant *GetCppAtomicObjectGetFunction();
   1231   virtual llvm::Constant *GetCppAtomicObjectSetFunction();
   1232   virtual llvm::Constant *EnumerationMutationFunction();
   1233 
   1234   virtual void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
   1235                            const ObjCAtTryStmt &S);
   1236   virtual void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
   1237                                     const ObjCAtSynchronizedStmt &S);
   1238   void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const Stmt &S);
   1239   virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
   1240                              const ObjCAtThrowStmt &S,
   1241                              bool ClearInsertionPoint=true);
   1242   virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
   1243                                          llvm::Value *AddrWeakObj);
   1244   virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
   1245                                   llvm::Value *src, llvm::Value *dst);
   1246   virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
   1247                                     llvm::Value *src, llvm::Value *dest,
   1248                                     bool threadlocal = false);
   1249   virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
   1250                                   llvm::Value *src, llvm::Value *dest,
   1251                                   llvm::Value *ivarOffset);
   1252   virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
   1253                                         llvm::Value *src, llvm::Value *dest);
   1254   virtual void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
   1255                                         llvm::Value *dest, llvm::Value *src,
   1256                                         llvm::Value *size);
   1257 
   1258   virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
   1259                                       QualType ObjectTy,
   1260                                       llvm::Value *BaseValue,
   1261                                       const ObjCIvarDecl *Ivar,
   1262                                       unsigned CVRQualifiers);
   1263   virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
   1264                                       const ObjCInterfaceDecl *Interface,
   1265                                       const ObjCIvarDecl *Ivar);
   1266 
   1267   /// GetClassGlobal - Return the global variable for the Objective-C
   1268   /// class of the given name.
   1269   virtual llvm::GlobalVariable *GetClassGlobal(const std::string &Name) {
   1270     llvm_unreachable("CGObjCMac::GetClassGlobal");
   1271   }
   1272 };
   1273 
   1274 class CGObjCNonFragileABIMac : public CGObjCCommonMac {
   1275 private:
   1276   ObjCNonFragileABITypesHelper ObjCTypes;
   1277   llvm::GlobalVariable* ObjCEmptyCacheVar;
   1278   llvm::GlobalVariable* ObjCEmptyVtableVar;
   1279 
   1280   /// SuperClassReferences - uniqued super class references.
   1281   llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
   1282 
   1283   /// MetaClassReferences - uniqued meta class references.
   1284   llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
   1285 
   1286   /// EHTypeReferences - uniqued class ehtype references.
   1287   llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
   1288 
   1289   /// VTableDispatchMethods - List of methods for which we generate
   1290   /// vtable-based message dispatch.
   1291   llvm::DenseSet<Selector> VTableDispatchMethods;
   1292 
   1293   /// DefinedMetaClasses - List of defined meta-classes.
   1294   std::vector<llvm::GlobalValue*> DefinedMetaClasses;
   1295 
   1296   /// isVTableDispatchedSelector - Returns true if SEL is a
   1297   /// vtable-based selector.
   1298   bool isVTableDispatchedSelector(Selector Sel);
   1299 
   1300   /// FinishNonFragileABIModule - Write out global data structures at the end of
   1301   /// processing a translation unit.
   1302   void FinishNonFragileABIModule();
   1303 
   1304   /// AddModuleClassList - Add the given list of class pointers to the
   1305   /// module with the provided symbol and section names.
   1306   void AddModuleClassList(ArrayRef<llvm::GlobalValue*> Container,
   1307                           const char *SymbolName,
   1308                           const char *SectionName);
   1309 
   1310   llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
   1311                                               unsigned InstanceStart,
   1312                                               unsigned InstanceSize,
   1313                                               const ObjCImplementationDecl *ID);
   1314   llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
   1315                                             llvm::Constant *IsAGV,
   1316                                             llvm::Constant *SuperClassGV,
   1317                                             llvm::Constant *ClassRoGV,
   1318                                             bool HiddenVisibility);
   1319 
   1320   llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
   1321 
   1322   llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
   1323 
   1324   /// EmitMethodList - Emit the method list for the given
   1325   /// implementation. The return value has type MethodListnfABITy.
   1326   llvm::Constant *EmitMethodList(Twine Name,
   1327                                  const char *Section,
   1328                                  ArrayRef<llvm::Constant*> Methods);
   1329   /// EmitIvarList - Emit the ivar list for the given
   1330   /// implementation. If ForClass is true the list of class ivars
   1331   /// (i.e. metaclass ivars) is emitted, otherwise the list of
   1332   /// interface ivars will be emitted. The return value has type
   1333   /// IvarListnfABIPtrTy.
   1334   llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
   1335 
   1336   llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
   1337                                     const ObjCIvarDecl *Ivar,
   1338                                     unsigned long int offset);
   1339 
   1340   /// GetOrEmitProtocol - Get the protocol object for the given
   1341   /// declaration, emitting it if necessary. The return value has type
   1342   /// ProtocolPtrTy.
   1343   virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
   1344 
   1345   /// GetOrEmitProtocolRef - Get a forward reference to the protocol
   1346   /// object for the given declaration, emitting it if needed. These
   1347   /// forward references will be filled in with empty bodies if no
   1348   /// definition is seen. The return value has type ProtocolPtrTy.
   1349   virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
   1350 
   1351   /// EmitProtocolList - Generate the list of referenced
   1352   /// protocols. The return value has type ProtocolListPtrTy.
   1353   llvm::Constant *EmitProtocolList(Twine Name,
   1354                                    ObjCProtocolDecl::protocol_iterator begin,
   1355                                    ObjCProtocolDecl::protocol_iterator end);
   1356 
   1357   CodeGen::RValue EmitVTableMessageSend(CodeGen::CodeGenFunction &CGF,
   1358                                         ReturnValueSlot Return,
   1359                                         QualType ResultType,
   1360                                         Selector Sel,
   1361                                         llvm::Value *Receiver,
   1362                                         QualType Arg0Ty,
   1363                                         bool IsSuper,
   1364                                         const CallArgList &CallArgs,
   1365                                         const ObjCMethodDecl *Method);
   1366 
   1367   /// GetClassGlobal - Return the global variable for the Objective-C
   1368   /// class of the given name.
   1369   llvm::GlobalVariable *GetClassGlobal(const std::string &Name);
   1370 
   1371   /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
   1372   /// for the given class reference.
   1373   llvm::Value *EmitClassRef(CodeGenFunction &CGF,
   1374                             const ObjCInterfaceDecl *ID);
   1375 
   1376   llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF,
   1377                                   IdentifierInfo *II);
   1378 
   1379   llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF);
   1380 
   1381   /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
   1382   /// for the given super class reference.
   1383   llvm::Value *EmitSuperClassRef(CodeGenFunction &CGF,
   1384                                  const ObjCInterfaceDecl *ID);
   1385 
   1386   /// EmitMetaClassRef - Return a Value * of the address of _class_t
   1387   /// meta-data
   1388   llvm::Value *EmitMetaClassRef(CodeGenFunction &CGF,
   1389                                 const ObjCInterfaceDecl *ID);
   1390 
   1391   /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
   1392   /// the given ivar.
   1393   ///
   1394   llvm::GlobalVariable * ObjCIvarOffsetVariable(
   1395     const ObjCInterfaceDecl *ID,
   1396     const ObjCIvarDecl *Ivar);
   1397 
   1398   /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
   1399   /// for the given selector.
   1400   llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel,
   1401                             bool lval=false);
   1402 
   1403   /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
   1404   /// interface. The return value has type EHTypePtrTy.
   1405   llvm::Constant *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
   1406                                   bool ForDefinition);
   1407 
   1408   const char *getMetaclassSymbolPrefix() const {
   1409     return "OBJC_METACLASS_$_";
   1410   }
   1411 
   1412   const char *getClassSymbolPrefix() const {
   1413     return "OBJC_CLASS_$_";
   1414   }
   1415 
   1416   void GetClassSizeInfo(const ObjCImplementationDecl *OID,
   1417                         uint32_t &InstanceStart,
   1418                         uint32_t &InstanceSize);
   1419 
   1420   // Shamelessly stolen from Analysis/CFRefCount.cpp
   1421   Selector GetNullarySelector(const char* name) const {
   1422     IdentifierInfo* II = &CGM.getContext().Idents.get(name);
   1423     return CGM.getContext().Selectors.getSelector(0, &II);
   1424   }
   1425 
   1426   Selector GetUnarySelector(const char* name) const {
   1427     IdentifierInfo* II = &CGM.getContext().Idents.get(name);
   1428     return CGM.getContext().Selectors.getSelector(1, &II);
   1429   }
   1430 
   1431   /// ImplementationIsNonLazy - Check whether the given category or
   1432   /// class implementation is "non-lazy".
   1433   bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const;
   1434 
   1435   bool IsIvarOffsetKnownIdempotent(const CodeGen::CodeGenFunction &CGF,
   1436                                    const ObjCInterfaceDecl *ID,
   1437                                    const ObjCIvarDecl *IV) {
   1438     // Annotate the load as an invariant load iff the object type is the type,
   1439     // or a derived type, of the class containing the ivar within an ObjC
   1440     // method.  This check is needed because the ivar offset is a lazily
   1441     // initialised value that may depend on objc_msgSend to perform a fixup on
   1442     // the first message dispatch.
   1443     //
   1444     // An additional opportunity to mark the load as invariant arises when the
   1445     // base of the ivar access is a parameter to an Objective C method.
   1446     // However, because the parameters are not available in the current
   1447     // interface, we cannot perform this check.
   1448     if (CGF.CurFuncDecl && isa<ObjCMethodDecl>(CGF.CurFuncDecl))
   1449       if (IV->getContainingInterface()->isSuperClassOf(ID))
   1450         return true;
   1451     return false;
   1452   }
   1453 
   1454 public:
   1455   CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
   1456   // FIXME. All stubs for now!
   1457   virtual llvm::Function *ModuleInitFunction();
   1458 
   1459   virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
   1460                                               ReturnValueSlot Return,
   1461                                               QualType ResultType,
   1462                                               Selector Sel,
   1463                                               llvm::Value *Receiver,
   1464                                               const CallArgList &CallArgs,
   1465                                               const ObjCInterfaceDecl *Class,
   1466                                               const ObjCMethodDecl *Method);
   1467 
   1468   virtual CodeGen::RValue
   1469   GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
   1470                            ReturnValueSlot Return,
   1471                            QualType ResultType,
   1472                            Selector Sel,
   1473                            const ObjCInterfaceDecl *Class,
   1474                            bool isCategoryImpl,
   1475                            llvm::Value *Receiver,
   1476                            bool IsClassMessage,
   1477                            const CallArgList &CallArgs,
   1478                            const ObjCMethodDecl *Method);
   1479 
   1480   virtual llvm::Value *GetClass(CodeGenFunction &CGF,
   1481                                 const ObjCInterfaceDecl *ID);
   1482 
   1483   virtual llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
   1484                                    bool lvalue = false)
   1485     { return EmitSelector(CGF, Sel, lvalue); }
   1486 
   1487   /// The NeXT/Apple runtimes do not support typed selectors; just emit an
   1488   /// untyped one.
   1489   virtual llvm::Value *GetSelector(CodeGenFunction &CGF,
   1490                                    const ObjCMethodDecl *Method)
   1491     { return EmitSelector(CGF, Method->getSelector()); }
   1492 
   1493   virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
   1494 
   1495   virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
   1496 
   1497   virtual void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {}
   1498 
   1499   virtual llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
   1500                                            const ObjCProtocolDecl *PD);
   1501 
   1502   virtual llvm::Constant *GetEHType(QualType T);
   1503 
   1504   virtual llvm::Constant *GetPropertyGetFunction() {
   1505     return ObjCTypes.getGetPropertyFn();
   1506   }
   1507   virtual llvm::Constant *GetPropertySetFunction() {
   1508     return ObjCTypes.getSetPropertyFn();
   1509   }
   1510 
   1511   virtual llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
   1512                                                           bool copy) {
   1513     return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy);
   1514   }
   1515 
   1516   virtual llvm::Constant *GetSetStructFunction() {
   1517     return ObjCTypes.getCopyStructFn();
   1518   }
   1519   virtual llvm::Constant *GetGetStructFunction() {
   1520     return ObjCTypes.getCopyStructFn();
   1521   }
   1522   virtual llvm::Constant *GetCppAtomicObjectSetFunction() {
   1523     return ObjCTypes.getCppAtomicObjectFunction();
   1524   }
   1525   virtual llvm::Constant *GetCppAtomicObjectGetFunction() {
   1526     return ObjCTypes.getCppAtomicObjectFunction();
   1527   }
   1528 
   1529   virtual llvm::Constant *EnumerationMutationFunction() {
   1530     return ObjCTypes.getEnumerationMutationFn();
   1531   }
   1532 
   1533   virtual void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
   1534                            const ObjCAtTryStmt &S);
   1535   virtual void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
   1536                                     const ObjCAtSynchronizedStmt &S);
   1537   virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
   1538                              const ObjCAtThrowStmt &S,
   1539                              bool ClearInsertionPoint=true);
   1540   virtual llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
   1541                                          llvm::Value *AddrWeakObj);
   1542   virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
   1543                                   llvm::Value *src, llvm::Value *dst);
   1544   virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
   1545                                     llvm::Value *src, llvm::Value *dest,
   1546                                     bool threadlocal = false);
   1547   virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
   1548                                   llvm::Value *src, llvm::Value *dest,
   1549                                   llvm::Value *ivarOffset);
   1550   virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
   1551                                         llvm::Value *src, llvm::Value *dest);
   1552   virtual void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
   1553                                         llvm::Value *dest, llvm::Value *src,
   1554                                         llvm::Value *size);
   1555   virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
   1556                                       QualType ObjectTy,
   1557                                       llvm::Value *BaseValue,
   1558                                       const ObjCIvarDecl *Ivar,
   1559                                       unsigned CVRQualifiers);
   1560   virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
   1561                                       const ObjCInterfaceDecl *Interface,
   1562                                       const ObjCIvarDecl *Ivar);
   1563 };
   1564 
   1565 /// A helper class for performing the null-initialization of a return
   1566 /// value.
   1567 struct NullReturnState {
   1568   llvm::BasicBlock *NullBB;
   1569   NullReturnState() : NullBB(0) {}
   1570 
   1571   /// Perform a null-check of the given receiver.
   1572   void init(CodeGenFunction &CGF, llvm::Value *receiver) {
   1573     // Make blocks for the null-receiver and call edges.
   1574     NullBB = CGF.createBasicBlock("msgSend.null-receiver");
   1575     llvm::BasicBlock *callBB = CGF.createBasicBlock("msgSend.call");
   1576 
   1577     // Check for a null receiver and, if there is one, jump to the
   1578     // null-receiver block.  There's no point in trying to avoid it:
   1579     // we're always going to put *something* there, because otherwise
   1580     // we shouldn't have done this null-check in the first place.
   1581     llvm::Value *isNull = CGF.Builder.CreateIsNull(receiver);
   1582     CGF.Builder.CreateCondBr(isNull, NullBB, callBB);
   1583 
   1584     // Otherwise, start performing the call.
   1585     CGF.EmitBlock(callBB);
   1586   }
   1587 
   1588   /// Complete the null-return operation.  It is valid to call this
   1589   /// regardless of whether 'init' has been called.
   1590   RValue complete(CodeGenFunction &CGF, RValue result, QualType resultType,
   1591                   const CallArgList &CallArgs,
   1592                   const ObjCMethodDecl *Method) {
   1593     // If we never had to do a null-check, just use the raw result.
   1594     if (!NullBB) return result;
   1595 
   1596     // The continuation block.  This will be left null if we don't have an
   1597     // IP, which can happen if the method we're calling is marked noreturn.
   1598     llvm::BasicBlock *contBB = 0;
   1599 
   1600     // Finish the call path.
   1601     llvm::BasicBlock *callBB = CGF.Builder.GetInsertBlock();
   1602     if (callBB) {
   1603       contBB = CGF.createBasicBlock("msgSend.cont");
   1604       CGF.Builder.CreateBr(contBB);
   1605     }
   1606 
   1607     // Okay, start emitting the null-receiver block.
   1608     CGF.EmitBlock(NullBB);
   1609 
   1610     // Release any consumed arguments we've got.
   1611     if (Method) {
   1612       CallArgList::const_iterator I = CallArgs.begin();
   1613       for (ObjCMethodDecl::param_const_iterator i = Method->param_begin(),
   1614            e = Method->param_end(); i != e; ++i, ++I) {
   1615         const ParmVarDecl *ParamDecl = (*i);
   1616         if (ParamDecl->hasAttr<NSConsumedAttr>()) {
   1617           RValue RV = I->RV;
   1618           assert(RV.isScalar() &&
   1619                  "NullReturnState::complete - arg not on object");
   1620           CGF.EmitARCRelease(RV.getScalarVal(), ARCImpreciseLifetime);
   1621         }
   1622       }
   1623     }
   1624 
   1625     // The phi code below assumes that we haven't needed any control flow yet.
   1626     assert(CGF.Builder.GetInsertBlock() == NullBB);
   1627 
   1628     // If we've got a void return, just jump to the continuation block.
   1629     if (result.isScalar() && resultType->isVoidType()) {
   1630       // No jumps required if the message-send was noreturn.
   1631       if (contBB) CGF.EmitBlock(contBB);
   1632       return result;
   1633     }
   1634 
   1635     // If we've got a scalar return, build a phi.
   1636     if (result.isScalar()) {
   1637       // Derive the null-initialization value.
   1638       llvm::Constant *null = CGF.CGM.EmitNullConstant(resultType);
   1639 
   1640       // If no join is necessary, just flow out.
   1641       if (!contBB) return RValue::get(null);
   1642 
   1643       // Otherwise, build a phi.
   1644       CGF.EmitBlock(contBB);
   1645       llvm::PHINode *phi = CGF.Builder.CreatePHI(null->getType(), 2);
   1646       phi->addIncoming(result.getScalarVal(), callBB);
   1647       phi->addIncoming(null, NullBB);
   1648       return RValue::get(phi);
   1649     }
   1650 
   1651     // If we've got an aggregate return, null the buffer out.
   1652     // FIXME: maybe we should be doing things differently for all the
   1653     // cases where the ABI has us returning (1) non-agg values in
   1654     // memory or (2) agg values in registers.
   1655     if (result.isAggregate()) {
   1656       assert(result.isAggregate() && "null init of non-aggregate result?");
   1657       CGF.EmitNullInitialization(result.getAggregateAddr(), resultType);
   1658       if (contBB) CGF.EmitBlock(contBB);
   1659       return result;
   1660     }
   1661 
   1662     // Complex types.
   1663     CGF.EmitBlock(contBB);
   1664     CodeGenFunction::ComplexPairTy callResult = result.getComplexVal();
   1665 
   1666     // Find the scalar type and its zero value.
   1667     llvm::Type *scalarTy = callResult.first->getType();
   1668     llvm::Constant *scalarZero = llvm::Constant::getNullValue(scalarTy);
   1669 
   1670     // Build phis for both coordinates.
   1671     llvm::PHINode *real = CGF.Builder.CreatePHI(scalarTy, 2);
   1672     real->addIncoming(callResult.first, callBB);
   1673     real->addIncoming(scalarZero, NullBB);
   1674     llvm::PHINode *imag = CGF.Builder.CreatePHI(scalarTy, 2);
   1675     imag->addIncoming(callResult.second, callBB);
   1676     imag->addIncoming(scalarZero, NullBB);
   1677     return RValue::getComplex(real, imag);
   1678   }
   1679 };
   1680 
   1681 } // end anonymous namespace
   1682 
   1683 /* *** Helper Functions *** */
   1684 
   1685 /// getConstantGEP() - Help routine to construct simple GEPs.
   1686 static llvm::Constant *getConstantGEP(llvm::LLVMContext &VMContext,
   1687                                       llvm::Constant *C,
   1688                                       unsigned idx0,
   1689                                       unsigned idx1) {
   1690   llvm::Value *Idxs[] = {
   1691     llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx0),
   1692     llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx1)
   1693   };
   1694   return llvm::ConstantExpr::getGetElementPtr(C, Idxs);
   1695 }
   1696 
   1697 /// hasObjCExceptionAttribute - Return true if this class or any super
   1698 /// class has the __objc_exception__ attribute.
   1699 static bool hasObjCExceptionAttribute(ASTContext &Context,
   1700                                       const ObjCInterfaceDecl *OID) {
   1701   if (OID->hasAttr<ObjCExceptionAttr>())
   1702     return true;
   1703   if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
   1704     return hasObjCExceptionAttribute(Context, Super);
   1705   return false;
   1706 }
   1707 
   1708 /* *** CGObjCMac Public Interface *** */
   1709 
   1710 CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
   1711                                                     ObjCTypes(cgm) {
   1712   ObjCABI = 1;
   1713   EmitImageInfo();
   1714 }
   1715 
   1716 /// GetClass - Return a reference to the class for the given interface
   1717 /// decl.
   1718 llvm::Value *CGObjCMac::GetClass(CodeGenFunction &CGF,
   1719                                  const ObjCInterfaceDecl *ID) {
   1720   return EmitClassRef(CGF, ID);
   1721 }
   1722 
   1723 /// GetSelector - Return the pointer to the unique'd string for this selector.
   1724 llvm::Value *CGObjCMac::GetSelector(CodeGenFunction &CGF, Selector Sel,
   1725                                     bool lval) {
   1726   return EmitSelector(CGF, Sel, lval);
   1727 }
   1728 llvm::Value *CGObjCMac::GetSelector(CodeGenFunction &CGF, const ObjCMethodDecl
   1729                                     *Method) {
   1730   return EmitSelector(CGF, Method->getSelector());
   1731 }
   1732 
   1733 llvm::Constant *CGObjCMac::GetEHType(QualType T) {
   1734   if (T->isObjCIdType() ||
   1735       T->isObjCQualifiedIdType()) {
   1736     return CGM.GetAddrOfRTTIDescriptor(
   1737               CGM.getContext().getObjCIdRedefinitionType(), /*ForEH=*/true);
   1738   }
   1739   if (T->isObjCClassType() ||
   1740       T->isObjCQualifiedClassType()) {
   1741     return CGM.GetAddrOfRTTIDescriptor(
   1742              CGM.getContext().getObjCClassRedefinitionType(), /*ForEH=*/true);
   1743   }
   1744   if (T->isObjCObjectPointerType())
   1745     return CGM.GetAddrOfRTTIDescriptor(T,  /*ForEH=*/true);
   1746 
   1747   llvm_unreachable("asking for catch type for ObjC type in fragile runtime");
   1748 }
   1749 
   1750 /// Generate a constant CFString object.
   1751 /*
   1752   struct __builtin_CFString {
   1753   const int *isa; // point to __CFConstantStringClassReference
   1754   int flags;
   1755   const char *str;
   1756   long length;
   1757   };
   1758 */
   1759 
   1760 /// or Generate a constant NSString object.
   1761 /*
   1762    struct __builtin_NSString {
   1763      const int *isa; // point to __NSConstantStringClassReference
   1764      const char *str;
   1765      unsigned int length;
   1766    };
   1767 */
   1768 
   1769 llvm::Constant *CGObjCCommonMac::GenerateConstantString(
   1770   const StringLiteral *SL) {
   1771   return (CGM.getLangOpts().NoConstantCFStrings == 0 ?
   1772           CGM.GetAddrOfConstantCFString(SL) :
   1773           CGM.GetAddrOfConstantString(SL));
   1774 }
   1775 
   1776 enum {
   1777   kCFTaggedObjectID_Integer = (1 << 1) + 1
   1778 };
   1779 
   1780 /// Generates a message send where the super is the receiver.  This is
   1781 /// a message send to self with special delivery semantics indicating
   1782 /// which class's method should be called.
   1783 CodeGen::RValue
   1784 CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
   1785                                     ReturnValueSlot Return,
   1786                                     QualType ResultType,
   1787                                     Selector Sel,
   1788                                     const ObjCInterfaceDecl *Class,
   1789                                     bool isCategoryImpl,
   1790                                     llvm::Value *Receiver,
   1791                                     bool IsClassMessage,
   1792                                     const CodeGen::CallArgList &CallArgs,
   1793                                     const ObjCMethodDecl *Method) {
   1794   // Create and init a super structure; this is a (receiver, class)
   1795   // pair we will pass to objc_msgSendSuper.
   1796   llvm::Value *ObjCSuper =
   1797     CGF.CreateTempAlloca(ObjCTypes.SuperTy, "objc_super");
   1798   llvm::Value *ReceiverAsObject =
   1799     CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
   1800   CGF.Builder.CreateStore(ReceiverAsObject,
   1801                           CGF.Builder.CreateStructGEP(ObjCSuper, 0));
   1802 
   1803   // If this is a class message the metaclass is passed as the target.
   1804   llvm::Value *Target;
   1805   if (IsClassMessage) {
   1806     if (isCategoryImpl) {
   1807       // Message sent to 'super' in a class method defined in a category
   1808       // implementation requires an odd treatment.
   1809       // If we are in a class method, we must retrieve the
   1810       // _metaclass_ for the current class, pointed at by
   1811       // the class's "isa" pointer.  The following assumes that
   1812       // isa" is the first ivar in a class (which it must be).
   1813       Target = EmitClassRef(CGF, Class->getSuperClass());
   1814       Target = CGF.Builder.CreateStructGEP(Target, 0);
   1815       Target = CGF.Builder.CreateLoad(Target);
   1816     } else {
   1817       llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
   1818       llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
   1819       llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
   1820       Target = Super;
   1821     }
   1822   }
   1823   else if (isCategoryImpl)
   1824     Target = EmitClassRef(CGF, Class->getSuperClass());
   1825   else {
   1826     llvm::Value *ClassPtr = EmitSuperClassRef(Class);
   1827     ClassPtr = CGF.Builder.CreateStructGEP(ClassPtr, 1);
   1828     Target = CGF.Builder.CreateLoad(ClassPtr);
   1829   }
   1830   // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
   1831   // ObjCTypes types.
   1832   llvm::Type *ClassTy =
   1833     CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
   1834   Target = CGF.Builder.CreateBitCast(Target, ClassTy);
   1835   CGF.Builder.CreateStore(Target,
   1836                           CGF.Builder.CreateStructGEP(ObjCSuper, 1));
   1837   return EmitMessageSend(CGF, Return, ResultType,
   1838                          EmitSelector(CGF, Sel),
   1839                          ObjCSuper, ObjCTypes.SuperPtrCTy,
   1840                          true, CallArgs, Method, ObjCTypes);
   1841 }
   1842 
   1843 /// Generate code for a message send expression.
   1844 CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
   1845                                                ReturnValueSlot Return,
   1846                                                QualType ResultType,
   1847                                                Selector Sel,
   1848                                                llvm::Value *Receiver,
   1849                                                const CallArgList &CallArgs,
   1850                                                const ObjCInterfaceDecl *Class,
   1851                                                const ObjCMethodDecl *Method) {
   1852   return EmitMessageSend(CGF, Return, ResultType,
   1853                          EmitSelector(CGF, Sel),
   1854                          Receiver, CGF.getContext().getObjCIdType(),
   1855                          false, CallArgs, Method, ObjCTypes);
   1856 }
   1857 
   1858 CodeGen::RValue
   1859 CGObjCCommonMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
   1860                                  ReturnValueSlot Return,
   1861                                  QualType ResultType,
   1862                                  llvm::Value *Sel,
   1863                                  llvm::Value *Arg0,
   1864                                  QualType Arg0Ty,
   1865                                  bool IsSuper,
   1866                                  const CallArgList &CallArgs,
   1867                                  const ObjCMethodDecl *Method,
   1868                                  const ObjCCommonTypesHelper &ObjCTypes) {
   1869   CallArgList ActualArgs;
   1870   if (!IsSuper)
   1871     Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy);
   1872   ActualArgs.add(RValue::get(Arg0), Arg0Ty);
   1873   ActualArgs.add(RValue::get(Sel), CGF.getContext().getObjCSelType());
   1874   ActualArgs.addFrom(CallArgs);
   1875 
   1876   // If we're calling a method, use the formal signature.
   1877   MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
   1878 
   1879   if (Method)
   1880     assert(CGM.getContext().getCanonicalType(Method->getResultType()) ==
   1881            CGM.getContext().getCanonicalType(ResultType) &&
   1882            "Result type mismatch!");
   1883 
   1884   NullReturnState nullReturn;
   1885 
   1886   llvm::Constant *Fn = NULL;
   1887   if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
   1888     if (!IsSuper) nullReturn.init(CGF, Arg0);
   1889     Fn = (ObjCABI == 2) ?  ObjCTypes.getSendStretFn2(IsSuper)
   1890       : ObjCTypes.getSendStretFn(IsSuper);
   1891   } else if (CGM.ReturnTypeUsesFPRet(ResultType)) {
   1892     Fn = (ObjCABI == 2) ? ObjCTypes.getSendFpretFn2(IsSuper)
   1893       : ObjCTypes.getSendFpretFn(IsSuper);
   1894   } else if (CGM.ReturnTypeUsesFP2Ret(ResultType)) {
   1895     Fn = (ObjCABI == 2) ? ObjCTypes.getSendFp2RetFn2(IsSuper)
   1896       : ObjCTypes.getSendFp2retFn(IsSuper);
   1897   } else {
   1898     Fn = (ObjCABI == 2) ? ObjCTypes.getSendFn2(IsSuper)
   1899       : ObjCTypes.getSendFn(IsSuper);
   1900   }
   1901 
   1902   bool requiresnullCheck = false;
   1903   if (CGM.getLangOpts().ObjCAutoRefCount && Method)
   1904     for (ObjCMethodDecl::param_const_iterator i = Method->param_begin(),
   1905          e = Method->param_end(); i != e; ++i) {
   1906       const ParmVarDecl *ParamDecl = (*i);
   1907       if (ParamDecl->hasAttr<NSConsumedAttr>()) {
   1908         if (!nullReturn.NullBB)
   1909           nullReturn.init(CGF, Arg0);
   1910         requiresnullCheck = true;
   1911         break;
   1912       }
   1913     }
   1914 
   1915   Fn = llvm::ConstantExpr::getBitCast(Fn, MSI.MessengerType);
   1916   RValue rvalue = CGF.EmitCall(MSI.CallInfo, Fn, Return, ActualArgs);
   1917   return nullReturn.complete(CGF, rvalue, ResultType, CallArgs,
   1918                              requiresnullCheck ? Method : 0);
   1919 }
   1920 
   1921 static Qualifiers::GC GetGCAttrTypeForType(ASTContext &Ctx, QualType FQT) {
   1922   if (FQT.isObjCGCStrong())
   1923     return Qualifiers::Strong;
   1924 
   1925   if (FQT.isObjCGCWeak() || FQT.getObjCLifetime() == Qualifiers::OCL_Weak)
   1926     return Qualifiers::Weak;
   1927 
   1928   // check for __unsafe_unretained
   1929   if (FQT.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
   1930     return Qualifiers::GCNone;
   1931 
   1932   if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType())
   1933     return Qualifiers::Strong;
   1934 
   1935   if (const PointerType *PT = FQT->getAs<PointerType>())
   1936     return GetGCAttrTypeForType(Ctx, PT->getPointeeType());
   1937 
   1938   return Qualifiers::GCNone;
   1939 }
   1940 
   1941 llvm::Constant *CGObjCCommonMac::BuildGCBlockLayout(CodeGenModule &CGM,
   1942                                                 const CGBlockInfo &blockInfo) {
   1943 
   1944   llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
   1945   if (CGM.getLangOpts().getGC() == LangOptions::NonGC &&
   1946       !CGM.getLangOpts().ObjCAutoRefCount)
   1947     return nullPtr;
   1948 
   1949   bool hasUnion = false;
   1950   SkipIvars.clear();
   1951   IvarsInfo.clear();
   1952   unsigned WordSizeInBits = CGM.getContext().getTargetInfo().getPointerWidth(0);
   1953   unsigned ByteSizeInBits = CGM.getContext().getTargetInfo().getCharWidth();
   1954 
   1955   // __isa is the first field in block descriptor and must assume by runtime's
   1956   // convention that it is GC'able.
   1957   IvarsInfo.push_back(GC_IVAR(0, 1));
   1958 
   1959   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
   1960 
   1961   // Calculate the basic layout of the block structure.
   1962   const llvm::StructLayout *layout =
   1963     CGM.getDataLayout().getStructLayout(blockInfo.StructureType);
   1964 
   1965   // Ignore the optional 'this' capture: C++ objects are not assumed
   1966   // to be GC'ed.
   1967 
   1968   // Walk the captured variables.
   1969   for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
   1970          ce = blockDecl->capture_end(); ci != ce; ++ci) {
   1971     const VarDecl *variable = ci->getVariable();
   1972     QualType type = variable->getType();
   1973 
   1974     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
   1975 
   1976     // Ignore constant captures.
   1977     if (capture.isConstant()) continue;
   1978 
   1979     uint64_t fieldOffset = layout->getElementOffset(capture.getIndex());
   1980 
   1981     // __block variables are passed by their descriptor address.
   1982     if (ci->isByRef()) {
   1983       IvarsInfo.push_back(GC_IVAR(fieldOffset, /*size in words*/ 1));
   1984       continue;
   1985     }
   1986 
   1987     assert(!type->isArrayType() && "array variable should not be caught");
   1988     if (const RecordType *record = type->getAs<RecordType>()) {
   1989       BuildAggrIvarRecordLayout(record, fieldOffset, true, hasUnion);
   1990       continue;
   1991     }
   1992 
   1993     Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), type);
   1994     unsigned fieldSize = CGM.getContext().getTypeSize(type);
   1995 
   1996     if (GCAttr == Qualifiers::Strong)
   1997       IvarsInfo.push_back(GC_IVAR(fieldOffset,
   1998                                   fieldSize / WordSizeInBits));
   1999     else if (GCAttr == Qualifiers::GCNone || GCAttr == Qualifiers::Weak)
   2000       SkipIvars.push_back(GC_IVAR(fieldOffset,
   2001                                   fieldSize / ByteSizeInBits));
   2002   }
   2003 
   2004   if (IvarsInfo.empty())
   2005     return nullPtr;
   2006 
   2007   // Sort on byte position; captures might not be allocated in order,
   2008   // and unions can do funny things.
   2009   llvm::array_pod_sort(IvarsInfo.begin(), IvarsInfo.end());
   2010   llvm::array_pod_sort(SkipIvars.begin(), SkipIvars.end());
   2011 
   2012   std::string BitMap;
   2013   llvm::Constant *C = BuildIvarLayoutBitmap(BitMap);
   2014   if (CGM.getLangOpts().ObjCGCBitmapPrint) {
   2015     printf("\n block variable layout for block: ");
   2016     const unsigned char *s = (const unsigned char*)BitMap.c_str();
   2017     for (unsigned i = 0, e = BitMap.size(); i < e; i++)
   2018       if (!(s[i] & 0xf0))
   2019         printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
   2020       else
   2021         printf("0x%x%s",  s[i], s[i] != 0 ? ", " : "");
   2022     printf("\n");
   2023   }
   2024 
   2025   return C;
   2026 }
   2027 
   2028 /// getBlockCaptureLifetime - This routine returns life time of the captured
   2029 /// block variable for the purpose of block layout meta-data generation. FQT is
   2030 /// the type of the variable captured in the block.
   2031 Qualifiers::ObjCLifetime CGObjCCommonMac::getBlockCaptureLifetime(QualType FQT,
   2032                                                                   bool ByrefLayout) {
   2033   if (CGM.getLangOpts().ObjCAutoRefCount)
   2034     return FQT.getObjCLifetime();
   2035 
   2036   // MRR.
   2037   if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType())
   2038     return ByrefLayout ? Qualifiers::OCL_ExplicitNone : Qualifiers::OCL_Strong;
   2039 
   2040   return Qualifiers::OCL_None;
   2041 }
   2042 
   2043 void CGObjCCommonMac::UpdateRunSkipBlockVars(bool IsByref,
   2044                                              Qualifiers::ObjCLifetime LifeTime,
   2045                                              CharUnits FieldOffset,
   2046                                              CharUnits FieldSize) {
   2047   // __block variables are passed by their descriptor address.
   2048   if (IsByref)
   2049     RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_BYREF, FieldOffset,
   2050                                         FieldSize));
   2051   else if (LifeTime == Qualifiers::OCL_Strong)
   2052     RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_STRONG, FieldOffset,
   2053                                         FieldSize));
   2054   else if (LifeTime == Qualifiers::OCL_Weak)
   2055     RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_WEAK, FieldOffset,
   2056                                         FieldSize));
   2057   else if (LifeTime == Qualifiers::OCL_ExplicitNone)
   2058     RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_UNRETAINED, FieldOffset,
   2059                                         FieldSize));
   2060   else
   2061     RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_NON_OBJECT_BYTES,
   2062                                         FieldOffset,
   2063                                         FieldSize));
   2064 }
   2065 
   2066 void CGObjCCommonMac::BuildRCRecordLayout(const llvm::StructLayout *RecLayout,
   2067                                           const RecordDecl *RD,
   2068                                           ArrayRef<const FieldDecl*> RecFields,
   2069                                           CharUnits BytePos, bool &HasUnion,
   2070                                           bool ByrefLayout) {
   2071   bool IsUnion = (RD && RD->isUnion());
   2072   CharUnits MaxUnionSize = CharUnits::Zero();
   2073   const FieldDecl *MaxField = 0;
   2074   const FieldDecl *LastFieldBitfieldOrUnnamed = 0;
   2075   CharUnits MaxFieldOffset = CharUnits::Zero();
   2076   CharUnits LastBitfieldOrUnnamedOffset = CharUnits::Zero();
   2077 
   2078   if (RecFields.empty())
   2079     return;
   2080   unsigned ByteSizeInBits = CGM.getContext().getTargetInfo().getCharWidth();
   2081 
   2082   for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
   2083     const FieldDecl *Field = RecFields[i];
   2084     // Note that 'i' here is actually the field index inside RD of Field,
   2085     // although this dependency is hidden.
   2086     const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
   2087     CharUnits FieldOffset =
   2088       CGM.getContext().toCharUnitsFromBits(RL.getFieldOffset(i));
   2089 
   2090     // Skip over unnamed or bitfields
   2091     if (!Field->getIdentifier() || Field->isBitField()) {
   2092       LastFieldBitfieldOrUnnamed = Field;
   2093       LastBitfieldOrUnnamedOffset = FieldOffset;
   2094       continue;
   2095     }
   2096 
   2097     LastFieldBitfieldOrUnnamed = 0;
   2098     QualType FQT = Field->getType();
   2099     if (FQT->isRecordType() || FQT->isUnionType()) {
   2100       if (FQT->isUnionType())
   2101         HasUnion = true;
   2102 
   2103       BuildRCBlockVarRecordLayout(FQT->getAs<RecordType>(),
   2104                                   BytePos + FieldOffset, HasUnion);
   2105       continue;
   2106     }
   2107 
   2108     if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
   2109       const ConstantArrayType *CArray =
   2110         dyn_cast_or_null<ConstantArrayType>(Array);
   2111       uint64_t ElCount = CArray->getSize().getZExtValue();
   2112       assert(CArray && "only array with known element size is supported");
   2113       FQT = CArray->getElementType();
   2114       while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
   2115         const ConstantArrayType *CArray =
   2116           dyn_cast_or_null<ConstantArrayType>(Array);
   2117         ElCount *= CArray->getSize().getZExtValue();
   2118         FQT = CArray->getElementType();
   2119       }
   2120 
   2121       assert(!FQT->isUnionType() &&
   2122              "layout for array of unions not supported");
   2123       if (FQT->isRecordType() && ElCount) {
   2124         int OldIndex = RunSkipBlockVars.size() - 1;
   2125         const RecordType *RT = FQT->getAs<RecordType>();
   2126         BuildRCBlockVarRecordLayout(RT, BytePos + FieldOffset,
   2127                                     HasUnion);
   2128 
   2129         // Replicate layout information for each array element. Note that
   2130         // one element is already done.
   2131         uint64_t ElIx = 1;
   2132         for (int FirstIndex = RunSkipBlockVars.size() - 1 ;ElIx < ElCount; ElIx++) {
   2133           CharUnits Size = CGM.getContext().getTypeSizeInChars(RT);
   2134           for (int i = OldIndex+1; i <= FirstIndex; ++i)
   2135             RunSkipBlockVars.push_back(
   2136               RUN_SKIP(RunSkipBlockVars[i].opcode,
   2137               RunSkipBlockVars[i].block_var_bytepos + Size*ElIx,
   2138               RunSkipBlockVars[i].block_var_size));
   2139         }
   2140         continue;
   2141       }
   2142     }
   2143     CharUnits FieldSize = CGM.getContext().getTypeSizeInChars(Field->getType());
   2144     if (IsUnion) {
   2145       CharUnits UnionIvarSize = FieldSize;
   2146       if (UnionIvarSize > MaxUnionSize) {
   2147         MaxUnionSize = UnionIvarSize;
   2148         MaxField = Field;
   2149         MaxFieldOffset = FieldOffset;
   2150       }
   2151     } else {
   2152       UpdateRunSkipBlockVars(false,
   2153                              getBlockCaptureLifetime(FQT, ByrefLayout),
   2154                              BytePos + FieldOffset,
   2155                              FieldSize);
   2156     }
   2157   }
   2158 
   2159   if (LastFieldBitfieldOrUnnamed) {
   2160     if (LastFieldBitfieldOrUnnamed->isBitField()) {
   2161       // Last field was a bitfield. Must update the info.
   2162       uint64_t BitFieldSize
   2163         = LastFieldBitfieldOrUnnamed->getBitWidthValue(CGM.getContext());
   2164       unsigned UnsSize = (BitFieldSize / ByteSizeInBits) +
   2165                         ((BitFieldSize % ByteSizeInBits) != 0);
   2166       CharUnits Size = CharUnits::fromQuantity(UnsSize);
   2167       Size += LastBitfieldOrUnnamedOffset;
   2168       UpdateRunSkipBlockVars(false,
   2169                              getBlockCaptureLifetime(LastFieldBitfieldOrUnnamed->getType(),
   2170                                                      ByrefLayout),
   2171                              BytePos + LastBitfieldOrUnnamedOffset,
   2172                              Size);
   2173     } else {
   2174       assert(!LastFieldBitfieldOrUnnamed->getIdentifier() &&"Expected unnamed");
   2175       // Last field was unnamed. Must update skip info.
   2176       CharUnits FieldSize
   2177         = CGM.getContext().getTypeSizeInChars(LastFieldBitfieldOrUnnamed->getType());
   2178       UpdateRunSkipBlockVars(false,
   2179                              getBlockCaptureLifetime(LastFieldBitfieldOrUnnamed->getType(),
   2180                                                      ByrefLayout),
   2181                              BytePos + LastBitfieldOrUnnamedOffset,
   2182                              FieldSize);
   2183     }
   2184   }
   2185 
   2186   if (MaxField)
   2187     UpdateRunSkipBlockVars(false,
   2188                            getBlockCaptureLifetime(MaxField->getType(), ByrefLayout),
   2189                            BytePos + MaxFieldOffset,
   2190                            MaxUnionSize);
   2191 }
   2192 
   2193 void CGObjCCommonMac::BuildRCBlockVarRecordLayout(const RecordType *RT,
   2194                                                   CharUnits BytePos,
   2195                                                   bool &HasUnion,
   2196                                                   bool ByrefLayout) {
   2197   const RecordDecl *RD = RT->getDecl();
   2198   SmallVector<const FieldDecl*, 16> Fields;
   2199   for (RecordDecl::field_iterator i = RD->field_begin(),
   2200        e = RD->field_end(); i != e; ++i)
   2201     Fields.push_back(*i);
   2202   llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
   2203   const llvm::StructLayout *RecLayout =
   2204     CGM.getDataLayout().getStructLayout(cast<llvm::StructType>(Ty));
   2205 
   2206   BuildRCRecordLayout(RecLayout, RD, Fields, BytePos, HasUnion, ByrefLayout);
   2207 }
   2208 
   2209 /// InlineLayoutInstruction - This routine produce an inline instruction for the
   2210 /// block variable layout if it can. If not, it returns 0. Rules are as follow:
   2211 /// If ((uintptr_t) layout) < (1 << 12), the layout is inline. In the 64bit world,
   2212 /// an inline layout of value 0x0000000000000xyz is interpreted as follows:
   2213 /// x captured object pointers of BLOCK_LAYOUT_STRONG. Followed by
   2214 /// y captured object of BLOCK_LAYOUT_BYREF. Followed by
   2215 /// z captured object of BLOCK_LAYOUT_WEAK. If any of the above is missing, zero
   2216 /// replaces it. For example, 0x00000x00 means x BLOCK_LAYOUT_STRONG and no
   2217 /// BLOCK_LAYOUT_BYREF and no BLOCK_LAYOUT_WEAK objects are captured.
   2218 uint64_t CGObjCCommonMac::InlineLayoutInstruction(
   2219                                     SmallVectorImpl<unsigned char> &Layout) {
   2220   uint64_t Result = 0;
   2221   if (Layout.size() <= 3) {
   2222     unsigned size = Layout.size();
   2223     unsigned strong_word_count = 0, byref_word_count=0, weak_word_count=0;
   2224     unsigned char inst;
   2225     enum BLOCK_LAYOUT_OPCODE opcode ;
   2226     switch (size) {
   2227       case 3:
   2228         inst = Layout[0];
   2229         opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
   2230         if (opcode == BLOCK_LAYOUT_STRONG)
   2231           strong_word_count = (inst & 0xF)+1;
   2232         else
   2233           return 0;
   2234         inst = Layout[1];
   2235         opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
   2236         if (opcode == BLOCK_LAYOUT_BYREF)
   2237           byref_word_count = (inst & 0xF)+1;
   2238         else
   2239           return 0;
   2240         inst = Layout[2];
   2241         opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
   2242         if (opcode == BLOCK_LAYOUT_WEAK)
   2243           weak_word_count = (inst & 0xF)+1;
   2244         else
   2245           return 0;
   2246         break;
   2247 
   2248       case 2:
   2249         inst = Layout[0];
   2250         opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
   2251         if (opcode == BLOCK_LAYOUT_STRONG) {
   2252           strong_word_count = (inst & 0xF)+1;
   2253           inst = Layout[1];
   2254           opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
   2255           if (opcode == BLOCK_LAYOUT_BYREF)
   2256             byref_word_count = (inst & 0xF)+1;
   2257           else if (opcode == BLOCK_LAYOUT_WEAK)
   2258             weak_word_count = (inst & 0xF)+1;
   2259           else
   2260             return 0;
   2261         }
   2262         else if (opcode == BLOCK_LAYOUT_BYREF) {
   2263           byref_word_count = (inst & 0xF)+1;
   2264           inst = Layout[1];
   2265           opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
   2266           if (opcode == BLOCK_LAYOUT_WEAK)
   2267             weak_word_count = (inst & 0xF)+1;
   2268           else
   2269             return 0;
   2270         }
   2271         else
   2272           return 0;
   2273         break;
   2274 
   2275       case 1:
   2276         inst = Layout[0];
   2277         opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
   2278         if (opcode == BLOCK_LAYOUT_STRONG)
   2279           strong_word_count = (inst & 0xF)+1;
   2280         else if (opcode == BLOCK_LAYOUT_BYREF)
   2281           byref_word_count = (inst & 0xF)+1;
   2282         else if (opcode == BLOCK_LAYOUT_WEAK)
   2283           weak_word_count = (inst & 0xF)+1;
   2284         else
   2285           return 0;
   2286         break;
   2287 
   2288       default:
   2289         return 0;
   2290     }
   2291 
   2292     // Cannot inline when any of the word counts is 15. Because this is one less
   2293     // than the actual work count (so 15 means 16 actual word counts),
   2294     // and we can only display 0 thru 15 word counts.
   2295     if (strong_word_count == 16 || byref_word_count == 16 || weak_word_count == 16)
   2296       return 0;
   2297 
   2298     unsigned count =
   2299       (strong_word_count != 0) + (byref_word_count != 0) + (weak_word_count != 0);
   2300 
   2301     if (size == count) {
   2302       if (strong_word_count)
   2303         Result = strong_word_count;
   2304       Result <<= 4;
   2305       if (byref_word_count)
   2306         Result += byref_word_count;
   2307       Result <<= 4;
   2308       if (weak_word_count)
   2309         Result += weak_word_count;
   2310     }
   2311   }
   2312   return Result;
   2313 }
   2314 
   2315 llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) {
   2316   llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
   2317   if (RunSkipBlockVars.empty())
   2318     return nullPtr;
   2319   unsigned WordSizeInBits = CGM.getContext().getTargetInfo().getPointerWidth(0);
   2320   unsigned ByteSizeInBits = CGM.getContext().getTargetInfo().getCharWidth();
   2321   unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits;
   2322 
   2323   // Sort on byte position; captures might not be allocated in order,
   2324   // and unions can do funny things.
   2325   llvm::array_pod_sort(RunSkipBlockVars.begin(), RunSkipBlockVars.end());
   2326   SmallVector<unsigned char, 16> Layout;
   2327 
   2328   unsigned size = RunSkipBlockVars.size();
   2329   for (unsigned i = 0; i < size; i++) {
   2330     enum BLOCK_LAYOUT_OPCODE opcode = RunSkipBlockVars[i].opcode;
   2331     CharUnits start_byte_pos = RunSkipBlockVars[i].block_var_bytepos;
   2332     CharUnits end_byte_pos = start_byte_pos;
   2333     unsigned j = i+1;
   2334     while (j < size) {
   2335       if (opcode == RunSkipBlockVars[j].opcode) {
   2336         end_byte_pos = RunSkipBlockVars[j++].block_var_bytepos;
   2337         i++;
   2338       }
   2339       else
   2340         break;
   2341     }
   2342     CharUnits size_in_bytes =
   2343     end_byte_pos - start_byte_pos + RunSkipBlockVars[j-1].block_var_size;
   2344     if (j < size) {
   2345       CharUnits gap =
   2346       RunSkipBlockVars[j].block_var_bytepos -
   2347       RunSkipBlockVars[j-1].block_var_bytepos - RunSkipBlockVars[j-1].block_var_size;
   2348       size_in_bytes += gap;
   2349     }
   2350     CharUnits residue_in_bytes = CharUnits::Zero();
   2351     if (opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES) {
   2352       residue_in_bytes = size_in_bytes % WordSizeInBytes;
   2353       size_in_bytes -= residue_in_bytes;
   2354       opcode = BLOCK_LAYOUT_NON_OBJECT_WORDS;
   2355     }
   2356 
   2357     unsigned size_in_words = size_in_bytes.getQuantity() / WordSizeInBytes;
   2358     while (size_in_words >= 16) {
   2359       // Note that value in imm. is one less that the actual
   2360       // value. So, 0xf means 16 words follow!
   2361       unsigned char inst = (opcode << 4) | 0xf;
   2362       Layout.push_back(inst);
   2363       size_in_words -= 16;
   2364     }
   2365     if (size_in_words > 0) {
   2366       // Note that value in imm. is one less that the actual
   2367       // value. So, we subtract 1 away!
   2368       unsigned char inst = (opcode << 4) | (size_in_words-1);
   2369       Layout.push_back(inst);
   2370     }
   2371     if (residue_in_bytes > CharUnits::Zero()) {
   2372       unsigned char inst =
   2373       (BLOCK_LAYOUT_NON_OBJECT_BYTES << 4) | (residue_in_bytes.getQuantity()-1);
   2374       Layout.push_back(inst);
   2375     }
   2376   }
   2377 
   2378   int e = Layout.size()-1;
   2379   while (e >= 0) {
   2380     unsigned char inst = Layout[e--];
   2381     enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
   2382     if (opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES || opcode == BLOCK_LAYOUT_NON_OBJECT_WORDS)
   2383       Layout.pop_back();
   2384     else
   2385       break;
   2386   }
   2387 
   2388   uint64_t Result = InlineLayoutInstruction(Layout);
   2389   if (Result != 0) {
   2390     // Block variable layout instruction has been inlined.
   2391     if (CGM.getLangOpts().ObjCGCBitmapPrint) {
   2392       if (ComputeByrefLayout)
   2393         printf("\n Inline instruction for BYREF variable layout: ");
   2394       else
   2395         printf("\n Inline instruction for block variable layout: ");
   2396       printf("0x0%llx\n", (unsigned long long)Result);
   2397     }
   2398     if (WordSizeInBytes == 8) {
   2399       const llvm::APInt Instruction(64, Result);
   2400       return llvm::Constant::getIntegerValue(CGM.Int64Ty, Instruction);
   2401     }
   2402     else {
   2403       const llvm::APInt Instruction(32, Result);
   2404       return llvm::Constant::getIntegerValue(CGM.Int32Ty, Instruction);
   2405     }
   2406   }
   2407 
   2408   unsigned char inst = (BLOCK_LAYOUT_OPERATOR << 4) | 0;
   2409   Layout.push_back(inst);
   2410   std::string BitMap;
   2411   for (unsigned i = 0, e = Layout.size(); i != e; i++)
   2412     BitMap += Layout[i];
   2413 
   2414   if (CGM.getLangOpts().ObjCGCBitmapPrint) {
   2415     if (ComputeByrefLayout)
   2416       printf("\n BYREF variable layout: ");
   2417     else
   2418       printf("\n block variable layout: ");
   2419     for (unsigned i = 0, e = BitMap.size(); i != e; i++) {
   2420       unsigned char inst = BitMap[i];
   2421       enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
   2422       unsigned delta = 1;
   2423       switch (opcode) {
   2424         case BLOCK_LAYOUT_OPERATOR:
   2425           printf("BL_OPERATOR:");
   2426           delta = 0;
   2427           break;
   2428         case BLOCK_LAYOUT_NON_OBJECT_BYTES:
   2429           printf("BL_NON_OBJECT_BYTES:");
   2430           break;
   2431         case BLOCK_LAYOUT_NON_OBJECT_WORDS:
   2432           printf("BL_NON_OBJECT_WORD:");
   2433           break;
   2434         case BLOCK_LAYOUT_STRONG:
   2435           printf("BL_STRONG:");
   2436           break;
   2437         case BLOCK_LAYOUT_BYREF:
   2438           printf("BL_BYREF:");
   2439           break;
   2440         case BLOCK_LAYOUT_WEAK:
   2441           printf("BL_WEAK:");
   2442           break;
   2443         case BLOCK_LAYOUT_UNRETAINED:
   2444           printf("BL_UNRETAINED:");
   2445           break;
   2446       }
   2447       // Actual value of word count is one more that what is in the imm.
   2448       // field of the instruction
   2449       printf("%d", (inst & 0xf) + delta);
   2450       if (i < e-1)
   2451         printf(", ");
   2452       else
   2453         printf("\n");
   2454     }
   2455   }
   2456 
   2457   llvm::GlobalVariable * Entry =
   2458   CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
   2459                     llvm::ConstantDataArray::getString(VMContext, BitMap,false),
   2460                     "__TEXT,__objc_classname,cstring_literals", 1, true);
   2461   return getConstantGEP(VMContext, Entry, 0, 0);
   2462 }
   2463 
   2464 llvm::Constant *CGObjCCommonMac::BuildRCBlockLayout(CodeGenModule &CGM,
   2465                                                     const CGBlockInfo &blockInfo) {
   2466   assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);
   2467 
   2468   RunSkipBlockVars.clear();
   2469   bool hasUnion = false;
   2470 
   2471   unsigned WordSizeInBits = CGM.getContext().getTargetInfo().getPointerWidth(0);
   2472   unsigned ByteSizeInBits = CGM.getContext().getTargetInfo().getCharWidth();
   2473   unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits;
   2474 
   2475   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
   2476 
   2477   // Calculate the basic layout of the block structure.
   2478   const llvm::StructLayout *layout =
   2479   CGM.getDataLayout().getStructLayout(blockInfo.StructureType);
   2480 
   2481   // Ignore the optional 'this' capture: C++ objects are not assumed
   2482   // to be GC'ed.
   2483   if (blockInfo.BlockHeaderForcedGapSize != CharUnits::Zero())
   2484     UpdateRunSkipBlockVars(false, Qualifiers::OCL_None,
   2485                            blockInfo.BlockHeaderForcedGapOffset,
   2486                            blockInfo.BlockHeaderForcedGapSize);
   2487   // Walk the captured variables.
   2488   for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
   2489        ce = blockDecl->capture_end(); ci != ce; ++ci) {
   2490     const VarDecl *variable = ci->getVariable();
   2491     QualType type = variable->getType();
   2492 
   2493     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
   2494 
   2495     // Ignore constant captures.
   2496     if (capture.isConstant()) continue;
   2497 
   2498     CharUnits fieldOffset =
   2499        CharUnits::fromQuantity(layout->getElementOffset(capture.getIndex()));
   2500 
   2501     assert(!type->isArrayType() && "array variable should not be caught");
   2502     if (!ci->isByRef())
   2503       if (const RecordType *record = type->getAs<RecordType>()) {
   2504         BuildRCBlockVarRecordLayout(record, fieldOffset, hasUnion);
   2505         continue;
   2506       }
   2507     CharUnits fieldSize;
   2508     if (ci->isByRef())
   2509       fieldSize = CharUnits::fromQuantity(WordSizeInBytes);
   2510     else
   2511       fieldSize = CGM.getContext().getTypeSizeInChars(type);
   2512     UpdateRunSkipBlockVars(ci->isByRef(), getBlockCaptureLifetime(type, false),
   2513                            fieldOffset, fieldSize);
   2514   }
   2515   return getBitmapBlockLayout(false);
   2516 }
   2517 
   2518 
   2519 llvm::Constant *CGObjCCommonMac::BuildByrefLayout(CodeGen::CodeGenModule &CGM,
   2520                                                   QualType T) {
   2521   assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);
   2522   assert(!T->isArrayType() && "__block array variable should not be caught");
   2523   CharUnits fieldOffset;
   2524   RunSkipBlockVars.clear();
   2525   bool hasUnion = false;
   2526   if (const RecordType *record = T->getAs<RecordType>()) {
   2527     BuildRCBlockVarRecordLayout(record, fieldOffset, hasUnion, true /*ByrefLayout */);
   2528     llvm::Constant *Result = getBitmapBlockLayout(true);
   2529     return Result;
   2530   }
   2531   llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
   2532   return nullPtr;
   2533 }
   2534 
   2535 llvm::Value *CGObjCMac::GenerateProtocolRef(CodeGenFunction &CGF,
   2536                                             const ObjCProtocolDecl *PD) {
   2537   // FIXME: I don't understand why gcc generates this, or where it is
   2538   // resolved. Investigate. Its also wasteful to look this up over and over.
   2539   LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
   2540 
   2541   return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
   2542                                         ObjCTypes.getExternalProtocolPtrTy());
   2543 }
   2544 
   2545 void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
   2546   // FIXME: We shouldn't need this, the protocol decl should contain enough
   2547   // information to tell us whether this was a declaration or a definition.
   2548   DefinedProtocols.insert(PD->getIdentifier());
   2549 
   2550   // If we have generated a forward reference to this protocol, emit
   2551   // it now. Otherwise do nothing, the protocol objects are lazily
   2552   // emitted.
   2553   if (Protocols.count(PD->getIdentifier()))
   2554     GetOrEmitProtocol(PD);
   2555 }
   2556 
   2557 llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
   2558   if (DefinedProtocols.count(PD->getIdentifier()))
   2559     return GetOrEmitProtocol(PD);
   2560 
   2561   return GetOrEmitProtocolRef(PD);
   2562 }
   2563 
   2564 /*
   2565 // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
   2566 struct _objc_protocol {
   2567 struct _objc_protocol_extension *isa;
   2568 char *protocol_name;
   2569 struct _objc_protocol_list *protocol_list;
   2570 struct _objc__method_prototype_list *instance_methods;
   2571 struct _objc__method_prototype_list *class_methods
   2572 };
   2573 
   2574 See EmitProtocolExtension().
   2575 */
   2576 llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
   2577   llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()];
   2578 
   2579   // Early exit if a defining object has already been generated.
   2580   if (Entry && Entry->hasInitializer())
   2581     return Entry;
   2582 
   2583   // Use the protocol definition, if there is one.
   2584   if (const ObjCProtocolDecl *Def = PD->getDefinition())
   2585     PD = Def;
   2586 
   2587   // FIXME: I don't understand why gcc generates this, or where it is
   2588   // resolved. Investigate. Its also wasteful to look this up over and over.
   2589   LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
   2590 
   2591   // Construct method lists.
   2592   std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
   2593   std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
   2594   std::vector<llvm::Constant*> MethodTypesExt, OptMethodTypesExt;
   2595   for (ObjCProtocolDecl::instmeth_iterator
   2596          i = PD->instmeth_begin(), e = PD->instmeth_end(); i != e; ++i) {
   2597     ObjCMethodDecl *MD = *i;
   2598     llvm::Constant *C = GetMethodDescriptionConstant(MD);
   2599     if (!C)
   2600       return GetOrEmitProtocolRef(PD);
   2601 
   2602     if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
   2603       OptInstanceMethods.push_back(C);
   2604       OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
   2605     } else {
   2606       InstanceMethods.push_back(C);
   2607       MethodTypesExt.push_back(GetMethodVarType(MD, true));
   2608     }
   2609   }
   2610 
   2611   for (ObjCProtocolDecl::classmeth_iterator
   2612          i = PD->classmeth_begin(), e = PD->classmeth_end(); i != e; ++i) {
   2613     ObjCMethodDecl *MD = *i;
   2614     llvm::Constant *C = GetMethodDescriptionConstant(MD);
   2615     if (!C)
   2616       return GetOrEmitProtocolRef(PD);
   2617 
   2618     if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
   2619       OptClassMethods.push_back(C);
   2620       OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
   2621     } else {
   2622       ClassMethods.push_back(C);
   2623       MethodTypesExt.push_back(GetMethodVarType(MD, true));
   2624     }
   2625   }
   2626 
   2627   MethodTypesExt.insert(MethodTypesExt.end(),
   2628                         OptMethodTypesExt.begin(), OptMethodTypesExt.end());
   2629 
   2630   llvm::Constant *Values[] = {
   2631     EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods,
   2632                           MethodTypesExt),
   2633     GetClassName(PD->getIdentifier()),
   2634     EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getName(),
   2635                      PD->protocol_begin(),
   2636                      PD->protocol_end()),
   2637     EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_" + PD->getName(),
   2638                        "__OBJC,__cat_inst_meth,regular,no_dead_strip",
   2639                        InstanceMethods),
   2640     EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_" + PD->getName(),
   2641                        "__OBJC,__cat_cls_meth,regular,no_dead_strip",
   2642                        ClassMethods)
   2643   };
   2644   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
   2645                                                    Values);
   2646 
   2647   if (Entry) {
   2648     // Already created, fix the linkage and update the initializer.
   2649     Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
   2650     Entry->setInitializer(Init);
   2651   } else {
   2652     Entry =
   2653       new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy, false,
   2654                                llvm::GlobalValue::InternalLinkage,
   2655                                Init,
   2656                                "\01L_OBJC_PROTOCOL_" + PD->getName());
   2657     Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
   2658     // FIXME: Is this necessary? Why only for protocol?
   2659     Entry->setAlignment(4);
   2660 
   2661     Protocols[PD->getIdentifier()] = Entry;
   2662   }
   2663   CGM.AddUsedGlobal(Entry);
   2664 
   2665   return Entry;
   2666 }
   2667 
   2668 llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
   2669   llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
   2670 
   2671   if (!Entry) {
   2672     // We use the initializer as a marker of whether this is a forward
   2673     // reference or not. At module finalization we add the empty
   2674     // contents for protocols which were referenced but never defined.
   2675     Entry =
   2676       new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy, false,
   2677                                llvm::GlobalValue::ExternalLinkage,
   2678                                0,
   2679                                "\01L_OBJC_PROTOCOL_" + PD->getName());
   2680     Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
   2681     // FIXME: Is this necessary? Why only for protocol?
   2682     Entry->setAlignment(4);
   2683   }
   2684 
   2685   return Entry;
   2686 }
   2687 
   2688 /*
   2689   struct _objc_protocol_extension {
   2690   uint32_t size;
   2691   struct objc_method_description_list *optional_instance_methods;
   2692   struct objc_method_description_list *optional_class_methods;
   2693   struct objc_property_list *instance_properties;
   2694   const char ** extendedMethodTypes;
   2695   };
   2696 */
   2697 llvm::Constant *
   2698 CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
   2699                                  ArrayRef<llvm::Constant*> OptInstanceMethods,
   2700                                  ArrayRef<llvm::Constant*> OptClassMethods,
   2701                                  ArrayRef<llvm::Constant*> MethodTypesExt) {
   2702   uint64_t Size =
   2703     CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolExtensionTy);
   2704   llvm::Constant *Values[] = {
   2705     llvm::ConstantInt::get(ObjCTypes.IntTy, Size),
   2706     EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
   2707                        + PD->getName(),
   2708                        "__OBJC,__cat_inst_meth,regular,no_dead_strip",
   2709                        OptInstanceMethods),
   2710     EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_" + PD->getName(),
   2711                        "__OBJC,__cat_cls_meth,regular,no_dead_strip",
   2712                        OptClassMethods),
   2713     EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" + PD->getName(), 0, PD,
   2714                      ObjCTypes),
   2715     EmitProtocolMethodTypes("\01L_OBJC_PROTOCOL_METHOD_TYPES_" + PD->getName(),
   2716                             MethodTypesExt, ObjCTypes)
   2717   };
   2718 
   2719   // Return null if no extension bits are used.
   2720   if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
   2721       Values[3]->isNullValue() && Values[4]->isNullValue())
   2722     return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
   2723 
   2724   llvm::Constant *Init =
   2725     llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
   2726 
   2727   // No special section, but goes in llvm.used
   2728   return CreateMetadataVar("\01L_OBJC_PROTOCOLEXT_" + PD->getName(),
   2729                            Init,
   2730                            0, 0, true);
   2731 }
   2732 
   2733 /*
   2734   struct objc_protocol_list {
   2735     struct objc_protocol_list *next;
   2736     long count;
   2737     Protocol *list[];
   2738   };
   2739 */
   2740 llvm::Constant *
   2741 CGObjCMac::EmitProtocolList(Twine Name,
   2742                             ObjCProtocolDecl::protocol_iterator begin,
   2743                             ObjCProtocolDecl::protocol_iterator end) {
   2744   SmallVector<llvm::Constant *, 16> ProtocolRefs;
   2745 
   2746   for (; begin != end; ++begin)
   2747     ProtocolRefs.push_back(GetProtocolRef(*begin));
   2748 
   2749   // Just return null for empty protocol lists
   2750   if (ProtocolRefs.empty())
   2751     return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
   2752 
   2753   // This list is null terminated.
   2754   ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
   2755 
   2756   llvm::Constant *Values[3];
   2757   // This field is only used by the runtime.
   2758   Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
   2759   Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy,
   2760                                      ProtocolRefs.size() - 1);
   2761   Values[2] =
   2762     llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
   2763                                                   ProtocolRefs.size()),
   2764                              ProtocolRefs);
   2765 
   2766   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
   2767   llvm::GlobalVariable *GV =
   2768     CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
   2769                       4, false);
   2770   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
   2771 }
   2772 
   2773 void CGObjCCommonMac::
   2774 PushProtocolProperties(llvm::SmallPtrSet<const IdentifierInfo*,16> &PropertySet,
   2775                        SmallVectorImpl<llvm::Constant *> &Properties,
   2776                        const Decl *Container,
   2777                        const ObjCProtocolDecl *PROTO,
   2778                        const ObjCCommonTypesHelper &ObjCTypes) {
   2779   for (ObjCProtocolDecl::protocol_iterator P = PROTO->protocol_begin(),
   2780          E = PROTO->protocol_end(); P != E; ++P)
   2781     PushProtocolProperties(PropertySet, Properties, Container, (*P), ObjCTypes);
   2782   for (ObjCContainerDecl::prop_iterator I = PROTO->prop_begin(),
   2783        E = PROTO->prop_end(); I != E; ++I) {
   2784     const ObjCPropertyDecl *PD = *I;
   2785     if (!PropertySet.insert(PD->getIdentifier()))
   2786       continue;
   2787     llvm::Constant *Prop[] = {
   2788       GetPropertyName(PD->getIdentifier()),
   2789       GetPropertyTypeString(PD, Container)
   2790     };
   2791     Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy, Prop));
   2792   }
   2793 }
   2794 
   2795 /*
   2796   struct _objc_property {
   2797     const char * const name;
   2798     const char * const attributes;
   2799   };
   2800 
   2801   struct _objc_property_list {
   2802     uint32_t entsize; // sizeof (struct _objc_property)
   2803     uint32_t prop_count;
   2804     struct _objc_property[prop_count];
   2805   };
   2806 */
   2807 llvm::Constant *CGObjCCommonMac::EmitPropertyList(Twine Name,
   2808                                        const Decl *Container,
   2809                                        const ObjCContainerDecl *OCD,
   2810                                        const ObjCCommonTypesHelper &ObjCTypes) {
   2811   SmallVector<llvm::Constant *, 16> Properties;
   2812   llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
   2813   for (ObjCContainerDecl::prop_iterator I = OCD->prop_begin(),
   2814          E = OCD->prop_end(); I != E; ++I) {
   2815     const ObjCPropertyDecl *PD = *I;
   2816     PropertySet.insert(PD->getIdentifier());
   2817     llvm::Constant *Prop[] = {
   2818       GetPropertyName(PD->getIdentifier()),
   2819       GetPropertyTypeString(PD, Container)
   2820     };
   2821     Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
   2822                                                    Prop));
   2823   }
   2824   if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD)) {
   2825     for (ObjCInterfaceDecl::all_protocol_iterator
   2826          P = OID->all_referenced_protocol_begin(),
   2827          E = OID->all_referenced_protocol_end(); P != E; ++P)
   2828       PushProtocolProperties(PropertySet, Properties, Container, (*P),
   2829                              ObjCTypes);
   2830   }
   2831   else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD)) {
   2832     for (ObjCCategoryDecl::protocol_iterator P = CD->protocol_begin(),
   2833          E = CD->protocol_end(); P != E; ++P)
   2834       PushProtocolProperties(PropertySet, Properties, Container, (*P),
   2835                              ObjCTypes);
   2836   }
   2837 
   2838   // Return null for empty list.
   2839   if (Properties.empty())
   2840     return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
   2841 
   2842   unsigned PropertySize =
   2843     CGM.getDataLayout().getTypeAllocSize(ObjCTypes.PropertyTy);
   2844   llvm::Constant *Values[3];
   2845   Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
   2846   Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
   2847   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
   2848                                              Properties.size());
   2849   Values[2] = llvm::ConstantArray::get(AT, Properties);
   2850   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
   2851 
   2852   llvm::GlobalVariable *GV =
   2853     CreateMetadataVar(Name, Init,
   2854                       (ObjCABI == 2) ? "__DATA, __objc_const" :
   2855                       "__OBJC,__property,regular,no_dead_strip",
   2856                       (ObjCABI == 2) ? 8 : 4,
   2857                       true);
   2858   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
   2859 }
   2860 
   2861 llvm::Constant *
   2862 CGObjCCommonMac::EmitProtocolMethodTypes(Twine Name,
   2863                                          ArrayRef<llvm::Constant*> MethodTypes,
   2864                                          const ObjCCommonTypesHelper &ObjCTypes) {
   2865   // Return null for empty list.
   2866   if (MethodTypes.empty())
   2867     return llvm::Constant::getNullValue(ObjCTypes.Int8PtrPtrTy);
   2868 
   2869   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
   2870                                              MethodTypes.size());
   2871   llvm::Constant *Init = llvm::ConstantArray::get(AT, MethodTypes);
   2872 
   2873   llvm::GlobalVariable *GV =
   2874     CreateMetadataVar(Name, Init,
   2875                       (ObjCABI == 2) ? "__DATA, __objc_const" : 0,
   2876                       (ObjCABI == 2) ? 8 : 4,
   2877                       true);
   2878   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.Int8PtrPtrTy);
   2879 }
   2880 
   2881 /*
   2882   struct objc_method_description_list {
   2883   int count;
   2884   struct objc_method_description list[];
   2885   };
   2886 */
   2887 llvm::Constant *
   2888 CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
   2889   llvm::Constant *Desc[] = {
   2890     llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
   2891                                    ObjCTypes.SelectorPtrTy),
   2892     GetMethodVarType(MD)
   2893   };
   2894   if (!Desc[1])
   2895     return 0;
   2896 
   2897   return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
   2898                                    Desc);
   2899 }
   2900 
   2901 llvm::Constant *
   2902 CGObjCMac::EmitMethodDescList(Twine Name, const char *Section,
   2903                               ArrayRef<llvm::Constant*> Methods) {
   2904   // Return null for empty list.
   2905   if (Methods.empty())
   2906     return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
   2907 
   2908   llvm::Constant *Values[2];
   2909   Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
   2910   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
   2911                                              Methods.size());
   2912   Values[1] = llvm::ConstantArray::get(AT, Methods);
   2913   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
   2914 
   2915   llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
   2916   return llvm::ConstantExpr::getBitCast(GV,
   2917                                         ObjCTypes.MethodDescriptionListPtrTy);
   2918 }
   2919 
   2920 /*
   2921   struct _objc_category {
   2922   char *category_name;
   2923   char *class_name;
   2924   struct _objc_method_list *instance_methods;
   2925   struct _objc_method_list *class_methods;
   2926   struct _objc_protocol_list *protocols;
   2927   uint32_t size; // <rdar://4585769>
   2928   struct _objc_property_list *instance_properties;
   2929   };
   2930 */
   2931 void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
   2932   unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.CategoryTy);
   2933 
   2934   // FIXME: This is poor design, the OCD should have a pointer to the category
   2935   // decl. Additionally, note that Category can be null for the @implementation
   2936   // w/o an @interface case. Sema should just create one for us as it does for
   2937   // @implementation so everyone else can live life under a clear blue sky.
   2938   const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
   2939   const ObjCCategoryDecl *Category =
   2940     Interface->FindCategoryDeclaration(OCD->getIdentifier());
   2941 
   2942   SmallString<256> ExtName;
   2943   llvm::raw_svector_ostream(ExtName) << Interface->getName() << '_'
   2944                                      << OCD->getName();
   2945 
   2946   SmallVector<llvm::Constant *, 16> InstanceMethods, ClassMethods;
   2947   for (ObjCCategoryImplDecl::instmeth_iterator
   2948          i = OCD->instmeth_begin(), e = OCD->instmeth_end(); i != e; ++i) {
   2949     // Instance methods should always be defined.
   2950     InstanceMethods.push_back(GetMethodConstant(*i));
   2951   }
   2952   for (ObjCCategoryImplDecl::classmeth_iterator
   2953          i = OCD->classmeth_begin(), e = OCD->classmeth_end(); i != e; ++i) {
   2954     // Class methods should always be defined.
   2955     ClassMethods.push_back(GetMethodConstant(*i));
   2956   }
   2957 
   2958   llvm::Constant *Values[7];
   2959   Values[0] = GetClassName(OCD->getIdentifier());
   2960   Values[1] = GetClassName(Interface->getIdentifier());
   2961   LazySymbols.insert(Interface->getIdentifier());
   2962   Values[2] =
   2963     EmitMethodList("\01L_OBJC_CATEGORY_INSTANCE_METHODS_" + ExtName.str(),
   2964                    "__OBJC,__cat_inst_meth,regular,no_dead_strip",
   2965                    InstanceMethods);
   2966   Values[3] =
   2967     EmitMethodList("\01L_OBJC_CATEGORY_CLASS_METHODS_" + ExtName.str(),
   2968                    "__OBJC,__cat_cls_meth,regular,no_dead_strip",
   2969                    ClassMethods);
   2970   if (Category) {
   2971     Values[4] =
   2972       EmitProtocolList("\01L_OBJC_CATEGORY_PROTOCOLS_" + ExtName.str(),
   2973                        Category->protocol_begin(),
   2974                        Category->protocol_end());
   2975   } else {
   2976     Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
   2977   }
   2978   Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
   2979 
   2980   // If there is no category @interface then there can be no properties.
   2981   if (Category) {
   2982     Values[6] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(),
   2983                                  OCD, Category, ObjCTypes);
   2984   } else {
   2985     Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
   2986   }
   2987 
   2988   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
   2989                                                    Values);
   2990 
   2991   llvm::GlobalVariable *GV =
   2992     CreateMetadataVar("\01L_OBJC_CATEGORY_" + ExtName.str(), Init,
   2993                       "__OBJC,__category,regular,no_dead_strip",
   2994                       4, true);
   2995   DefinedCategories.push_back(GV);
   2996   DefinedCategoryNames.insert(ExtName.str());
   2997   // method definition entries must be clear for next implementation.
   2998   MethodDefinitions.clear();
   2999 }
   3000 
   3001 enum FragileClassFlags {
   3002   FragileABI_Class_Factory                 = 0x00001,
   3003   FragileABI_Class_Meta                    = 0x00002,
   3004   FragileABI_Class_HasCXXStructors         = 0x02000,
   3005   FragileABI_Class_Hidden                  = 0x20000
   3006 };
   3007 
   3008 enum NonFragileClassFlags {
   3009   /// Is a meta-class.
   3010   NonFragileABI_Class_Meta                 = 0x00001,
   3011 
   3012   /// Is a root class.
   3013   NonFragileABI_Class_Root                 = 0x00002,
   3014 
   3015   /// Has a C++ constructor and destructor.
   3016   NonFragileABI_Class_HasCXXStructors      = 0x00004,
   3017 
   3018   /// Has hidden visibility.
   3019   NonFragileABI_Class_Hidden               = 0x00010,
   3020 
   3021   /// Has the exception attribute.
   3022   NonFragileABI_Class_Exception            = 0x00020,
   3023 
   3024   /// (Obsolete) ARC-specific: this class has a .release_ivars method
   3025   NonFragileABI_Class_HasIvarReleaser      = 0x00040,
   3026 
   3027   /// Class implementation was compiled under ARC.
   3028   NonFragileABI_Class_CompiledByARC        = 0x00080,
   3029 
   3030   /// Class has non-trivial destructors, but zero-initialization is okay.
   3031   NonFragileABI_Class_HasCXXDestructorOnly = 0x00100
   3032 };
   3033 
   3034 /*
   3035   struct _objc_class {
   3036   Class isa;
   3037   Class super_class;
   3038   const char *name;
   3039   long version;
   3040   long info;
   3041   long instance_size;
   3042   struct _objc_ivar_list *ivars;
   3043   struct _objc_method_list *methods;
   3044   struct _objc_cache *cache;
   3045   struct _objc_protocol_list *protocols;
   3046   // Objective-C 1.0 extensions (<rdr://4585769>)
   3047   const char *ivar_layout;
   3048   struct _objc_class_ext *ext;
   3049   };
   3050 
   3051   See EmitClassExtension();
   3052 */
   3053 void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
   3054   DefinedSymbols.insert(ID->getIdentifier());
   3055 
   3056   std::string ClassName = ID->getNameAsString();
   3057   // FIXME: Gross
   3058   ObjCInterfaceDecl *Interface =
   3059     const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
   3060   llvm::Constant *Protocols =
   3061     EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getName(),
   3062                      Interface->all_referenced_protocol_begin(),
   3063                      Interface->all_referenced_protocol_end());
   3064   unsigned Flags = FragileABI_Class_Factory;
   3065   if (ID->hasNonZeroConstructors() || ID->hasDestructors())
   3066     Flags |= FragileABI_Class_HasCXXStructors;
   3067   unsigned Size =
   3068     CGM.getContext().getASTObjCImplementationLayout(ID).getSize().getQuantity();
   3069 
   3070   // FIXME: Set CXX-structors flag.
   3071   if (ID->getClassInterface()->getVisibility() == HiddenVisibility)
   3072     Flags |= FragileABI_Class_Hidden;
   3073 
   3074   SmallVector<llvm::Constant *, 16> InstanceMethods, ClassMethods;
   3075   for (ObjCImplementationDecl::instmeth_iterator
   3076          i = ID->instmeth_begin(), e = ID->instmeth_end(); i != e; ++i) {
   3077     // Instance methods should always be defined.
   3078     InstanceMethods.push_back(GetMethodConstant(*i));
   3079   }
   3080   for (ObjCImplementationDecl::classmeth_iterator
   3081          i = ID->classmeth_begin(), e = ID->classmeth_end(); i != e; ++i) {
   3082     // Class methods should always be defined.
   3083     ClassMethods.push_back(GetMethodConstant(*i));
   3084   }
   3085 
   3086   for (ObjCImplementationDecl::propimpl_iterator
   3087          i = ID->propimpl_begin(), e = ID->propimpl_end(); i != e; ++i) {
   3088     ObjCPropertyImplDecl *PID = *i;
   3089 
   3090     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
   3091       ObjCPropertyDecl *PD = PID->getPropertyDecl();
   3092 
   3093       if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
   3094         if (llvm::Constant *C = GetMethodConstant(MD))
   3095           InstanceMethods.push_back(C);
   3096       if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
   3097         if (llvm::Constant *C = GetMethodConstant(MD))
   3098           InstanceMethods.push_back(C);
   3099     }
   3100   }
   3101 
   3102   llvm::Constant *Values[12];
   3103   Values[ 0] = EmitMetaClass(ID, Protocols, ClassMethods);
   3104   if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
   3105     // Record a reference to the super class.
   3106     LazySymbols.insert(Super->getIdentifier());
   3107 
   3108     Values[ 1] =
   3109       llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
   3110                                      ObjCTypes.ClassPtrTy);
   3111   } else {
   3112     Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
   3113   }
   3114   Values[ 2] = GetClassName(ID->getIdentifier());
   3115   // Version is always 0.
   3116   Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
   3117   Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
   3118   Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
   3119   Values[ 6] = EmitIvarList(ID, false);
   3120   Values[ 7] =
   3121     EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getName(),
   3122                    "__OBJC,__inst_meth,regular,no_dead_strip",
   3123                    InstanceMethods);
   3124   // cache is always NULL.
   3125   Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
   3126   Values[ 9] = Protocols;
   3127   Values[10] = BuildIvarLayout(ID, true);
   3128   Values[11] = EmitClassExtension(ID);
   3129   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
   3130                                                    Values);
   3131   std::string Name("\01L_OBJC_CLASS_");
   3132   Name += ClassName;
   3133   const char *Section = "__OBJC,__class,regular,no_dead_strip";
   3134   // Check for a forward reference.
   3135   llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
   3136   if (GV) {
   3137     assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
   3138            "Forward metaclass reference has incorrect type.");
   3139     GV->setLinkage(llvm::GlobalValue::InternalLinkage);
   3140     GV->setInitializer(Init);
   3141     GV->setSection(Section);
   3142     GV->setAlignment(4);
   3143     CGM.AddUsedGlobal(GV);
   3144   }
   3145   else
   3146     GV = CreateMetadataVar(Name, Init, Section, 4, true);
   3147   DefinedClasses.push_back(GV);
   3148   // method definition entries must be clear for next implementation.
   3149   MethodDefinitions.clear();
   3150 }
   3151 
   3152 llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
   3153                                          llvm::Constant *Protocols,
   3154                                          ArrayRef<llvm::Constant*> Methods) {
   3155   unsigned Flags = FragileABI_Class_Meta;
   3156   unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassTy);
   3157 
   3158   if (ID->getClassInterface()->getVisibility() == HiddenVisibility)
   3159     Flags |= FragileABI_Class_Hidden;
   3160 
   3161   llvm::Constant *Values[12];
   3162   // The isa for the metaclass is the root of the hierarchy.
   3163   const ObjCInterfaceDecl *Root = ID->getClassInterface();
   3164   while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
   3165     Root = Super;
   3166   Values[ 0] =
   3167     llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
   3168                                    ObjCTypes.ClassPtrTy);
   3169   // The super class for the metaclass is emitted as the name of the
   3170   // super class. The runtime fixes this up to point to the
   3171   // *metaclass* for the super class.
   3172   if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
   3173     Values[ 1] =
   3174       llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
   3175                                      ObjCTypes.ClassPtrTy);
   3176   } else {
   3177     Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
   3178   }
   3179   Values[ 2] = GetClassName(ID->getIdentifier());
   3180   // Version is always 0.
   3181   Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
   3182   Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
   3183   Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
   3184   Values[ 6] = EmitIvarList(ID, true);
   3185   Values[ 7] =
   3186     EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
   3187                    "__OBJC,__cls_meth,regular,no_dead_strip",
   3188                    Methods);
   3189   // cache is always NULL.
   3190   Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
   3191   Values[ 9] = Protocols;
   3192   // ivar_layout for metaclass is always NULL.
   3193   Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
   3194   // The class extension is always unused for metaclasses.
   3195   Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
   3196   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
   3197                                                    Values);
   3198 
   3199   std::string Name("\01L_OBJC_METACLASS_");
   3200   Name += ID->getName();
   3201 
   3202   // Check for a forward reference.
   3203   llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
   3204   if (GV) {
   3205     assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
   3206            "Forward metaclass reference has incorrect type.");
   3207     GV->setLinkage(llvm::GlobalValue::InternalLinkage);
   3208     GV->setInitializer(Init);
   3209   } else {
   3210     GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
   3211                                   llvm::GlobalValue::InternalLinkage,
   3212                                   Init, Name);
   3213   }
   3214   GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
   3215   GV->setAlignment(4);
   3216   CGM.AddUsedGlobal(GV);
   3217 
   3218   return GV;
   3219 }
   3220 
   3221 llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
   3222   std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
   3223 
   3224   // FIXME: Should we look these up somewhere other than the module. Its a bit
   3225   // silly since we only generate these while processing an implementation, so
   3226   // exactly one pointer would work if know when we entered/exitted an
   3227   // implementation block.
   3228 
   3229   // Check for an existing forward reference.
   3230   // Previously, metaclass with internal linkage may have been defined.
   3231   // pass 'true' as 2nd argument so it is returned.
   3232   if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name,
   3233                                                                    true)) {
   3234     assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
   3235            "Forward metaclass reference has incorrect type.");
   3236     return GV;
   3237   } else {
   3238     // Generate as an external reference to keep a consistent
   3239     // module. This will be patched up when we emit the metaclass.
   3240     return new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
   3241                                     llvm::GlobalValue::ExternalLinkage,
   3242                                     0,
   3243                                     Name);
   3244   }
   3245 }
   3246 
   3247 llvm::Value *CGObjCMac::EmitSuperClassRef(const ObjCInterfaceDecl *ID) {
   3248   std::string Name = "\01L_OBJC_CLASS_" + ID->getNameAsString();
   3249 
   3250   if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name,
   3251                                                                    true)) {
   3252     assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
   3253            "Forward class metadata reference has incorrect type.");
   3254     return GV;
   3255   } else {
   3256     return new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
   3257                                     llvm::GlobalValue::ExternalLinkage,
   3258                                     0,
   3259                                     Name);
   3260   }
   3261 }
   3262 
   3263 /*
   3264   struct objc_class_ext {
   3265   uint32_t size;
   3266   const char *weak_ivar_layout;
   3267   struct _objc_property_list *properties;
   3268   };
   3269 */
   3270 llvm::Constant *
   3271 CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
   3272   uint64_t Size =
   3273     CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassExtensionTy);
   3274 
   3275   llvm::Constant *Values[3];
   3276   Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
   3277   Values[1] = BuildIvarLayout(ID, false);
   3278   Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getName(),
   3279                                ID, ID->getClassInterface(), ObjCTypes);
   3280 
   3281   // Return null if no extension bits are used.
   3282   if (Values[1]->isNullValue() && Values[2]->isNullValue())
   3283     return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
   3284 
   3285   llvm::Constant *Init =
   3286     llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
   3287   return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getName(),
   3288                            Init, "__OBJC,__class_ext,regular,no_dead_strip",
   3289                            4, true);
   3290 }
   3291 
   3292 /*
   3293   struct objc_ivar {
   3294     char *ivar_name;
   3295     char *ivar_type;
   3296     int ivar_offset;
   3297   };
   3298 
   3299   struct objc_ivar_list {
   3300     int ivar_count;
   3301     struct objc_ivar list[count];
   3302   };
   3303 */
   3304 llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
   3305                                         bool ForClass) {
   3306   std::vector<llvm::Constant*> Ivars;
   3307 
   3308   // When emitting the root class GCC emits ivar entries for the
   3309   // actual class structure. It is not clear if we need to follow this
   3310   // behavior; for now lets try and get away with not doing it. If so,
   3311   // the cleanest solution would be to make up an ObjCInterfaceDecl
   3312   // for the class.
   3313   if (ForClass)
   3314     return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
   3315 
   3316   const ObjCInterfaceDecl *OID = ID->getClassInterface();
   3317 
   3318   for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin();
   3319        IVD; IVD = IVD->getNextIvar()) {
   3320     // Ignore unnamed bit-fields.
   3321     if (!IVD->getDeclName())
   3322       continue;
   3323     llvm::Constant *Ivar[] = {
   3324       GetMethodVarName(IVD->getIdentifier()),
   3325       GetMethodVarType(IVD),
   3326       llvm::ConstantInt::get(ObjCTypes.IntTy,
   3327                              ComputeIvarBaseOffset(CGM, OID, IVD))
   3328     };
   3329     Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
   3330   }
   3331 
   3332   // Return null for empty list.
   3333   if (Ivars.empty())
   3334     return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
   3335 
   3336   llvm::Constant *Values[2];
   3337   Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
   3338   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
   3339                                              Ivars.size());
   3340   Values[1] = llvm::ConstantArray::get(AT, Ivars);
   3341   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
   3342 
   3343   llvm::GlobalVariable *GV;
   3344   if (ForClass)
   3345     GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getName(),
   3346                            Init, "__OBJC,__class_vars,regular,no_dead_strip",
   3347                            4, true);
   3348   else
   3349     GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_" + ID->getName(),
   3350                            Init, "__OBJC,__instance_vars,regular,no_dead_strip",
   3351                            4, true);
   3352   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
   3353 }
   3354 
   3355 /*
   3356   struct objc_method {
   3357   SEL method_name;
   3358   char *method_types;
   3359   void *method;
   3360   };
   3361 
   3362   struct objc_method_list {
   3363   struct objc_method_list *obsolete;
   3364   int count;
   3365   struct objc_method methods_list[count];
   3366   };
   3367 */
   3368 
   3369 /// GetMethodConstant - Return a struct objc_method constant for the
   3370 /// given method if it has been defined. The result is null if the
   3371 /// method has not been defined. The return value has type MethodPtrTy.
   3372 llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
   3373   llvm::Function *Fn = GetMethodDefinition(MD);
   3374   if (!Fn)
   3375     return 0;
   3376 
   3377   llvm::Constant *Method[] = {
   3378     llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
   3379                                    ObjCTypes.SelectorPtrTy),
   3380     GetMethodVarType(MD),
   3381     llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy)
   3382   };
   3383   return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
   3384 }
   3385 
   3386 llvm::Constant *CGObjCMac::EmitMethodList(Twine Name,
   3387                                           const char *Section,
   3388                                           ArrayRef<llvm::Constant*> Methods) {
   3389   // Return null for empty list.
   3390   if (Methods.empty())
   3391     return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
   3392 
   3393   llvm::Constant *Values[3];
   3394   Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
   3395   Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
   3396   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
   3397                                              Methods.size());
   3398   Values[2] = llvm::ConstantArray::get(AT, Methods);
   3399   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
   3400 
   3401   llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
   3402   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListPtrTy);
   3403 }
   3404 
   3405 llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
   3406                                                 const ObjCContainerDecl *CD) {
   3407   SmallString<256> Name;
   3408   GetNameForMethod(OMD, CD, Name);
   3409 
   3410   CodeGenTypes &Types = CGM.getTypes();
   3411   llvm::FunctionType *MethodTy =
   3412     Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
   3413   llvm::Function *Method =
   3414     llvm::Function::Create(MethodTy,
   3415                            llvm::GlobalValue::InternalLinkage,
   3416                            Name.str(),
   3417                            &CGM.getModule());
   3418   MethodDefinitions.insert(std::make_pair(OMD, Method));
   3419 
   3420   return Method;
   3421 }
   3422 
   3423 llvm::GlobalVariable *
   3424 CGObjCCommonMac::CreateMetadataVar(Twine Name,
   3425                                    llvm::Constant *Init,
   3426                                    const char *Section,
   3427                                    unsigned Align,
   3428                                    bool AddToUsed) {
   3429   llvm::Type *Ty = Init->getType();
   3430   llvm::GlobalVariable *GV =
   3431     new llvm::GlobalVariable(CGM.getModule(), Ty, false,
   3432                              llvm::GlobalValue::InternalLinkage, Init, Name);
   3433   if (Section)
   3434     GV->setSection(Section);
   3435   if (Align)
   3436     GV->setAlignment(Align);
   3437   if (AddToUsed)
   3438     CGM.AddUsedGlobal(GV);
   3439   return GV;
   3440 }
   3441 
   3442 llvm::Function *CGObjCMac::ModuleInitFunction() {
   3443   // Abuse this interface function as a place to finalize.
   3444   FinishModule();
   3445   return NULL;
   3446 }
   3447 
   3448 llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
   3449   return ObjCTypes.getGetPropertyFn();
   3450 }
   3451 
   3452 llvm::Constant *CGObjCMac::GetPropertySetFunction() {
   3453   return ObjCTypes.getSetPropertyFn();
   3454 }
   3455 
   3456 llvm::Constant *CGObjCMac::GetOptimizedPropertySetFunction(bool atomic,
   3457                                                            bool copy) {
   3458   return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy);
   3459 }
   3460 
   3461 llvm::Constant *CGObjCMac::GetGetStructFunction() {
   3462   return ObjCTypes.getCopyStructFn();
   3463 }
   3464 llvm::Constant *CGObjCMac::GetSetStructFunction() {
   3465   return ObjCTypes.getCopyStructFn();
   3466 }
   3467 
   3468 llvm::Constant *CGObjCMac::GetCppAtomicObjectGetFunction() {
   3469   return ObjCTypes.getCppAtomicObjectFunction();
   3470 }
   3471 llvm::Constant *CGObjCMac::GetCppAtomicObjectSetFunction() {
   3472   return ObjCTypes.getCppAtomicObjectFunction();
   3473 }
   3474 
   3475 llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
   3476   return ObjCTypes.getEnumerationMutationFn();
   3477 }
   3478 
   3479 void CGObjCMac::EmitTryStmt(CodeGenFunction &CGF, const ObjCAtTryStmt &S) {
   3480   return EmitTryOrSynchronizedStmt(CGF, S);
   3481 }
   3482 
   3483 void CGObjCMac::EmitSynchronizedStmt(CodeGenFunction &CGF,
   3484                                      const ObjCAtSynchronizedStmt &S) {
   3485   return EmitTryOrSynchronizedStmt(CGF, S);
   3486 }
   3487 
   3488 namespace {
   3489   struct PerformFragileFinally : EHScopeStack::Cleanup {
   3490     const Stmt &S;
   3491     llvm::Value *SyncArgSlot;
   3492     llvm::Value *CallTryExitVar;
   3493     llvm::Value *ExceptionData;
   3494     ObjCTypesHelper &ObjCTypes;
   3495     PerformFragileFinally(const Stmt *S,
   3496                           llvm::Value *SyncArgSlot,
   3497                           llvm::Value *CallTryExitVar,
   3498                           llvm::Value *ExceptionData,
   3499                           ObjCTypesHelper *ObjCTypes)
   3500       : S(*S), SyncArgSlot(SyncArgSlot), CallTryExitVar(CallTryExitVar),
   3501         ExceptionData(ExceptionData), ObjCTypes(*ObjCTypes) {}
   3502 
   3503     void Emit(CodeGenFunction &CGF, Flags flags) {
   3504       // Check whether we need to call objc_exception_try_exit.
   3505       // In optimized code, this branch will always be folded.
   3506       llvm::BasicBlock *FinallyCallExit =
   3507         CGF.createBasicBlock("finally.call_exit");
   3508       llvm::BasicBlock *FinallyNoCallExit =
   3509         CGF.createBasicBlock("finally.no_call_exit");
   3510       CGF.Builder.CreateCondBr(CGF.Builder.CreateLoad(CallTryExitVar),
   3511                                FinallyCallExit, FinallyNoCallExit);
   3512 
   3513       CGF.EmitBlock(FinallyCallExit);
   3514       CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryExitFn(),
   3515                                   ExceptionData);
   3516 
   3517       CGF.EmitBlock(FinallyNoCallExit);
   3518 
   3519       if (isa<ObjCAtTryStmt>(S)) {
   3520         if (const ObjCAtFinallyStmt* FinallyStmt =
   3521               cast<ObjCAtTryStmt>(S).getFinallyStmt()) {
   3522           // Save the current cleanup destination in case there's
   3523           // control flow inside the finally statement.
   3524           llvm::Value *CurCleanupDest =
   3525             CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot());
   3526 
   3527           CGF.EmitStmt(FinallyStmt->getFinallyBody());
   3528 
   3529           if (CGF.HaveInsertPoint()) {
   3530             CGF.Builder.CreateStore(CurCleanupDest,
   3531                                     CGF.getNormalCleanupDestSlot());
   3532           } else {
   3533             // Currently, the end of the cleanup must always exist.
   3534             CGF.EnsureInsertPoint();
   3535           }
   3536         }
   3537       } else {
   3538         // Emit objc_sync_exit(expr); as finally's sole statement for
   3539         // @synchronized.
   3540         llvm::Value *SyncArg = CGF.Builder.CreateLoad(SyncArgSlot);
   3541         CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncExitFn(), SyncArg);
   3542       }
   3543     }
   3544   };
   3545 
   3546   class FragileHazards {
   3547     CodeGenFunction &CGF;
   3548     SmallVector<llvm::Value*, 20> Locals;
   3549     llvm::DenseSet<llvm::BasicBlock*> BlocksBeforeTry;
   3550 
   3551     llvm::InlineAsm *ReadHazard;
   3552     llvm::InlineAsm *WriteHazard;
   3553 
   3554     llvm::FunctionType *GetAsmFnType();
   3555 
   3556     void collectLocals();
   3557     void emitReadHazard(CGBuilderTy &Builder);
   3558 
   3559   public:
   3560     FragileHazards(CodeGenFunction &CGF);
   3561 
   3562     void emitWriteHazard();
   3563     void emitHazardsInNewBlocks();
   3564   };
   3565 }
   3566 
   3567 /// Create the fragile-ABI read and write hazards based on the current
   3568 /// state of the function, which is presumed to be immediately prior
   3569 /// to a @try block.  These hazards are used to maintain correct
   3570 /// semantics in the face of optimization and the fragile ABI's
   3571 /// cavalier use of setjmp/longjmp.
   3572 FragileHazards::FragileHazards(CodeGenFunction &CGF) : CGF(CGF) {
   3573   collectLocals();
   3574 
   3575   if (Locals.empty()) return;
   3576 
   3577   // Collect all the blocks in the function.
   3578   for (llvm::Function::iterator
   3579          I = CGF.CurFn->begin(), E = CGF.CurFn->end(); I != E; ++I)
   3580     BlocksBeforeTry.insert(&*I);
   3581 
   3582   llvm::FunctionType *AsmFnTy = GetAsmFnType();
   3583 
   3584   // Create a read hazard for the allocas.  This inhibits dead-store
   3585   // optimizations and forces the values to memory.  This hazard is
   3586   // inserted before any 'throwing' calls in the protected scope to
   3587   // reflect the possibility that the variables might be read from the
   3588   // catch block if the call throws.
   3589   {
   3590     std::string Constraint;
   3591     for (unsigned I = 0, E = Locals.size(); I != E; ++I) {
   3592       if (I) Constraint += ',';
   3593       Constraint += "*m";
   3594     }
   3595 
   3596     ReadHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);
   3597   }
   3598 
   3599   // Create a write hazard for the allocas.  This inhibits folding
   3600   // loads across the hazard.  This hazard is inserted at the
   3601   // beginning of the catch path to reflect the possibility that the
   3602   // variables might have been written within the protected scope.
   3603   {
   3604     std::string Constraint;
   3605     for (unsigned I = 0, E = Locals.size(); I != E; ++I) {
   3606       if (I) Constraint += ',';
   3607       Constraint += "=*m";
   3608     }
   3609 
   3610     WriteHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);
   3611   }
   3612 }
   3613 
   3614 /// Emit a write hazard at the current location.
   3615 void FragileHazards::emitWriteHazard() {
   3616   if (Locals.empty()) return;
   3617 
   3618   CGF.EmitNounwindRuntimeCall(WriteHazard, Locals);
   3619 }
   3620 
   3621 void FragileHazards::emitReadHazard(CGBuilderTy &Builder) {
   3622   assert(!Locals.empty());
   3623   llvm::CallInst *call = Builder.CreateCall(ReadHazard, Locals);
   3624   call->setDoesNotThrow();
   3625   call->setCallingConv(CGF.getRuntimeCC());
   3626 }
   3627 
   3628 /// Emit read hazards in all the protected blocks, i.e. all the blocks
   3629 /// which have been inserted since the beginning of the try.
   3630 void FragileHazards::emitHazardsInNewBlocks() {
   3631   if (Locals.empty()) return;
   3632 
   3633   CGBuilderTy Builder(CGF.getLLVMContext());
   3634 
   3635   // Iterate through all blocks, skipping those prior to the try.
   3636   for (llvm::Function::iterator
   3637          FI = CGF.CurFn->begin(), FE = CGF.CurFn->end(); FI != FE; ++FI) {
   3638     llvm::BasicBlock &BB = *FI;
   3639     if (BlocksBeforeTry.count(&BB)) continue;
   3640 
   3641     // Walk through all the calls in the block.
   3642     for (llvm::BasicBlock::iterator
   3643            BI = BB.begin(), BE = BB.end(); BI != BE; ++BI) {
   3644       llvm::Instruction &I = *BI;
   3645 
   3646       // Ignore instructions that aren't non-intrinsic calls.
   3647       // These are the only calls that can possibly call longjmp.
   3648       if (!isa<llvm::CallInst>(I) && !isa<llvm::InvokeInst>(I)) continue;
   3649       if (isa<llvm::IntrinsicInst>(I))
   3650         continue;
   3651 
   3652       // Ignore call sites marked nounwind.  This may be questionable,
   3653       // since 'nounwind' doesn't necessarily mean 'does not call longjmp'.
   3654       llvm::CallSite CS(&I);
   3655       if (CS.doesNotThrow()) continue;
   3656 
   3657       // Insert a read hazard before the call.  This will ensure that
   3658       // any writes to the locals are performed before making the
   3659       // call.  If the call throws, then this is sufficient to
   3660       // guarantee correctness as long as it doesn't also write to any
   3661       // locals.
   3662       Builder.SetInsertPoint(&BB, BI);
   3663       emitReadHazard(Builder);
   3664     }
   3665   }
   3666 }
   3667 
   3668 static void addIfPresent(llvm::DenseSet<llvm::Value*> &S, llvm::Value *V) {
   3669   if (V) S.insert(V);
   3670 }
   3671 
   3672 void FragileHazards::collectLocals() {
   3673   // Compute a set of allocas to ignore.
   3674   llvm::DenseSet<llvm::Value*> AllocasToIgnore;
   3675   addIfPresent(AllocasToIgnore, CGF.ReturnValue);
   3676   addIfPresent(AllocasToIgnore, CGF.NormalCleanupDest);
   3677 
   3678   // Collect all the allocas currently in the function.  This is
   3679   // probably way too aggressive.
   3680   llvm::BasicBlock &Entry = CGF.CurFn->getEntryBlock();
   3681   for (llvm::BasicBlock::iterator
   3682          I = Entry.begin(), E = Entry.end(); I != E; ++I)
   3683     if (isa<llvm::AllocaInst>(*I) && !AllocasToIgnore.count(&*I))
   3684       Locals.push_back(&*I);
   3685 }
   3686 
   3687 llvm::FunctionType *FragileHazards::GetAsmFnType() {
   3688   SmallVector<llvm::Type *, 16> tys(Locals.size());
   3689   for (unsigned i = 0, e = Locals.size(); i != e; ++i)
   3690     tys[i] = Locals[i]->getType();
   3691   return llvm::FunctionType::get(CGF.VoidTy, tys, false);
   3692 }
   3693 
   3694 /*
   3695 
   3696   Objective-C setjmp-longjmp (sjlj) Exception Handling
   3697   --
   3698 
   3699   A catch buffer is a setjmp buffer plus:
   3700     - a pointer to the exception that was caught
   3701     - a pointer to the previous exception data buffer
   3702     - two pointers of reserved storage
   3703   Therefore catch buffers form a stack, with a pointer to the top
   3704   of the stack kept in thread-local storage.
   3705 
   3706   objc_exception_try_enter pushes a catch buffer onto the EH stack.
   3707   objc_exception_try_exit pops the given catch buffer, which is
   3708     required to be the top of the EH stack.
   3709   objc_exception_throw pops the top of the EH stack, writes the
   3710     thrown exception into the appropriate field, and longjmps
   3711     to the setjmp buffer.  It crashes the process (with a printf
   3712     and an abort()) if there are no catch buffers on the stack.
   3713   objc_exception_extract just reads the exception pointer out of the
   3714     catch buffer.
   3715 
   3716   There's no reason an implementation couldn't use a light-weight
   3717   setjmp here --- something like __builtin_setjmp, but API-compatible
   3718   with the heavyweight setjmp.  This will be more important if we ever
   3719   want to implement correct ObjC/C++ exception interactions for the
   3720   fragile ABI.
   3721 
   3722   Note that for this use of setjmp/longjmp to be correct, we may need
   3723   to mark some local variables volatile: if a non-volatile local
   3724   variable is modified between the setjmp and the longjmp, it has
   3725   indeterminate value.  For the purposes of LLVM IR, it may be
   3726   sufficient to make loads and stores within the @try (to variables
   3727   declared outside the @try) volatile.  This is necessary for
   3728   optimized correctness, but is not currently being done; this is
   3729   being tracked as rdar://problem/8160285
   3730 
   3731   The basic framework for a @try-catch-finally is as follows:
   3732   {
   3733   objc_exception_data d;
   3734   id _rethrow = null;
   3735   bool _call_try_exit = true;
   3736 
   3737   objc_exception_try_enter(&d);
   3738   if (!setjmp(d.jmp_buf)) {
   3739   ... try body ...
   3740   } else {
   3741   // exception path
   3742   id _caught = objc_exception_extract(&d);
   3743 
   3744   // enter new try scope for handlers
   3745   if (!setjmp(d.jmp_buf)) {
   3746   ... match exception and execute catch blocks ...
   3747 
   3748   // fell off end, rethrow.
   3749   _rethrow = _caught;
   3750   ... jump-through-finally to finally_rethrow ...
   3751   } else {
   3752   // exception in catch block
   3753   _rethrow = objc_exception_extract(&d);
   3754   _call_try_exit = false;
   3755   ... jump-through-finally to finally_rethrow ...
   3756   }
   3757   }
   3758   ... jump-through-finally to finally_end ...
   3759 
   3760   finally:
   3761   if (_call_try_exit)
   3762   objc_exception_try_exit(&d);
   3763 
   3764   ... finally block ....
   3765   ... dispatch to finally destination ...
   3766 
   3767   finally_rethrow:
   3768   objc_exception_throw(_rethrow);
   3769 
   3770   finally_end:
   3771   }
   3772 
   3773   This framework differs slightly from the one gcc uses, in that gcc
   3774   uses _rethrow to determine if objc_exception_try_exit should be called
   3775   and if the object should be rethrown. This breaks in the face of
   3776   throwing nil and introduces unnecessary branches.
   3777 
   3778   We specialize this framework for a few particular circumstances:
   3779 
   3780   - If there are no catch blocks, then we avoid emitting the second
   3781   exception handling context.
   3782 
   3783   - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
   3784   e)) we avoid emitting the code to rethrow an uncaught exception.
   3785 
   3786   - FIXME: If there is no @finally block we can do a few more
   3787   simplifications.
   3788 
   3789   Rethrows and Jumps-Through-Finally
   3790   --
   3791 
   3792   '@throw;' is supported by pushing the currently-caught exception
   3793   onto ObjCEHStack while the @catch blocks are emitted.
   3794 
   3795   Branches through the @finally block are handled with an ordinary
   3796   normal cleanup.  We do not register an EH cleanup; fragile-ABI ObjC
   3797   exceptions are not compatible with C++ exceptions, and this is
   3798   hardly the only place where this will go wrong.
   3799 
   3800   @synchronized(expr) { stmt; } is emitted as if it were:
   3801     id synch_value = expr;
   3802     objc_sync_enter(synch_value);
   3803     @try { stmt; } @finally { objc_sync_exit(synch_value); }
   3804 */
   3805 
   3806 void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
   3807                                           const Stmt &S) {
   3808   bool isTry = isa<ObjCAtTryStmt>(S);
   3809 
   3810   // A destination for the fall-through edges of the catch handlers to
   3811   // jump to.
   3812   CodeGenFunction::JumpDest FinallyEnd =
   3813     CGF.getJumpDestInCurrentScope("finally.end");
   3814 
   3815   // A destination for the rethrow edge of the catch handlers to jump
   3816   // to.
   3817   CodeGenFunction::JumpDest FinallyRethrow =
   3818     CGF.getJumpDestInCurrentScope("finally.rethrow");
   3819 
   3820   // For @synchronized, call objc_sync_enter(sync.expr). The
   3821   // evaluation of the expression must occur before we enter the
   3822   // @synchronized.  We can't avoid a temp here because we need the
   3823   // value to be preserved.  If the backend ever does liveness
   3824   // correctly after setjmp, this will be unnecessary.
   3825   llvm::Value *SyncArgSlot = 0;
   3826   if (!isTry) {
   3827     llvm::Value *SyncArg =
   3828       CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
   3829     SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
   3830     CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncEnterFn(), SyncArg);
   3831 
   3832     SyncArgSlot = CGF.CreateTempAlloca(SyncArg->getType(), "sync.arg");
   3833     CGF.Builder.CreateStore(SyncArg, SyncArgSlot);
   3834   }
   3835 
   3836   // Allocate memory for the setjmp buffer.  This needs to be kept
   3837   // live throughout the try and catch blocks.
   3838   llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
   3839                                                     "exceptiondata.ptr");
   3840 
   3841   // Create the fragile hazards.  Note that this will not capture any
   3842   // of the allocas required for exception processing, but will
   3843   // capture the current basic block (which extends all the way to the
   3844   // setjmp call) as "before the @try".
   3845   FragileHazards Hazards(CGF);
   3846 
   3847   // Create a flag indicating whether the cleanup needs to call
   3848   // objc_exception_try_exit.  This is true except when
   3849   //   - no catches match and we're branching through the cleanup
   3850   //     just to rethrow the exception, or
   3851   //   - a catch matched and we're falling out of the catch handler.
   3852   // The setjmp-safety rule here is that we should always store to this
   3853   // variable in a place that dominates the branch through the cleanup
   3854   // without passing through any setjmps.
   3855   llvm::Value *CallTryExitVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(),
   3856                                                      "_call_try_exit");
   3857 
   3858   // A slot containing the exception to rethrow.  Only needed when we
   3859   // have both a @catch and a @finally.
   3860   llvm::Value *PropagatingExnVar = 0;
   3861 
   3862   // Push a normal cleanup to leave the try scope.
   3863   CGF.EHStack.pushCleanup<PerformFragileFinally>(NormalCleanup, &S,
   3864                                                  SyncArgSlot,
   3865                                                  CallTryExitVar,
   3866                                                  ExceptionData,
   3867                                                  &ObjCTypes);
   3868 
   3869   // Enter a try block:
   3870   //  - Call objc_exception_try_enter to push ExceptionData on top of
   3871   //    the EH stack.
   3872   CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
   3873 
   3874   //  - Call setjmp on the exception data buffer.
   3875   llvm::Constant *Zero = llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
   3876   llvm::Value *GEPIndexes[] = { Zero, Zero, Zero };
   3877   llvm::Value *SetJmpBuffer =
   3878     CGF.Builder.CreateGEP(ExceptionData, GEPIndexes, "setjmp_buffer");
   3879   llvm::CallInst *SetJmpResult =
   3880     CGF.EmitNounwindRuntimeCall(ObjCTypes.getSetJmpFn(), SetJmpBuffer, "setjmp_result");
   3881   SetJmpResult->setCanReturnTwice();
   3882 
   3883   // If setjmp returned 0, enter the protected block; otherwise,
   3884   // branch to the handler.
   3885   llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
   3886   llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
   3887   llvm::Value *DidCatch =
   3888     CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
   3889   CGF.Builder.CreateCondBr(DidCatch, TryHandler, TryBlock);
   3890 
   3891   // Emit the protected block.
   3892   CGF.EmitBlock(TryBlock);
   3893   CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
   3894   CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
   3895                      : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
   3896 
   3897   CGBuilderTy::InsertPoint TryFallthroughIP = CGF.Builder.saveAndClearIP();
   3898 
   3899   // Emit the exception handler block.
   3900   CGF.EmitBlock(TryHandler);
   3901 
   3902   // Don't optimize loads of the in-scope locals across this point.
   3903   Hazards.emitWriteHazard();
   3904 
   3905   // For a @synchronized (or a @try with no catches), just branch
   3906   // through the cleanup to the rethrow block.
   3907   if (!isTry || !cast<ObjCAtTryStmt>(S).getNumCatchStmts()) {
   3908     // Tell the cleanup not to re-pop the exit.
   3909     CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
   3910     CGF.EmitBranchThroughCleanup(FinallyRethrow);
   3911 
   3912   // Otherwise, we have to match against the caught exceptions.
   3913   } else {
   3914     // Retrieve the exception object.  We may emit multiple blocks but
   3915     // nothing can cross this so the value is already in SSA form.
   3916     llvm::CallInst *Caught =
   3917       CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
   3918                                   ExceptionData, "caught");
   3919 
   3920     // Push the exception to rethrow onto the EH value stack for the
   3921     // benefit of any @throws in the handlers.
   3922     CGF.ObjCEHValueStack.push_back(Caught);
   3923 
   3924     const ObjCAtTryStmt* AtTryStmt = cast<ObjCAtTryStmt>(&S);
   3925 
   3926     bool HasFinally = (AtTryStmt->getFinallyStmt() != 0);
   3927 
   3928     llvm::BasicBlock *CatchBlock = 0;
   3929     llvm::BasicBlock *CatchHandler = 0;
   3930     if (HasFinally) {
   3931       // Save the currently-propagating exception before
   3932       // objc_exception_try_enter clears the exception slot.
   3933       PropagatingExnVar = CGF.CreateTempAlloca(Caught->getType(),
   3934                                                "propagating_exception");
   3935       CGF.Builder.CreateStore(Caught, PropagatingExnVar);
   3936 
   3937       // Enter a new exception try block (in case a @catch block
   3938       // throws an exception).
   3939       CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(),
   3940                                   ExceptionData);
   3941 
   3942       llvm::CallInst *SetJmpResult =
   3943         CGF.EmitNounwindRuntimeCall(ObjCTypes.getSetJmpFn(),
   3944                                     SetJmpBuffer, "setjmp.result");
   3945       SetJmpResult->setCanReturnTwice();
   3946 
   3947       llvm::Value *Threw =
   3948         CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
   3949 
   3950       CatchBlock = CGF.createBasicBlock("catch");
   3951       CatchHandler = CGF.createBasicBlock("catch_for_catch");
   3952       CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
   3953 
   3954       CGF.EmitBlock(CatchBlock);
   3955     }
   3956 
   3957     CGF.Builder.CreateStore(CGF.Builder.getInt1(HasFinally), CallTryExitVar);
   3958 
   3959     // Handle catch list. As a special case we check if everything is
   3960     // matched and avoid generating code for falling off the end if
   3961     // so.
   3962     bool AllMatched = false;
   3963     for (unsigned I = 0, N = AtTryStmt->getNumCatchStmts(); I != N; ++I) {
   3964       const ObjCAtCatchStmt *CatchStmt = AtTryStmt->getCatchStmt(I);
   3965 
   3966       const VarDecl *CatchParam = CatchStmt->getCatchParamDecl();
   3967       const ObjCObjectPointerType *OPT = 0;
   3968 
   3969       // catch(...) always matches.
   3970       if (!CatchParam) {
   3971         AllMatched = true;
   3972       } else {
   3973         OPT = CatchParam->getType()->getAs<ObjCObjectPointerType>();
   3974 
   3975         // catch(id e) always matches under this ABI, since only
   3976         // ObjC exceptions end up here in the first place.
   3977         // FIXME: For the time being we also match id<X>; this should
   3978         // be rejected by Sema instead.
   3979         if (OPT && (OPT->isObjCIdType() || OPT->isObjCQualifiedIdType()))
   3980           AllMatched = true;
   3981       }
   3982 
   3983       // If this is a catch-all, we don't need to test anything.
   3984       if (AllMatched) {
   3985         CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
   3986 
   3987         if (CatchParam) {
   3988           CGF.EmitAutoVarDecl(*CatchParam);
   3989           assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
   3990 
   3991           // These types work out because ConvertType(id) == i8*.
   3992           CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
   3993         }
   3994 
   3995         CGF.EmitStmt(CatchStmt->getCatchBody());
   3996 
   3997         // The scope of the catch variable ends right here.
   3998         CatchVarCleanups.ForceCleanup();
   3999 
   4000         CGF.EmitBranchThroughCleanup(FinallyEnd);
   4001         break;
   4002       }
   4003 
   4004       assert(OPT && "Unexpected non-object pointer type in @catch");
   4005       const ObjCObjectType *ObjTy = OPT->getObjectType();
   4006 
   4007       // FIXME: @catch (Class c) ?
   4008       ObjCInterfaceDecl *IDecl = ObjTy->getInterface();
   4009       assert(IDecl && "Catch parameter must have Objective-C type!");
   4010 
   4011       // Check if the @catch block matches the exception object.
   4012       llvm::Value *Class = EmitClassRef(CGF, IDecl);
   4013 
   4014       llvm::Value *matchArgs[] = { Class, Caught };
   4015       llvm::CallInst *Match =
   4016         CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionMatchFn(),
   4017                                     matchArgs, "match");
   4018 
   4019       llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("match");
   4020       llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch.next");
   4021 
   4022       CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
   4023                                MatchedBlock, NextCatchBlock);
   4024 
   4025       // Emit the @catch block.
   4026       CGF.EmitBlock(MatchedBlock);
   4027 
   4028       // Collect any cleanups for the catch variable.  The scope lasts until
   4029       // the end of the catch body.
   4030       CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
   4031 
   4032       CGF.EmitAutoVarDecl(*CatchParam);
   4033       assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
   4034 
   4035       // Initialize the catch variable.
   4036       llvm::Value *Tmp =
   4037         CGF.Builder.CreateBitCast(Caught,
   4038                                   CGF.ConvertType(CatchParam->getType()));
   4039       CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
   4040 
   4041       CGF.EmitStmt(CatchStmt->getCatchBody());
   4042 
   4043       // We're done with the catch variable.
   4044       CatchVarCleanups.ForceCleanup();
   4045 
   4046       CGF.EmitBranchThroughCleanup(FinallyEnd);
   4047 
   4048       CGF.EmitBlock(NextCatchBlock);
   4049     }
   4050 
   4051     CGF.ObjCEHValueStack.pop_back();
   4052 
   4053     // If nothing wanted anything to do with the caught exception,
   4054     // kill the extract call.
   4055     if (Caught->use_empty())
   4056       Caught->eraseFromParent();
   4057 
   4058     if (!AllMatched)
   4059       CGF.EmitBranchThroughCleanup(FinallyRethrow);
   4060 
   4061     if (HasFinally) {
   4062       // Emit the exception handler for the @catch blocks.
   4063       CGF.EmitBlock(CatchHandler);
   4064 
   4065       // In theory we might now need a write hazard, but actually it's
   4066       // unnecessary because there's no local-accessing code between
   4067       // the try's write hazard and here.
   4068       //Hazards.emitWriteHazard();
   4069 
   4070       // Extract the new exception and save it to the
   4071       // propagating-exception slot.
   4072       assert(PropagatingExnVar);
   4073       llvm::CallInst *NewCaught =
   4074         CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
   4075                                     ExceptionData, "caught");
   4076       CGF.Builder.CreateStore(NewCaught, PropagatingExnVar);
   4077 
   4078       // Don't pop the catch handler; the throw already did.
   4079       CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
   4080       CGF.EmitBranchThroughCleanup(FinallyRethrow);
   4081     }
   4082   }
   4083 
   4084   // Insert read hazards as required in the new blocks.
   4085   Hazards.emitHazardsInNewBlocks();
   4086 
   4087   // Pop the cleanup.
   4088   CGF.Builder.restoreIP(TryFallthroughIP);
   4089   if (CGF.HaveInsertPoint())
   4090     CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
   4091   CGF.PopCleanupBlock();
   4092   CGF.EmitBlock(FinallyEnd.getBlock(), true);
   4093 
   4094   // Emit the rethrow block.
   4095   CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
   4096   CGF.EmitBlock(FinallyRethrow.getBlock(), true);
   4097   if (CGF.HaveInsertPoint()) {
   4098     // If we have a propagating-exception variable, check it.
   4099     llvm::Value *PropagatingExn;
   4100     if (PropagatingExnVar) {
   4101       PropagatingExn = CGF.Builder.CreateLoad(PropagatingExnVar);
   4102 
   4103     // Otherwise, just look in the buffer for the exception to throw.
   4104     } else {
   4105       llvm::CallInst *Caught =
   4106         CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
   4107                                     ExceptionData);
   4108       PropagatingExn = Caught;
   4109     }
   4110 
   4111     CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionThrowFn(),
   4112                                 PropagatingExn);
   4113     CGF.Builder.CreateUnreachable();
   4114   }
   4115 
   4116   CGF.Builder.restoreIP(SavedIP);
   4117 }
   4118 
   4119 void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
   4120                               const ObjCAtThrowStmt &S,
   4121                               bool ClearInsertionPoint) {
   4122   llvm::Value *ExceptionAsObject;
   4123 
   4124   if (const Expr *ThrowExpr = S.getThrowExpr()) {
   4125     llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
   4126     ExceptionAsObject =
   4127       CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
   4128   } else {
   4129     assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
   4130            "Unexpected rethrow outside @catch block.");
   4131     ExceptionAsObject = CGF.ObjCEHValueStack.back();
   4132   }
   4133 
   4134   CGF.EmitRuntimeCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject)
   4135     ->setDoesNotReturn();
   4136   CGF.Builder.CreateUnreachable();
   4137 
   4138   // Clear the insertion point to indicate we are in unreachable code.
   4139   if (ClearInsertionPoint)
   4140     CGF.Builder.ClearInsertionPoint();
   4141 }
   4142 
   4143 /// EmitObjCWeakRead - Code gen for loading value of a __weak
   4144 /// object: objc_read_weak (id *src)
   4145 ///
   4146 llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
   4147                                           llvm::Value *AddrWeakObj) {
   4148   llvm::Type* DestTy =
   4149     cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
   4150   AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj,
   4151                                           ObjCTypes.PtrObjectPtrTy);
   4152   llvm::Value *read_weak =
   4153     CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(),
   4154                                 AddrWeakObj, "weakread");
   4155   read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
   4156   return read_weak;
   4157 }
   4158 
   4159 /// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
   4160 /// objc_assign_weak (id src, id *dst)
   4161 ///
   4162 void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
   4163                                    llvm::Value *src, llvm::Value *dst) {
   4164   llvm::Type * SrcTy = src->getType();
   4165   if (!isa<llvm::PointerType>(SrcTy)) {
   4166     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
   4167     assert(Size <= 8 && "does not support size > 8");
   4168     src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
   4169       : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
   4170     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
   4171   }
   4172   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
   4173   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
   4174   llvm::Value *args[] = { src, dst };
   4175   CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(),
   4176                               args, "weakassign");
   4177   return;
   4178 }
   4179 
   4180 /// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
   4181 /// objc_assign_global (id src, id *dst)
   4182 ///
   4183 void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
   4184                                      llvm::Value *src, llvm::Value *dst,
   4185                                      bool threadlocal) {
   4186   llvm::Type * SrcTy = src->getType();
   4187   if (!isa<llvm::PointerType>(SrcTy)) {
   4188     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
   4189     assert(Size <= 8 && "does not support size > 8");
   4190     src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
   4191       : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
   4192     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
   4193   }
   4194   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
   4195   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
   4196   llvm::Value *args[] = { src, dst };
   4197   if (!threadlocal)
   4198     CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(),
   4199                                 args, "globalassign");
   4200   else
   4201     CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(),
   4202                                 args, "threadlocalassign");
   4203   return;
   4204 }
   4205 
   4206 /// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
   4207 /// objc_assign_ivar (id src, id *dst, ptrdiff_t ivaroffset)
   4208 ///
   4209 void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
   4210                                    llvm::Value *src, llvm::Value *dst,
   4211                                    llvm::Value *ivarOffset) {
   4212   assert(ivarOffset && "EmitObjCIvarAssign - ivarOffset is NULL");
   4213   llvm::Type * SrcTy = src->getType();
   4214   if (!isa<llvm::PointerType>(SrcTy)) {
   4215     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
   4216     assert(Size <= 8 && "does not support size > 8");
   4217     src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
   4218       : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
   4219     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
   4220   }
   4221   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
   4222   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
   4223   llvm::Value *args[] = { src, dst, ivarOffset };
   4224   CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args);
   4225   return;
   4226 }
   4227 
   4228 /// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
   4229 /// objc_assign_strongCast (id src, id *dst)
   4230 ///
   4231 void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
   4232                                          llvm::Value *src, llvm::Value *dst) {
   4233   llvm::Type * SrcTy = src->getType();
   4234   if (!isa<llvm::PointerType>(SrcTy)) {
   4235     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
   4236     assert(Size <= 8 && "does not support size > 8");
   4237     src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
   4238       : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
   4239     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
   4240   }
   4241   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
   4242   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
   4243   llvm::Value *args[] = { src, dst };
   4244   CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(),
   4245                               args, "weakassign");
   4246   return;
   4247 }
   4248 
   4249 void CGObjCMac::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
   4250                                          llvm::Value *DestPtr,
   4251                                          llvm::Value *SrcPtr,
   4252                                          llvm::Value *size) {
   4253   SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
   4254   DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
   4255   llvm::Value *args[] = { DestPtr, SrcPtr, size };
   4256   CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args);
   4257 }
   4258 
   4259 /// EmitObjCValueForIvar - Code Gen for ivar reference.
   4260 ///
   4261 LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
   4262                                        QualType ObjectTy,
   4263                                        llvm::Value *BaseValue,
   4264                                        const ObjCIvarDecl *Ivar,
   4265                                        unsigned CVRQualifiers) {
   4266   const ObjCInterfaceDecl *ID =
   4267     ObjectTy->getAs<ObjCObjectType>()->getInterface();
   4268   return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
   4269                                   EmitIvarOffset(CGF, ID, Ivar));
   4270 }
   4271 
   4272 llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
   4273                                        const ObjCInterfaceDecl *Interface,
   4274                                        const ObjCIvarDecl *Ivar) {
   4275   uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
   4276   return llvm::ConstantInt::get(
   4277     CGM.getTypes().ConvertType(CGM.getContext().LongTy),
   4278     Offset);
   4279 }
   4280 
   4281 /* *** Private Interface *** */
   4282 
   4283 /// EmitImageInfo - Emit the image info marker used to encode some module
   4284 /// level information.
   4285 ///
   4286 /// See: <rdr://4810609&4810587&4810587>
   4287 /// struct IMAGE_INFO {
   4288 ///   unsigned version;
   4289 ///   unsigned flags;
   4290 /// };
   4291 enum ImageInfoFlags {
   4292   eImageInfo_FixAndContinue      = (1 << 0),
   4293   eImageInfo_GarbageCollected    = (1 << 1),
   4294   eImageInfo_GCOnly              = (1 << 2),
   4295   eImageInfo_OptimizedByDyld     = (1 << 3), // FIXME: When is this set.
   4296 
   4297   // A flag indicating that the module has no instances of a @synthesize of a
   4298   // superclass variable. <rdar://problem/6803242>
   4299   eImageInfo_CorrectedSynthesize = (1 << 4),
   4300   eImageInfo_ImageIsSimulated    = (1 << 5)
   4301 };
   4302 
   4303 void CGObjCCommonMac::EmitImageInfo() {
   4304   unsigned version = 0; // Version is unused?
   4305   const char *Section = (ObjCABI == 1) ?
   4306     "__OBJC, __image_info,regular" :
   4307     "__DATA, __objc_imageinfo, regular, no_dead_strip";
   4308 
   4309   // Generate module-level named metadata to convey this information to the
   4310   // linker and code-gen.
   4311   llvm::Module &Mod = CGM.getModule();
   4312 
   4313   // Add the ObjC ABI version to the module flags.
   4314   Mod.addModuleFlag(llvm::Module::Error, "Objective-C Version", ObjCABI);
   4315   Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Version",
   4316                     version);
   4317   Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Section",
   4318                     llvm::MDString::get(VMContext,Section));
   4319 
   4320   if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
   4321     // Non-GC overrides those files which specify GC.
   4322     Mod.addModuleFlag(llvm::Module::Override,
   4323                       "Objective-C Garbage Collection", (uint32_t)0);
   4324   } else {
   4325     // Add the ObjC garbage collection value.
   4326     Mod.addModuleFlag(llvm::Module::Error,
   4327                       "Objective-C Garbage Collection",
   4328                       eImageInfo_GarbageCollected);
   4329 
   4330     if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
   4331       // Add the ObjC GC Only value.
   4332       Mod.addModuleFlag(llvm::Module::Error, "Objective-C GC Only",
   4333                         eImageInfo_GCOnly);
   4334 
   4335       // Require that GC be specified and set to eImageInfo_GarbageCollected.
   4336       llvm::Value *Ops[2] = {
   4337         llvm::MDString::get(VMContext, "Objective-C Garbage Collection"),
   4338         llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
   4339                                eImageInfo_GarbageCollected)
   4340       };
   4341       Mod.addModuleFlag(llvm::Module::Require, "Objective-C GC Only",
   4342                         llvm::MDNode::get(VMContext, Ops));
   4343     }
   4344   }
   4345 
   4346   // Indicate whether we're compiling this to run on a simulator.
   4347   const llvm::Triple &Triple = CGM.getTarget().getTriple();
   4348   if (Triple.getOS() == llvm::Triple::IOS &&
   4349       (Triple.getArch() == llvm::Triple::x86 ||
   4350        Triple.getArch() == llvm::Triple::x86_64))
   4351     Mod.addModuleFlag(llvm::Module::Error, "Objective-C Is Simulated",
   4352                       eImageInfo_ImageIsSimulated);
   4353 }
   4354 
   4355 // struct objc_module {
   4356 //   unsigned long version;
   4357 //   unsigned long size;
   4358 //   const char *name;
   4359 //   Symtab symtab;
   4360 // };
   4361 
   4362 // FIXME: Get from somewhere
   4363 static const int ModuleVersion = 7;
   4364 
   4365 void CGObjCMac::EmitModuleInfo() {
   4366   uint64_t Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ModuleTy);
   4367 
   4368   llvm::Constant *Values[] = {
   4369     llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion),
   4370     llvm::ConstantInt::get(ObjCTypes.LongTy, Size),
   4371     // This used to be the filename, now it is unused. <rdr://4327263>
   4372     GetClassName(&CGM.getContext().Idents.get("")),
   4373     EmitModuleSymbols()
   4374   };
   4375   CreateMetadataVar("\01L_OBJC_MODULES",
   4376                     llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
   4377                     "__OBJC,__module_info,regular,no_dead_strip",
   4378                     4, true);
   4379 }
   4380 
   4381 llvm::Constant *CGObjCMac::EmitModuleSymbols() {
   4382   unsigned NumClasses = DefinedClasses.size();
   4383   unsigned NumCategories = DefinedCategories.size();
   4384 
   4385   // Return null if no symbols were defined.
   4386   if (!NumClasses && !NumCategories)
   4387     return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
   4388 
   4389   llvm::Constant *Values[5];
   4390   Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
   4391   Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
   4392   Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
   4393   Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
   4394 
   4395   // The runtime expects exactly the list of defined classes followed
   4396   // by the list of defined categories, in a single array.
   4397   SmallVector<llvm::Constant*, 8> Symbols(NumClasses + NumCategories);
   4398   for (unsigned i=0; i<NumClasses; i++)
   4399     Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
   4400                                                 ObjCTypes.Int8PtrTy);
   4401   for (unsigned i=0; i<NumCategories; i++)
   4402     Symbols[NumClasses + i] =
   4403       llvm::ConstantExpr::getBitCast(DefinedCategories[i],
   4404                                      ObjCTypes.Int8PtrTy);
   4405 
   4406   Values[4] =
   4407     llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
   4408                                                   Symbols.size()),
   4409                              Symbols);
   4410 
   4411   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
   4412 
   4413   llvm::GlobalVariable *GV =
   4414     CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
   4415                       "__OBJC,__symbols,regular,no_dead_strip",
   4416                       4, true);
   4417   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
   4418 }
   4419 
   4420 llvm::Value *CGObjCMac::EmitClassRefFromId(CodeGenFunction &CGF,
   4421                                            IdentifierInfo *II) {
   4422   LazySymbols.insert(II);
   4423 
   4424   llvm::GlobalVariable *&Entry = ClassReferences[II];
   4425 
   4426   if (!Entry) {
   4427     llvm::Constant *Casted =
   4428     llvm::ConstantExpr::getBitCast(GetClassName(II),
   4429                                    ObjCTypes.ClassPtrTy);
   4430     Entry =
   4431     CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
   4432                       "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
   4433                       4, true);
   4434   }
   4435 
   4436   return CGF.Builder.CreateLoad(Entry);
   4437 }
   4438 
   4439 llvm::Value *CGObjCMac::EmitClassRef(CodeGenFunction &CGF,
   4440                                      const ObjCInterfaceDecl *ID) {
   4441   return EmitClassRefFromId(CGF, ID->getIdentifier());
   4442 }
   4443 
   4444 llvm::Value *CGObjCMac::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
   4445   IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
   4446   return EmitClassRefFromId(CGF, II);
   4447 }
   4448 
   4449 llvm::Value *CGObjCMac::EmitSelector(CodeGenFunction &CGF, Selector Sel,
   4450                                      bool lvalue) {
   4451   llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
   4452 
   4453   if (!Entry) {
   4454     llvm::Constant *Casted =
   4455       llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
   4456                                      ObjCTypes.SelectorPtrTy);
   4457     Entry =
   4458       CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
   4459                         "__OBJC,__message_refs,literal_pointers,no_dead_strip",
   4460                         4, true);
   4461     Entry->setExternallyInitialized(true);
   4462   }
   4463 
   4464   if (lvalue)
   4465     return Entry;
   4466   return CGF.Builder.CreateLoad(Entry);
   4467 }
   4468 
   4469 llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
   4470   llvm::GlobalVariable *&Entry = ClassNames[Ident];
   4471 
   4472   if (!Entry)
   4473     Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
   4474                               llvm::ConstantDataArray::getString(VMContext,
   4475                                                          Ident->getNameStart()),
   4476                               ((ObjCABI == 2) ?
   4477                                "__TEXT,__objc_classname,cstring_literals" :
   4478                                "__TEXT,__cstring,cstring_literals"),
   4479                               1, true);
   4480 
   4481   return getConstantGEP(VMContext, Entry, 0, 0);
   4482 }
   4483 
   4484 llvm::Function *CGObjCCommonMac::GetMethodDefinition(const ObjCMethodDecl *MD) {
   4485   llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*>::iterator
   4486       I = MethodDefinitions.find(MD);
   4487   if (I != MethodDefinitions.end())
   4488     return I->second;
   4489 
   4490   return NULL;
   4491 }
   4492 
   4493 /// GetIvarLayoutName - Returns a unique constant for the given
   4494 /// ivar layout bitmap.
   4495 llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
   4496                                        const ObjCCommonTypesHelper &ObjCTypes) {
   4497   return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
   4498 }
   4499 
   4500 void CGObjCCommonMac::BuildAggrIvarRecordLayout(const RecordType *RT,
   4501                                                 unsigned int BytePos,
   4502                                                 bool ForStrongLayout,
   4503                                                 bool &HasUnion) {
   4504   const RecordDecl *RD = RT->getDecl();
   4505   // FIXME - Use iterator.
   4506   SmallVector<const FieldDecl*, 16> Fields;
   4507   for (RecordDecl::field_iterator i = RD->field_begin(),
   4508                                   e = RD->field_end(); i != e; ++i)
   4509     Fields.push_back(*i);
   4510   llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
   4511   const llvm::StructLayout *RecLayout =
   4512     CGM.getDataLayout().getStructLayout(cast<llvm::StructType>(Ty));
   4513 
   4514   BuildAggrIvarLayout(0, RecLayout, RD, Fields, BytePos,
   4515                       ForStrongLayout, HasUnion);
   4516 }
   4517 
   4518 void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
   4519                              const llvm::StructLayout *Layout,
   4520                              const RecordDecl *RD,
   4521                              ArrayRef<const FieldDecl*> RecFields,
   4522                              unsigned int BytePos, bool ForStrongLayout,
   4523                              bool &HasUnion) {
   4524   bool IsUnion = (RD && RD->isUnion());
   4525   uint64_t MaxUnionIvarSize = 0;
   4526   uint64_t MaxSkippedUnionIvarSize = 0;
   4527   const FieldDecl *MaxField = 0;
   4528   const FieldDecl *MaxSkippedField = 0;
   4529   const FieldDecl *LastFieldBitfieldOrUnnamed = 0;
   4530   uint64_t MaxFieldOffset = 0;
   4531   uint64_t MaxSkippedFieldOffset = 0;
   4532   uint64_t LastBitfieldOrUnnamedOffset = 0;
   4533   uint64_t FirstFieldDelta = 0;
   4534 
   4535   if (RecFields.empty())
   4536     return;
   4537   unsigned WordSizeInBits = CGM.getContext().getTargetInfo().getPointerWidth(0);
   4538   unsigned ByteSizeInBits = CGM.getContext().getTargetInfo().getCharWidth();
   4539   if (!RD && CGM.getLangOpts().ObjCAutoRefCount) {
   4540     const FieldDecl *FirstField = RecFields[0];
   4541     FirstFieldDelta =
   4542       ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(FirstField));
   4543   }
   4544 
   4545   for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
   4546     const FieldDecl *Field = RecFields[i];
   4547     uint64_t FieldOffset;
   4548     if (RD) {
   4549       // Note that 'i' here is actually the field index inside RD of Field,
   4550       // although this dependency is hidden.
   4551       const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
   4552       FieldOffset = (RL.getFieldOffset(i) / ByteSizeInBits) - FirstFieldDelta;
   4553     } else
   4554       FieldOffset =
   4555         ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field)) - FirstFieldDelta;
   4556 
   4557     // Skip over unnamed or bitfields
   4558     if (!Field->getIdentifier() || Field->isBitField()) {
   4559       LastFieldBitfieldOrUnnamed = Field;
   4560       LastBitfieldOrUnnamedOffset = FieldOffset;
   4561       continue;
   4562     }
   4563 
   4564     LastFieldBitfieldOrUnnamed = 0;
   4565     QualType FQT = Field->getType();
   4566     if (FQT->isRecordType() || FQT->isUnionType()) {
   4567       if (FQT->isUnionType())
   4568         HasUnion = true;
   4569 
   4570       BuildAggrIvarRecordLayout(FQT->getAs<RecordType>(),
   4571                                 BytePos + FieldOffset,
   4572                                 ForStrongLayout, HasUnion);
   4573       continue;
   4574     }
   4575 
   4576     if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
   4577       const ConstantArrayType *CArray =
   4578         dyn_cast_or_null<ConstantArrayType>(Array);
   4579       uint64_t ElCount = CArray->getSize().getZExtValue();
   4580       assert(CArray && "only array with known element size is supported");
   4581       FQT = CArray->getElementType();
   4582       while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
   4583         const ConstantArrayType *CArray =
   4584           dyn_cast_or_null<ConstantArrayType>(Array);
   4585         ElCount *= CArray->getSize().getZExtValue();
   4586         FQT = CArray->getElementType();
   4587       }
   4588 
   4589       assert(!FQT->isUnionType() &&
   4590              "layout for array of unions not supported");
   4591       if (FQT->isRecordType() && ElCount) {
   4592         int OldIndex = IvarsInfo.size() - 1;
   4593         int OldSkIndex = SkipIvars.size() -1;
   4594 
   4595         const RecordType *RT = FQT->getAs<RecordType>();
   4596         BuildAggrIvarRecordLayout(RT, BytePos + FieldOffset,
   4597                                   ForStrongLayout, HasUnion);
   4598 
   4599         // Replicate layout information for each array element. Note that
   4600         // one element is already done.
   4601         uint64_t ElIx = 1;
   4602         for (int FirstIndex = IvarsInfo.size() - 1,
   4603                FirstSkIndex = SkipIvars.size() - 1 ;ElIx < ElCount; ElIx++) {
   4604           uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
   4605           for (int i = OldIndex+1; i <= FirstIndex; ++i)
   4606             IvarsInfo.push_back(GC_IVAR(IvarsInfo[i].ivar_bytepos + Size*ElIx,
   4607                                         IvarsInfo[i].ivar_size));
   4608           for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i)
   4609             SkipIvars.push_back(GC_IVAR(SkipIvars[i].ivar_bytepos + Size*ElIx,
   4610                                         SkipIvars[i].ivar_size));
   4611         }
   4612         continue;
   4613       }
   4614     }
   4615     // At this point, we are done with Record/Union and array there of.
   4616     // For other arrays we are down to its element type.
   4617     Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), FQT);
   4618 
   4619     unsigned FieldSize = CGM.getContext().getTypeSize(Field->getType());
   4620     if ((ForStrongLayout && GCAttr == Qualifiers::Strong)
   4621         || (!ForStrongLayout && GCAttr == Qualifiers::Weak)) {
   4622       if (IsUnion) {
   4623         uint64_t UnionIvarSize = FieldSize / WordSizeInBits;
   4624         if (UnionIvarSize > MaxUnionIvarSize) {
   4625           MaxUnionIvarSize = UnionIvarSize;
   4626           MaxField = Field;
   4627           MaxFieldOffset = FieldOffset;
   4628         }
   4629       } else {
   4630         IvarsInfo.push_back(GC_IVAR(BytePos + FieldOffset,
   4631                                     FieldSize / WordSizeInBits));
   4632       }
   4633     } else if ((ForStrongLayout &&
   4634                 (GCAttr == Qualifiers::GCNone || GCAttr == Qualifiers::Weak))
   4635                || (!ForStrongLayout && GCAttr != Qualifiers::Weak)) {
   4636       if (IsUnion) {
   4637         // FIXME: Why the asymmetry? We divide by word size in bits on other
   4638         // side.
   4639         uint64_t UnionIvarSize = FieldSize / ByteSizeInBits;
   4640         if (UnionIvarSize > MaxSkippedUnionIvarSize) {
   4641           MaxSkippedUnionIvarSize = UnionIvarSize;
   4642           MaxSkippedField = Field;
   4643           MaxSkippedFieldOffset = FieldOffset;
   4644         }
   4645       } else {
   4646         // FIXME: Why the asymmetry, we divide by byte size in bits here?
   4647         SkipIvars.push_back(GC_IVAR(BytePos + FieldOffset,
   4648                                     FieldSize / ByteSizeInBits));
   4649       }
   4650     }
   4651   }
   4652 
   4653   if (LastFieldBitfieldOrUnnamed) {
   4654     if (LastFieldBitfieldOrUnnamed->isBitField()) {
   4655       // Last field was a bitfield. Must update skip info.
   4656       uint64_t BitFieldSize
   4657           = LastFieldBitfieldOrUnnamed->getBitWidthValue(CGM.getContext());
   4658       GC_IVAR skivar;
   4659       skivar.ivar_bytepos = BytePos + LastBitfieldOrUnnamedOffset;
   4660       skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
   4661         + ((BitFieldSize % ByteSizeInBits) != 0);
   4662       SkipIvars.push_back(skivar);
   4663     } else {
   4664       assert(!LastFieldBitfieldOrUnnamed->getIdentifier() &&"Expected unnamed");
   4665       // Last field was unnamed. Must update skip info.
   4666       unsigned FieldSize
   4667           = CGM.getContext().getTypeSize(LastFieldBitfieldOrUnnamed->getType());
   4668       SkipIvars.push_back(GC_IVAR(BytePos + LastBitfieldOrUnnamedOffset,
   4669                                   FieldSize / ByteSizeInBits));
   4670     }
   4671   }
   4672 
   4673   if (MaxField)
   4674     IvarsInfo.push_back(GC_IVAR(BytePos + MaxFieldOffset,
   4675                                 MaxUnionIvarSize));
   4676   if (MaxSkippedField)
   4677     SkipIvars.push_back(GC_IVAR(BytePos + MaxSkippedFieldOffset,
   4678                                 MaxSkippedUnionIvarSize));
   4679 }
   4680 
   4681 /// BuildIvarLayoutBitmap - This routine is the horsework for doing all
   4682 /// the computations and returning the layout bitmap (for ivar or blocks) in
   4683 /// the given argument BitMap string container. Routine reads
   4684 /// two containers, IvarsInfo and SkipIvars which are assumed to be
   4685 /// filled already by the caller.
   4686 llvm::Constant *CGObjCCommonMac::BuildIvarLayoutBitmap(std::string &BitMap) {
   4687   unsigned int WordsToScan, WordsToSkip;
   4688   llvm::Type *PtrTy = CGM.Int8PtrTy;
   4689 
   4690   // Build the string of skip/scan nibbles
   4691   SmallVector<SKIP_SCAN, 32> SkipScanIvars;
   4692   unsigned int WordSize =
   4693   CGM.getTypes().getDataLayout().getTypeAllocSize(PtrTy);
   4694   if (IvarsInfo[0].ivar_bytepos == 0) {
   4695     WordsToSkip = 0;
   4696     WordsToScan = IvarsInfo[0].ivar_size;
   4697   } else {
   4698     WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
   4699     WordsToScan = IvarsInfo[0].ivar_size;
   4700   }
   4701   for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++) {
   4702     unsigned int TailPrevGCObjC =
   4703     IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
   4704     if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC) {
   4705       // consecutive 'scanned' object pointers.
   4706       WordsToScan += IvarsInfo[i].ivar_size;
   4707     } else {
   4708       // Skip over 'gc'able object pointer which lay over each other.
   4709       if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
   4710         continue;
   4711       // Must skip over 1 or more words. We save current skip/scan values
   4712       //  and start a new pair.
   4713       SKIP_SCAN SkScan;
   4714       SkScan.skip = WordsToSkip;
   4715       SkScan.scan = WordsToScan;
   4716       SkipScanIvars.push_back(SkScan);
   4717 
   4718       // Skip the hole.
   4719       SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
   4720       SkScan.scan = 0;
   4721       SkipScanIvars.push_back(SkScan);
   4722       WordsToSkip = 0;
   4723       WordsToScan = IvarsInfo[i].ivar_size;
   4724     }
   4725   }
   4726   if (WordsToScan > 0) {
   4727     SKIP_SCAN SkScan;
   4728     SkScan.skip = WordsToSkip;
   4729     SkScan.scan = WordsToScan;
   4730     SkipScanIvars.push_back(SkScan);
   4731   }
   4732 
   4733   if (!SkipIvars.empty()) {
   4734     unsigned int LastIndex = SkipIvars.size()-1;
   4735     int LastByteSkipped =
   4736     SkipIvars[LastIndex].ivar_bytepos + SkipIvars[LastIndex].ivar_size;
   4737     LastIndex = IvarsInfo.size()-1;
   4738     int LastByteScanned =
   4739     IvarsInfo[LastIndex].ivar_bytepos +
   4740     IvarsInfo[LastIndex].ivar_size * WordSize;
   4741     // Compute number of bytes to skip at the tail end of the last ivar scanned.
   4742     if (LastByteSkipped > LastByteScanned) {
   4743       unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
   4744       SKIP_SCAN SkScan;
   4745       SkScan.skip = TotalWords - (LastByteScanned/WordSize);
   4746       SkScan.scan = 0;
   4747       SkipScanIvars.push_back(SkScan);
   4748     }
   4749   }
   4750   // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
   4751   // as 0xMN.
   4752   int SkipScan = SkipScanIvars.size()-1;
   4753   for (int i = 0; i <= SkipScan; i++) {
   4754     if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
   4755         && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
   4756       // 0xM0 followed by 0x0N detected.
   4757       SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
   4758       for (int j = i+1; j < SkipScan; j++)
   4759         SkipScanIvars[j] = SkipScanIvars[j+1];
   4760       --SkipScan;
   4761     }
   4762   }
   4763 
   4764   // Generate the string.
   4765   for (int i = 0; i <= SkipScan; i++) {
   4766     unsigned char byte;
   4767     unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
   4768     unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
   4769     unsigned int skip_big  = SkipScanIvars[i].skip / 0xf;
   4770     unsigned int scan_big  = SkipScanIvars[i].scan / 0xf;
   4771 
   4772     // first skip big.
   4773     for (unsigned int ix = 0; ix < skip_big; ix++)
   4774       BitMap += (unsigned char)(0xf0);
   4775 
   4776     // next (skip small, scan)
   4777     if (skip_small) {
   4778       byte = skip_small << 4;
   4779       if (scan_big > 0) {
   4780         byte |= 0xf;
   4781         --scan_big;
   4782       } else if (scan_small) {
   4783         byte |= scan_small;
   4784         scan_small = 0;
   4785       }
   4786       BitMap += byte;
   4787     }
   4788     // next scan big
   4789     for (unsigned int ix = 0; ix < scan_big; ix++)
   4790       BitMap += (unsigned char)(0x0f);
   4791     // last scan small
   4792     if (scan_small) {
   4793       byte = scan_small;
   4794       BitMap += byte;
   4795     }
   4796   }
   4797   // null terminate string.
   4798   unsigned char zero = 0;
   4799   BitMap += zero;
   4800 
   4801   llvm::GlobalVariable * Entry =
   4802   CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
   4803                     llvm::ConstantDataArray::getString(VMContext, BitMap,false),
   4804                     ((ObjCABI == 2) ?
   4805                      "__TEXT,__objc_classname,cstring_literals" :
   4806                      "__TEXT,__cstring,cstring_literals"),
   4807                     1, true);
   4808   return getConstantGEP(VMContext, Entry, 0, 0);
   4809 }
   4810 
   4811 /// BuildIvarLayout - Builds ivar layout bitmap for the class
   4812 /// implementation for the __strong or __weak case.
   4813 /// The layout map displays which words in ivar list must be skipped
   4814 /// and which must be scanned by GC (see below). String is built of bytes.
   4815 /// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
   4816 /// of words to skip and right nibble is count of words to scan. So, each
   4817 /// nibble represents up to 15 workds to skip or scan. Skipping the rest is
   4818 /// represented by a 0x00 byte which also ends the string.
   4819 /// 1. when ForStrongLayout is true, following ivars are scanned:
   4820 /// - id, Class
   4821 /// - object *
   4822 /// - __strong anything
   4823 ///
   4824 /// 2. When ForStrongLayout is false, following ivars are scanned:
   4825 /// - __weak anything
   4826 ///
   4827 llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
   4828   const ObjCImplementationDecl *OMD,
   4829   bool ForStrongLayout) {
   4830   bool hasUnion = false;
   4831 
   4832   llvm::Type *PtrTy = CGM.Int8PtrTy;
   4833   if (CGM.getLangOpts().getGC() == LangOptions::NonGC &&
   4834       !CGM.getLangOpts().ObjCAutoRefCount)
   4835     return llvm::Constant::getNullValue(PtrTy);
   4836 
   4837   const ObjCInterfaceDecl *OI = OMD->getClassInterface();
   4838   SmallVector<const FieldDecl*, 32> RecFields;
   4839   if (CGM.getLangOpts().ObjCAutoRefCount) {
   4840     for (const ObjCIvarDecl *IVD = OI->all_declared_ivar_begin();
   4841          IVD; IVD = IVD->getNextIvar())
   4842       RecFields.push_back(cast<FieldDecl>(IVD));
   4843   }
   4844   else {
   4845     SmallVector<const ObjCIvarDecl*, 32> Ivars;
   4846     CGM.getContext().DeepCollectObjCIvars(OI, true, Ivars);
   4847 
   4848     // FIXME: This is not ideal; we shouldn't have to do this copy.
   4849     RecFields.append(Ivars.begin(), Ivars.end());
   4850   }
   4851 
   4852   if (RecFields.empty())
   4853     return llvm::Constant::getNullValue(PtrTy);
   4854 
   4855   SkipIvars.clear();
   4856   IvarsInfo.clear();
   4857 
   4858   BuildAggrIvarLayout(OMD, 0, 0, RecFields, 0, ForStrongLayout, hasUnion);
   4859   if (IvarsInfo.empty())
   4860     return llvm::Constant::getNullValue(PtrTy);
   4861   // Sort on byte position in case we encounterred a union nested in
   4862   // the ivar list.
   4863   if (hasUnion && !IvarsInfo.empty())
   4864     std::sort(IvarsInfo.begin(), IvarsInfo.end());
   4865   if (hasUnion && !SkipIvars.empty())
   4866     std::sort(SkipIvars.begin(), SkipIvars.end());
   4867 
   4868   std::string BitMap;
   4869   llvm::Constant *C = BuildIvarLayoutBitmap(BitMap);
   4870 
   4871    if (CGM.getLangOpts().ObjCGCBitmapPrint) {
   4872     printf("\n%s ivar layout for class '%s': ",
   4873            ForStrongLayout ? "strong" : "weak",
   4874            OMD->getClassInterface()->getName().data());
   4875     const unsigned char *s = (const unsigned char*)BitMap.c_str();
   4876     for (unsigned i = 0, e = BitMap.size(); i < e; i++)
   4877       if (!(s[i] & 0xf0))
   4878         printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
   4879       else
   4880         printf("0x%x%s",  s[i], s[i] != 0 ? ", " : "");
   4881     printf("\n");
   4882   }
   4883   return C;
   4884 }
   4885 
   4886 llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
   4887   llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
   4888 
   4889   // FIXME: Avoid std::string in "Sel.getAsString()"
   4890   if (!Entry)
   4891     Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
   4892                llvm::ConstantDataArray::getString(VMContext, Sel.getAsString()),
   4893                               ((ObjCABI == 2) ?
   4894                                "__TEXT,__objc_methname,cstring_literals" :
   4895                                "__TEXT,__cstring,cstring_literals"),
   4896                               1, true);
   4897 
   4898   return getConstantGEP(VMContext, Entry, 0, 0);
   4899 }
   4900 
   4901 // FIXME: Merge into a single cstring creation function.
   4902 llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
   4903   return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
   4904 }
   4905 
   4906 llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
   4907   std::string TypeStr;
   4908   CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
   4909 
   4910   llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
   4911 
   4912   if (!Entry)
   4913     Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
   4914                          llvm::ConstantDataArray::getString(VMContext, TypeStr),
   4915                               ((ObjCABI == 2) ?
   4916                                "__TEXT,__objc_methtype,cstring_literals" :
   4917                                "__TEXT,__cstring,cstring_literals"),
   4918                               1, true);
   4919 
   4920   return getConstantGEP(VMContext, Entry, 0, 0);
   4921 }
   4922 
   4923 llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D,
   4924                                                   bool Extended) {
   4925   std::string TypeStr;
   4926   if (CGM.getContext().getObjCEncodingForMethodDecl(D, TypeStr, Extended))
   4927     return 0;
   4928 
   4929   llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
   4930 
   4931   if (!Entry)
   4932     Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
   4933                          llvm::ConstantDataArray::getString(VMContext, TypeStr),
   4934                               ((ObjCABI == 2) ?
   4935                                "__TEXT,__objc_methtype,cstring_literals" :
   4936                                "__TEXT,__cstring,cstring_literals"),
   4937                               1, true);
   4938 
   4939   return getConstantGEP(VMContext, Entry, 0, 0);
   4940 }
   4941 
   4942 // FIXME: Merge into a single cstring creation function.
   4943 llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
   4944   llvm::GlobalVariable *&Entry = PropertyNames[Ident];
   4945 
   4946   if (!Entry)
   4947     Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
   4948                         llvm::ConstantDataArray::getString(VMContext,
   4949                                                        Ident->getNameStart()),
   4950                               "__TEXT,__cstring,cstring_literals",
   4951                               1, true);
   4952 
   4953   return getConstantGEP(VMContext, Entry, 0, 0);
   4954 }
   4955 
   4956 // FIXME: Merge into a single cstring creation function.
   4957 // FIXME: This Decl should be more precise.
   4958 llvm::Constant *
   4959 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
   4960                                        const Decl *Container) {
   4961   std::string TypeStr;
   4962   CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
   4963   return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
   4964 }
   4965 
   4966 void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
   4967                                        const ObjCContainerDecl *CD,
   4968                                        SmallVectorImpl<char> &Name) {
   4969   llvm::raw_svector_ostream OS(Name);
   4970   assert (CD && "Missing container decl in GetNameForMethod");
   4971   OS << '\01' << (D->isInstanceMethod() ? '-' : '+')
   4972      << '[' << CD->getName();
   4973   if (const ObjCCategoryImplDecl *CID =
   4974       dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext()))
   4975     OS << '(' << *CID << ')';
   4976   OS << ' ' << D->getSelector().getAsString() << ']';
   4977 }
   4978 
   4979 void CGObjCMac::FinishModule() {
   4980   EmitModuleInfo();
   4981 
   4982   // Emit the dummy bodies for any protocols which were referenced but
   4983   // never defined.
   4984   for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
   4985          I = Protocols.begin(), e = Protocols.end(); I != e; ++I) {
   4986     if (I->second->hasInitializer())
   4987       continue;
   4988 
   4989     llvm::Constant *Values[5];
   4990     Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
   4991     Values[1] = GetClassName(I->first);
   4992     Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
   4993     Values[3] = Values[4] =
   4994       llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
   4995     I->second->setLinkage(llvm::GlobalValue::InternalLinkage);
   4996     I->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
   4997                                                         Values));
   4998     CGM.AddUsedGlobal(I->second);
   4999   }
   5000 
   5001   // Add assembler directives to add lazy undefined symbol references
   5002   // for classes which are referenced but not defined. This is
   5003   // important for correct linker interaction.
   5004   //
   5005   // FIXME: It would be nice if we had an LLVM construct for this.
   5006   if (!LazySymbols.empty() || !DefinedSymbols.empty()) {
   5007     SmallString<256> Asm;
   5008     Asm += CGM.getModule().getModuleInlineAsm();
   5009     if (!Asm.empty() && Asm.back() != '\n')
   5010       Asm += '\n';
   5011 
   5012     llvm::raw_svector_ostream OS(Asm);
   5013     for (llvm::SetVector<IdentifierInfo*>::iterator I = DefinedSymbols.begin(),
   5014            e = DefinedSymbols.end(); I != e; ++I)
   5015       OS << "\t.objc_class_name_" << (*I)->getName() << "=0\n"
   5016          << "\t.globl .objc_class_name_" << (*I)->getName() << "\n";
   5017     for (llvm::SetVector<IdentifierInfo*>::iterator I = LazySymbols.begin(),
   5018          e = LazySymbols.end(); I != e; ++I) {
   5019       OS << "\t.lazy_reference .objc_class_name_" << (*I)->getName() << "\n";
   5020     }
   5021 
   5022     for (size_t i = 0, e = DefinedCategoryNames.size(); i < e; ++i) {
   5023       OS << "\t.objc_category_name_" << DefinedCategoryNames[i] << "=0\n"
   5024          << "\t.globl .objc_category_name_" << DefinedCategoryNames[i] << "\n";
   5025     }
   5026 
   5027     CGM.getModule().setModuleInlineAsm(OS.str());
   5028   }
   5029 }
   5030 
   5031 CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
   5032   : CGObjCCommonMac(cgm),
   5033     ObjCTypes(cgm) {
   5034   ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
   5035   ObjCABI = 2;
   5036 }
   5037 
   5038 /* *** */
   5039 
   5040 ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
   5041   : VMContext(cgm.getLLVMContext()), CGM(cgm), ExternalProtocolPtrTy(0)
   5042 {
   5043   CodeGen::CodeGenTypes &Types = CGM.getTypes();
   5044   ASTContext &Ctx = CGM.getContext();
   5045 
   5046   ShortTy = Types.ConvertType(Ctx.ShortTy);
   5047   IntTy = Types.ConvertType(Ctx.IntTy);
   5048   LongTy = Types.ConvertType(Ctx.LongTy);
   5049   LongLongTy = Types.ConvertType(Ctx.LongLongTy);
   5050   Int8PtrTy = CGM.Int8PtrTy;
   5051   Int8PtrPtrTy = CGM.Int8PtrPtrTy;
   5052 
   5053   ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
   5054   PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
   5055   SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
   5056 
   5057   // I'm not sure I like this. The implicit coordination is a bit
   5058   // gross. We should solve this in a reasonable fashion because this
   5059   // is a pretty common task (match some runtime data structure with
   5060   // an LLVM data structure).
   5061 
   5062   // FIXME: This is leaked.
   5063   // FIXME: Merge with rewriter code?
   5064 
   5065   // struct _objc_super {
   5066   //   id self;
   5067   //   Class cls;
   5068   // }
   5069   RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct,
   5070                                       Ctx.getTranslationUnitDecl(),
   5071                                       SourceLocation(), SourceLocation(),
   5072                                       &Ctx.Idents.get("_objc_super"));
   5073   RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(), 0,
   5074                                 Ctx.getObjCIdType(), 0, 0, false, ICIS_NoInit));
   5075   RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(), 0,
   5076                                 Ctx.getObjCClassType(), 0, 0, false,
   5077                                 ICIS_NoInit));
   5078   RD->completeDefinition();
   5079 
   5080   SuperCTy = Ctx.getTagDeclType(RD);
   5081   SuperPtrCTy = Ctx.getPointerType(SuperCTy);
   5082 
   5083   SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
   5084   SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
   5085 
   5086   // struct _prop_t {
   5087   //   char *name;
   5088   //   char *attributes;
   5089   // }
   5090   PropertyTy = llvm::StructType::create("struct._prop_t",
   5091                                         Int8PtrTy, Int8PtrTy, NULL);
   5092 
   5093   // struct _prop_list_t {
   5094   //   uint32_t entsize;      // sizeof(struct _prop_t)
   5095   //   uint32_t count_of_properties;
   5096   //   struct _prop_t prop_list[count_of_properties];
   5097   // }
   5098   PropertyListTy =
   5099     llvm::StructType::create("struct._prop_list_t", IntTy, IntTy,
   5100                              llvm::ArrayType::get(PropertyTy, 0), NULL);
   5101   // struct _prop_list_t *
   5102   PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
   5103 
   5104   // struct _objc_method {
   5105   //   SEL _cmd;
   5106   //   char *method_type;
   5107   //   char *_imp;
   5108   // }
   5109   MethodTy = llvm::StructType::create("struct._objc_method",
   5110                                       SelectorPtrTy, Int8PtrTy, Int8PtrTy,
   5111                                       NULL);
   5112 
   5113   // struct _objc_cache *
   5114   CacheTy = llvm::StructType::create(VMContext, "struct._objc_cache");
   5115   CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
   5116 
   5117 }
   5118 
   5119 ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
   5120   : ObjCCommonTypesHelper(cgm) {
   5121   // struct _objc_method_description {
   5122   //   SEL name;
   5123   //   char *types;
   5124   // }
   5125   MethodDescriptionTy =
   5126     llvm::StructType::create("struct._objc_method_description",
   5127                              SelectorPtrTy, Int8PtrTy, NULL);
   5128 
   5129   // struct _objc_method_description_list {
   5130   //   int count;
   5131   //   struct _objc_method_description[1];
   5132   // }
   5133   MethodDescriptionListTy =
   5134     llvm::StructType::create("struct._objc_method_description_list",
   5135                              IntTy,
   5136                              llvm::ArrayType::get(MethodDescriptionTy, 0),NULL);
   5137 
   5138   // struct _objc_method_description_list *
   5139   MethodDescriptionListPtrTy =
   5140     llvm::PointerType::getUnqual(MethodDescriptionListTy);
   5141 
   5142   // Protocol description structures
   5143 
   5144   // struct _objc_protocol_extension {
   5145   //   uint32_t size;  // sizeof(struct _objc_protocol_extension)
   5146   //   struct _objc_method_description_list *optional_instance_methods;
   5147   //   struct _objc_method_description_list *optional_class_methods;
   5148   //   struct _objc_property_list *instance_properties;
   5149   //   const char ** extendedMethodTypes;
   5150   // }
   5151   ProtocolExtensionTy =
   5152     llvm::StructType::create("struct._objc_protocol_extension",
   5153                              IntTy, MethodDescriptionListPtrTy,
   5154                              MethodDescriptionListPtrTy, PropertyListPtrTy,
   5155                              Int8PtrPtrTy, NULL);
   5156 
   5157   // struct _objc_protocol_extension *
   5158   ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
   5159 
   5160   // Handle recursive construction of Protocol and ProtocolList types
   5161 
   5162   ProtocolTy =
   5163     llvm::StructType::create(VMContext, "struct._objc_protocol");
   5164 
   5165   ProtocolListTy =
   5166     llvm::StructType::create(VMContext, "struct._objc_protocol_list");
   5167   ProtocolListTy->setBody(llvm::PointerType::getUnqual(ProtocolListTy),
   5168                           LongTy,
   5169                           llvm::ArrayType::get(ProtocolTy, 0),
   5170                           NULL);
   5171 
   5172   // struct _objc_protocol {
   5173   //   struct _objc_protocol_extension *isa;
   5174   //   char *protocol_name;
   5175   //   struct _objc_protocol **_objc_protocol_list;
   5176   //   struct _objc_method_description_list *instance_methods;
   5177   //   struct _objc_method_description_list *class_methods;
   5178   // }
   5179   ProtocolTy->setBody(ProtocolExtensionPtrTy, Int8PtrTy,
   5180                       llvm::PointerType::getUnqual(ProtocolListTy),
   5181                       MethodDescriptionListPtrTy,
   5182                       MethodDescriptionListPtrTy,
   5183                       NULL);
   5184 
   5185   // struct _objc_protocol_list *
   5186   ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
   5187 
   5188   ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
   5189 
   5190   // Class description structures
   5191 
   5192   // struct _objc_ivar {
   5193   //   char *ivar_name;
   5194   //   char *ivar_type;
   5195   //   int  ivar_offset;
   5196   // }
   5197   IvarTy = llvm::StructType::create("struct._objc_ivar",
   5198                                     Int8PtrTy, Int8PtrTy, IntTy, NULL);
   5199 
   5200   // struct _objc_ivar_list *
   5201   IvarListTy =
   5202     llvm::StructType::create(VMContext, "struct._objc_ivar_list");
   5203   IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
   5204 
   5205   // struct _objc_method_list *
   5206   MethodListTy =
   5207     llvm::StructType::create(VMContext, "struct._objc_method_list");
   5208   MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
   5209 
   5210   // struct _objc_class_extension *
   5211   ClassExtensionTy =
   5212     llvm::StructType::create("struct._objc_class_extension",
   5213                              IntTy, Int8PtrTy, PropertyListPtrTy, NULL);
   5214   ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
   5215 
   5216   ClassTy = llvm::StructType::create(VMContext, "struct._objc_class");
   5217 
   5218   // struct _objc_class {
   5219   //   Class isa;
   5220   //   Class super_class;
   5221   //   char *name;
   5222   //   long version;
   5223   //   long info;
   5224   //   long instance_size;
   5225   //   struct _objc_ivar_list *ivars;
   5226   //   struct _objc_method_list *methods;
   5227   //   struct _objc_cache *cache;
   5228   //   struct _objc_protocol_list *protocols;
   5229   //   char *ivar_layout;
   5230   //   struct _objc_class_ext *ext;
   5231   // };
   5232   ClassTy->setBody(llvm::PointerType::getUnqual(ClassTy),
   5233                    llvm::PointerType::getUnqual(ClassTy),
   5234                    Int8PtrTy,
   5235                    LongTy,
   5236                    LongTy,
   5237                    LongTy,
   5238                    IvarListPtrTy,
   5239                    MethodListPtrTy,
   5240                    CachePtrTy,
   5241                    ProtocolListPtrTy,
   5242                    Int8PtrTy,
   5243                    ClassExtensionPtrTy,
   5244                    NULL);
   5245 
   5246   ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
   5247 
   5248   // struct _objc_category {
   5249   //   char *category_name;
   5250   //   char *class_name;
   5251   //   struct _objc_method_list *instance_method;
   5252   //   struct _objc_method_list *class_method;
   5253   //   uint32_t size;  // sizeof(struct _objc_category)
   5254   //   struct _objc_property_list *instance_properties;// category's @property
   5255   // }
   5256   CategoryTy =
   5257     llvm::StructType::create("struct._objc_category",
   5258                              Int8PtrTy, Int8PtrTy, MethodListPtrTy,
   5259                              MethodListPtrTy, ProtocolListPtrTy,
   5260                              IntTy, PropertyListPtrTy, NULL);
   5261 
   5262   // Global metadata structures
   5263 
   5264   // struct _objc_symtab {
   5265   //   long sel_ref_cnt;
   5266   //   SEL *refs;
   5267   //   short cls_def_cnt;
   5268   //   short cat_def_cnt;
   5269   //   char *defs[cls_def_cnt + cat_def_cnt];
   5270   // }
   5271   SymtabTy =
   5272     llvm::StructType::create("struct._objc_symtab",
   5273                              LongTy, SelectorPtrTy, ShortTy, ShortTy,
   5274                              llvm::ArrayType::get(Int8PtrTy, 0), NULL);
   5275   SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
   5276 
   5277   // struct _objc_module {
   5278   //   long version;
   5279   //   long size;   // sizeof(struct _objc_module)
   5280   //   char *name;
   5281   //   struct _objc_symtab* symtab;
   5282   //  }
   5283   ModuleTy =
   5284     llvm::StructType::create("struct._objc_module",
   5285                              LongTy, LongTy, Int8PtrTy, SymtabPtrTy, NULL);
   5286 
   5287 
   5288   // FIXME: This is the size of the setjmp buffer and should be target
   5289   // specific. 18 is what's used on 32-bit X86.
   5290   uint64_t SetJmpBufferSize = 18;
   5291 
   5292   // Exceptions
   5293   llvm::Type *StackPtrTy = llvm::ArrayType::get(CGM.Int8PtrTy, 4);
   5294 
   5295   ExceptionDataTy =
   5296     llvm::StructType::create("struct._objc_exception_data",
   5297                              llvm::ArrayType::get(CGM.Int32Ty,SetJmpBufferSize),
   5298                              StackPtrTy, NULL);
   5299 
   5300 }
   5301 
   5302 ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
   5303   : ObjCCommonTypesHelper(cgm) {
   5304   // struct _method_list_t {
   5305   //   uint32_t entsize;  // sizeof(struct _objc_method)
   5306   //   uint32_t method_count;
   5307   //   struct _objc_method method_list[method_count];
   5308   // }
   5309   MethodListnfABITy =
   5310     llvm::StructType::create("struct.__method_list_t", IntTy, IntTy,
   5311                              llvm::ArrayType::get(MethodTy, 0), NULL);
   5312   // struct method_list_t *
   5313   MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
   5314 
   5315   // struct _protocol_t {
   5316   //   id isa;  // NULL
   5317   //   const char * const protocol_name;
   5318   //   const struct _protocol_list_t * protocol_list; // super protocols
   5319   //   const struct method_list_t * const instance_methods;
   5320   //   const struct method_list_t * const class_methods;
   5321   //   const struct method_list_t *optionalInstanceMethods;
   5322   //   const struct method_list_t *optionalClassMethods;
   5323   //   const struct _prop_list_t * properties;
   5324   //   const uint32_t size;  // sizeof(struct _protocol_t)
   5325   //   const uint32_t flags;  // = 0
   5326   //   const char ** extendedMethodTypes;
   5327   // }
   5328 
   5329   // Holder for struct _protocol_list_t *
   5330   ProtocolListnfABITy =
   5331     llvm::StructType::create(VMContext, "struct._objc_protocol_list");
   5332 
   5333   ProtocolnfABITy =
   5334     llvm::StructType::create("struct._protocol_t", ObjectPtrTy, Int8PtrTy,
   5335                              llvm::PointerType::getUnqual(ProtocolListnfABITy),
   5336                              MethodListnfABIPtrTy, MethodListnfABIPtrTy,
   5337                              MethodListnfABIPtrTy, MethodListnfABIPtrTy,
   5338                              PropertyListPtrTy, IntTy, IntTy, Int8PtrPtrTy,
   5339                              NULL);
   5340 
   5341   // struct _protocol_t*
   5342   ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
   5343 
   5344   // struct _protocol_list_t {
   5345   //   long protocol_count;   // Note, this is 32/64 bit
   5346   //   struct _protocol_t *[protocol_count];
   5347   // }
   5348   ProtocolListnfABITy->setBody(LongTy,
   5349                                llvm::ArrayType::get(ProtocolnfABIPtrTy, 0),
   5350                                NULL);
   5351 
   5352   // struct _objc_protocol_list*
   5353   ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
   5354 
   5355   // struct _ivar_t {
   5356   //   unsigned long int *offset;  // pointer to ivar offset location
   5357   //   char *name;
   5358   //   char *type;
   5359   //   uint32_t alignment;
   5360   //   uint32_t size;
   5361   // }
   5362   IvarnfABITy =
   5363     llvm::StructType::create("struct._ivar_t",
   5364                              llvm::PointerType::getUnqual(LongTy),
   5365                              Int8PtrTy, Int8PtrTy, IntTy, IntTy, NULL);
   5366 
   5367   // struct _ivar_list_t {
   5368   //   uint32 entsize;  // sizeof(struct _ivar_t)
   5369   //   uint32 count;
   5370   //   struct _iver_t list[count];
   5371   // }
   5372   IvarListnfABITy =
   5373     llvm::StructType::create("struct._ivar_list_t", IntTy, IntTy,
   5374                              llvm::ArrayType::get(IvarnfABITy, 0), NULL);
   5375 
   5376   IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
   5377 
   5378   // struct _class_ro_t {
   5379   //   uint32_t const flags;
   5380   //   uint32_t const instanceStart;
   5381   //   uint32_t const instanceSize;
   5382   //   uint32_t const reserved;  // only when building for 64bit targets
   5383   //   const uint8_t * const ivarLayout;
   5384   //   const char *const name;
   5385   //   const struct _method_list_t * const baseMethods;
   5386   //   const struct _objc_protocol_list *const baseProtocols;
   5387   //   const struct _ivar_list_t *const ivars;
   5388   //   const uint8_t * const weakIvarLayout;
   5389   //   const struct _prop_list_t * const properties;
   5390   // }
   5391 
   5392   // FIXME. Add 'reserved' field in 64bit abi mode!
   5393   ClassRonfABITy = llvm::StructType::create("struct._class_ro_t",
   5394                                             IntTy, IntTy, IntTy, Int8PtrTy,
   5395                                             Int8PtrTy, MethodListnfABIPtrTy,
   5396                                             ProtocolListnfABIPtrTy,
   5397                                             IvarListnfABIPtrTy,
   5398                                             Int8PtrTy, PropertyListPtrTy, NULL);
   5399 
   5400   // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
   5401   llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
   5402   ImpnfABITy = llvm::FunctionType::get(ObjectPtrTy, params, false)
   5403                  ->getPointerTo();
   5404 
   5405   // struct _class_t {
   5406   //   struct _class_t *isa;
   5407   //   struct _class_t * const superclass;
   5408   //   void *cache;
   5409   //   IMP *vtable;
   5410   //   struct class_ro_t *ro;
   5411   // }
   5412 
   5413   ClassnfABITy = llvm::StructType::create(VMContext, "struct._class_t");
   5414   ClassnfABITy->setBody(llvm::PointerType::getUnqual(ClassnfABITy),
   5415                         llvm::PointerType::getUnqual(ClassnfABITy),
   5416                         CachePtrTy,
   5417                         llvm::PointerType::getUnqual(ImpnfABITy),
   5418                         llvm::PointerType::getUnqual(ClassRonfABITy),
   5419                         NULL);
   5420 
   5421   // LLVM for struct _class_t *
   5422   ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
   5423 
   5424   // struct _category_t {
   5425   //   const char * const name;
   5426   //   struct _class_t *const cls;
   5427   //   const struct _method_list_t * const instance_methods;
   5428   //   const struct _method_list_t * const class_methods;
   5429   //   const struct _protocol_list_t * const protocols;
   5430   //   const struct _prop_list_t * const properties;
   5431   // }
   5432   CategorynfABITy = llvm::StructType::create("struct._category_t",
   5433                                              Int8PtrTy, ClassnfABIPtrTy,
   5434                                              MethodListnfABIPtrTy,
   5435                                              MethodListnfABIPtrTy,
   5436                                              ProtocolListnfABIPtrTy,
   5437                                              PropertyListPtrTy,
   5438                                              NULL);
   5439 
   5440   // New types for nonfragile abi messaging.
   5441   CodeGen::CodeGenTypes &Types = CGM.getTypes();
   5442   ASTContext &Ctx = CGM.getContext();
   5443 
   5444   // MessageRefTy - LLVM for:
   5445   // struct _message_ref_t {
   5446   //   IMP messenger;
   5447   //   SEL name;
   5448   // };
   5449 
   5450   // First the clang type for struct _message_ref_t
   5451   RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct,
   5452                                       Ctx.getTranslationUnitDecl(),
   5453                                       SourceLocation(), SourceLocation(),
   5454                                       &Ctx.Idents.get("_message_ref_t"));
   5455   RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(), 0,
   5456                                 Ctx.VoidPtrTy, 0, 0, false, ICIS_NoInit));
   5457   RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(), 0,
   5458                                 Ctx.getObjCSelType(), 0, 0, false,
   5459                                 ICIS_NoInit));
   5460   RD->completeDefinition();
   5461 
   5462   MessageRefCTy = Ctx.getTagDeclType(RD);
   5463   MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
   5464   MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
   5465 
   5466   // MessageRefPtrTy - LLVM for struct _message_ref_t*
   5467   MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
   5468 
   5469   // SuperMessageRefTy - LLVM for:
   5470   // struct _super_message_ref_t {
   5471   //   SUPER_IMP messenger;
   5472   //   SEL name;
   5473   // };
   5474   SuperMessageRefTy =
   5475     llvm::StructType::create("struct._super_message_ref_t",
   5476                              ImpnfABITy, SelectorPtrTy, NULL);
   5477 
   5478   // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
   5479   SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
   5480 
   5481 
   5482   // struct objc_typeinfo {
   5483   //   const void** vtable; // objc_ehtype_vtable + 2
   5484   //   const char*  name;    // c++ typeinfo string
   5485   //   Class        cls;
   5486   // };
   5487   EHTypeTy =
   5488     llvm::StructType::create("struct._objc_typeinfo",
   5489                              llvm::PointerType::getUnqual(Int8PtrTy),
   5490                              Int8PtrTy, ClassnfABIPtrTy, NULL);
   5491   EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
   5492 }
   5493 
   5494 llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
   5495   FinishNonFragileABIModule();
   5496 
   5497   return NULL;
   5498 }
   5499 
   5500 void CGObjCNonFragileABIMac::
   5501 AddModuleClassList(ArrayRef<llvm::GlobalValue*> Container,
   5502                    const char *SymbolName,
   5503                    const char *SectionName) {
   5504   unsigned NumClasses = Container.size();
   5505 
   5506   if (!NumClasses)
   5507     return;
   5508 
   5509   SmallVector<llvm::Constant*, 8> Symbols(NumClasses);
   5510   for (unsigned i=0; i<NumClasses; i++)
   5511     Symbols[i] = llvm::ConstantExpr::getBitCast(Container[i],
   5512                                                 ObjCTypes.Int8PtrTy);
   5513   llvm::Constant *Init =
   5514     llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
   5515                                                   Symbols.size()),
   5516                              Symbols);
   5517 
   5518   llvm::GlobalVariable *GV =
   5519     new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
   5520                              llvm::GlobalValue::InternalLinkage,
   5521                              Init,
   5522                              SymbolName);
   5523   GV->setAlignment(CGM.getDataLayout().getABITypeAlignment(Init->getType()));
   5524   GV->setSection(SectionName);
   5525   CGM.AddUsedGlobal(GV);
   5526 }
   5527 
   5528 void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
   5529   // nonfragile abi has no module definition.
   5530 
   5531   // Build list of all implemented class addresses in array
   5532   // L_OBJC_LABEL_CLASS_$.
   5533   AddModuleClassList(DefinedClasses,
   5534                      "\01L_OBJC_LABEL_CLASS_$",
   5535                      "__DATA, __objc_classlist, regular, no_dead_strip");
   5536 
   5537   for (unsigned i = 0, e = DefinedClasses.size(); i < e; i++) {
   5538     llvm::GlobalValue *IMPLGV = DefinedClasses[i];
   5539     if (IMPLGV->getLinkage() != llvm::GlobalValue::ExternalWeakLinkage)
   5540       continue;
   5541     IMPLGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
   5542   }
   5543 
   5544   for (unsigned i = 0, e = DefinedMetaClasses.size(); i < e; i++) {
   5545     llvm::GlobalValue *IMPLGV = DefinedMetaClasses[i];
   5546     if (IMPLGV->getLinkage() != llvm::GlobalValue::ExternalWeakLinkage)
   5547       continue;
   5548     IMPLGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
   5549   }
   5550 
   5551   AddModuleClassList(DefinedNonLazyClasses,
   5552                      "\01L_OBJC_LABEL_NONLAZY_CLASS_$",
   5553                      "__DATA, __objc_nlclslist, regular, no_dead_strip");
   5554 
   5555   // Build list of all implemented category addresses in array
   5556   // L_OBJC_LABEL_CATEGORY_$.
   5557   AddModuleClassList(DefinedCategories,
   5558                      "\01L_OBJC_LABEL_CATEGORY_$",
   5559                      "__DATA, __objc_catlist, regular, no_dead_strip");
   5560   AddModuleClassList(DefinedNonLazyCategories,
   5561                      "\01L_OBJC_LABEL_NONLAZY_CATEGORY_$",
   5562                      "__DATA, __objc_nlcatlist, regular, no_dead_strip");
   5563 
   5564   EmitImageInfo();
   5565 }
   5566 
   5567 /// isVTableDispatchedSelector - Returns true if SEL is not in the list of
   5568 /// VTableDispatchMethods; false otherwise. What this means is that
   5569 /// except for the 19 selectors in the list, we generate 32bit-style
   5570 /// message dispatch call for all the rest.
   5571 bool CGObjCNonFragileABIMac::isVTableDispatchedSelector(Selector Sel) {
   5572   // At various points we've experimented with using vtable-based
   5573   // dispatch for all methods.
   5574   switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
   5575   case CodeGenOptions::Legacy:
   5576     return false;
   5577   case CodeGenOptions::NonLegacy:
   5578     return true;
   5579   case CodeGenOptions::Mixed:
   5580     break;
   5581   }
   5582 
   5583   // If so, see whether this selector is in the white-list of things which must
   5584   // use the new dispatch convention. We lazily build a dense set for this.
   5585   if (VTableDispatchMethods.empty()) {
   5586     VTableDispatchMethods.insert(GetNullarySelector("alloc"));
   5587     VTableDispatchMethods.insert(GetNullarySelector("class"));
   5588     VTableDispatchMethods.insert(GetNullarySelector("self"));
   5589     VTableDispatchMethods.insert(GetNullarySelector("isFlipped"));
   5590     VTableDispatchMethods.insert(GetNullarySelector("length"));
   5591     VTableDispatchMethods.insert(GetNullarySelector("count"));
   5592 
   5593     // These are vtable-based if GC is disabled.
   5594     // Optimistically use vtable dispatch for hybrid compiles.
   5595     if (CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
   5596       VTableDispatchMethods.insert(GetNullarySelector("retain"));
   5597       VTableDispatchMethods.insert(GetNullarySelector("release"));
   5598       VTableDispatchMethods.insert(GetNullarySelector("autorelease"));
   5599     }
   5600 
   5601     VTableDispatchMethods.insert(GetUnarySelector("allocWithZone"));
   5602     VTableDispatchMethods.insert(GetUnarySelector("isKindOfClass"));
   5603     VTableDispatchMethods.insert(GetUnarySelector("respondsToSelector"));
   5604     VTableDispatchMethods.insert(GetUnarySelector("objectForKey"));
   5605     VTableDispatchMethods.insert(GetUnarySelector("objectAtIndex"));
   5606     VTableDispatchMethods.insert(GetUnarySelector("isEqualToString"));
   5607     VTableDispatchMethods.insert(GetUnarySelector("isEqual"));
   5608 
   5609     // These are vtable-based if GC is enabled.
   5610     // Optimistically use vtable dispatch for hybrid compiles.
   5611     if (CGM.getLangOpts().getGC() != LangOptions::NonGC) {
   5612       VTableDispatchMethods.insert(GetNullarySelector("hash"));
   5613       VTableDispatchMethods.insert(GetUnarySelector("addObject"));
   5614 
   5615       // "countByEnumeratingWithState:objects:count"
   5616       IdentifierInfo *KeyIdents[] = {
   5617         &CGM.getContext().Idents.get("countByEnumeratingWithState"),
   5618         &CGM.getContext().Idents.get("objects"),
   5619         &CGM.getContext().Idents.get("count")
   5620       };
   5621       VTableDispatchMethods.insert(
   5622         CGM.getContext().Selectors.getSelector(3, KeyIdents));
   5623     }
   5624   }
   5625 
   5626   return VTableDispatchMethods.count(Sel);
   5627 }
   5628 
   5629 /// BuildClassRoTInitializer - generate meta-data for:
   5630 /// struct _class_ro_t {
   5631 ///   uint32_t const flags;
   5632 ///   uint32_t const instanceStart;
   5633 ///   uint32_t const instanceSize;
   5634 ///   uint32_t const reserved;  // only when building for 64bit targets
   5635 ///   const uint8_t * const ivarLayout;
   5636 ///   const char *const name;
   5637 ///   const struct _method_list_t * const baseMethods;
   5638 ///   const struct _protocol_list_t *const baseProtocols;
   5639 ///   const struct _ivar_list_t *const ivars;
   5640 ///   const uint8_t * const weakIvarLayout;
   5641 ///   const struct _prop_list_t * const properties;
   5642 /// }
   5643 ///
   5644 llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
   5645   unsigned flags,
   5646   unsigned InstanceStart,
   5647   unsigned InstanceSize,
   5648   const ObjCImplementationDecl *ID) {
   5649   std::string ClassName = ID->getNameAsString();
   5650   llvm::Constant *Values[10]; // 11 for 64bit targets!
   5651 
   5652   if (CGM.getLangOpts().ObjCAutoRefCount)
   5653     flags |= NonFragileABI_Class_CompiledByARC;
   5654 
   5655   Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
   5656   Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
   5657   Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
   5658   // FIXME. For 64bit targets add 0 here.
   5659   Values[ 3] = (flags & NonFragileABI_Class_Meta)
   5660     ? GetIvarLayoutName(0, ObjCTypes)
   5661     : BuildIvarLayout(ID, true);
   5662   Values[ 4] = GetClassName(ID->getIdentifier());
   5663   // const struct _method_list_t * const baseMethods;
   5664   std::vector<llvm::Constant*> Methods;
   5665   std::string MethodListName("\01l_OBJC_$_");
   5666   if (flags & NonFragileABI_Class_Meta) {
   5667     MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
   5668     for (ObjCImplementationDecl::classmeth_iterator
   5669            i = ID->classmeth_begin(), e = ID->classmeth_end(); i != e; ++i) {
   5670       // Class methods should always be defined.
   5671       Methods.push_back(GetMethodConstant(*i));
   5672     }
   5673   } else {
   5674     MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
   5675     for (ObjCImplementationDecl::instmeth_iterator
   5676            i = ID->instmeth_begin(), e = ID->instmeth_end(); i != e; ++i) {
   5677       // Instance methods should always be defined.
   5678       Methods.push_back(GetMethodConstant(*i));
   5679     }
   5680     for (ObjCImplementationDecl::propimpl_iterator
   5681            i = ID->propimpl_begin(), e = ID->propimpl_end(); i != e; ++i) {
   5682       ObjCPropertyImplDecl *PID = *i;
   5683 
   5684       if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
   5685         ObjCPropertyDecl *PD = PID->getPropertyDecl();
   5686 
   5687         if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
   5688           if (llvm::Constant *C = GetMethodConstant(MD))
   5689             Methods.push_back(C);
   5690         if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
   5691           if (llvm::Constant *C = GetMethodConstant(MD))
   5692             Methods.push_back(C);
   5693       }
   5694     }
   5695   }
   5696   Values[ 5] = EmitMethodList(MethodListName,
   5697                               "__DATA, __objc_const", Methods);
   5698 
   5699   const ObjCInterfaceDecl *OID = ID->getClassInterface();
   5700   assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
   5701   Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
   5702                                 + OID->getName(),
   5703                                 OID->all_referenced_protocol_begin(),
   5704                                 OID->all_referenced_protocol_end());
   5705 
   5706   if (flags & NonFragileABI_Class_Meta) {
   5707     Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
   5708     Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
   5709     Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
   5710   } else {
   5711     Values[ 7] = EmitIvarList(ID);
   5712     Values[ 8] = BuildIvarLayout(ID, false);
   5713     Values[ 9] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getName(),
   5714                                   ID, ID->getClassInterface(), ObjCTypes);
   5715   }
   5716   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
   5717                                                    Values);
   5718   llvm::GlobalVariable *CLASS_RO_GV =
   5719     new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassRonfABITy, false,
   5720                              llvm::GlobalValue::InternalLinkage,
   5721                              Init,
   5722                              (flags & NonFragileABI_Class_Meta) ?
   5723                              std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
   5724                              std::string("\01l_OBJC_CLASS_RO_$_")+ClassName);
   5725   CLASS_RO_GV->setAlignment(
   5726     CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ClassRonfABITy));
   5727   CLASS_RO_GV->setSection("__DATA, __objc_const");
   5728   return CLASS_RO_GV;
   5729 
   5730 }
   5731 
   5732 /// BuildClassMetaData - This routine defines that to-level meta-data
   5733 /// for the given ClassName for:
   5734 /// struct _class_t {
   5735 ///   struct _class_t *isa;
   5736 ///   struct _class_t * const superclass;
   5737 ///   void *cache;
   5738 ///   IMP *vtable;
   5739 ///   struct class_ro_t *ro;
   5740 /// }
   5741 ///
   5742 llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassMetaData(
   5743   std::string &ClassName,
   5744   llvm::Constant *IsAGV,
   5745   llvm::Constant *SuperClassGV,
   5746   llvm::Constant *ClassRoGV,
   5747   bool HiddenVisibility) {
   5748   llvm::Constant *Values[] = {
   5749     IsAGV,
   5750     SuperClassGV,
   5751     ObjCEmptyCacheVar,  // &ObjCEmptyCacheVar
   5752     ObjCEmptyVtableVar, // &ObjCEmptyVtableVar
   5753     ClassRoGV           // &CLASS_RO_GV
   5754   };
   5755   if (!Values[1])
   5756     Values[1] = llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
   5757   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
   5758                                                    Values);
   5759   llvm::GlobalVariable *GV = GetClassGlobal(ClassName);
   5760   GV->setInitializer(Init);
   5761   GV->setSection("__DATA, __objc_data");
   5762   GV->setAlignment(
   5763     CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ClassnfABITy));
   5764   if (HiddenVisibility)
   5765     GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
   5766   return GV;
   5767 }
   5768 
   5769 bool
   5770 CGObjCNonFragileABIMac::ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
   5771   return OD->getClassMethod(GetNullarySelector("load")) != 0;
   5772 }
   5773 
   5774 void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
   5775                                               uint32_t &InstanceStart,
   5776                                               uint32_t &InstanceSize) {
   5777   const ASTRecordLayout &RL =
   5778     CGM.getContext().getASTObjCImplementationLayout(OID);
   5779 
   5780   // InstanceSize is really instance end.
   5781   InstanceSize = RL.getDataSize().getQuantity();
   5782 
   5783   // If there are no fields, the start is the same as the end.
   5784   if (!RL.getFieldCount())
   5785     InstanceStart = InstanceSize;
   5786   else
   5787     InstanceStart = RL.getFieldOffset(0) / CGM.getContext().getCharWidth();
   5788 }
   5789 
   5790 void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
   5791   std::string ClassName = ID->getNameAsString();
   5792   if (!ObjCEmptyCacheVar) {
   5793     ObjCEmptyCacheVar = new llvm::GlobalVariable(
   5794       CGM.getModule(),
   5795       ObjCTypes.CacheTy,
   5796       false,
   5797       llvm::GlobalValue::ExternalLinkage,
   5798       0,
   5799       "_objc_empty_cache");
   5800 
   5801     ObjCEmptyVtableVar = new llvm::GlobalVariable(
   5802       CGM.getModule(),
   5803       ObjCTypes.ImpnfABITy,
   5804       false,
   5805       llvm::GlobalValue::ExternalLinkage,
   5806       0,
   5807       "_objc_empty_vtable");
   5808   }
   5809   assert(ID->getClassInterface() &&
   5810          "CGObjCNonFragileABIMac::GenerateClass - class is 0");
   5811   // FIXME: Is this correct (that meta class size is never computed)?
   5812   uint32_t InstanceStart =
   5813     CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassnfABITy);
   5814   uint32_t InstanceSize = InstanceStart;
   5815   uint32_t flags = NonFragileABI_Class_Meta;
   5816   std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
   5817   std::string ObjCClassName(getClassSymbolPrefix());
   5818 
   5819   llvm::GlobalVariable *SuperClassGV, *IsAGV;
   5820 
   5821   // Build the flags for the metaclass.
   5822   bool classIsHidden =
   5823     ID->getClassInterface()->getVisibility() == HiddenVisibility;
   5824   if (classIsHidden)
   5825     flags |= NonFragileABI_Class_Hidden;
   5826 
   5827   // FIXME: why is this flag set on the metaclass?
   5828   // ObjC metaclasses have no fields and don't really get constructed.
   5829   if (ID->hasNonZeroConstructors() || ID->hasDestructors()) {
   5830     flags |= NonFragileABI_Class_HasCXXStructors;
   5831     if (!ID->hasNonZeroConstructors())
   5832       flags |= NonFragileABI_Class_HasCXXDestructorOnly;
   5833   }
   5834 
   5835   if (!ID->getClassInterface()->getSuperClass()) {
   5836     // class is root
   5837     flags |= NonFragileABI_Class_Root;
   5838     SuperClassGV = GetClassGlobal(ObjCClassName + ClassName);
   5839     IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName);
   5840   } else {
   5841     // Has a root. Current class is not a root.
   5842     const ObjCInterfaceDecl *Root = ID->getClassInterface();
   5843     while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
   5844       Root = Super;
   5845     IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString());
   5846     if (Root->isWeakImported())
   5847       IsAGV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
   5848     // work on super class metadata symbol.
   5849     std::string SuperClassName =
   5850       ObjCMetaClassName +
   5851         ID->getClassInterface()->getSuperClass()->getNameAsString();
   5852     SuperClassGV = GetClassGlobal(SuperClassName);
   5853     if (ID->getClassInterface()->getSuperClass()->isWeakImported())
   5854       SuperClassGV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
   5855   }
   5856   llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
   5857                                                                InstanceStart,
   5858                                                                InstanceSize,ID);
   5859   std::string TClassName = ObjCMetaClassName + ClassName;
   5860   llvm::GlobalVariable *MetaTClass =
   5861     BuildClassMetaData(TClassName, IsAGV, SuperClassGV, CLASS_RO_GV,
   5862                        classIsHidden);
   5863   DefinedMetaClasses.push_back(MetaTClass);
   5864 
   5865   // Metadata for the class
   5866   flags = 0;
   5867   if (classIsHidden)
   5868     flags |= NonFragileABI_Class_Hidden;
   5869 
   5870   if (ID->hasNonZeroConstructors() || ID->hasDestructors()) {
   5871     flags |= NonFragileABI_Class_HasCXXStructors;
   5872 
   5873     // Set a flag to enable a runtime optimization when a class has
   5874     // fields that require destruction but which don't require
   5875     // anything except zero-initialization during construction.  This
   5876     // is most notably true of __strong and __weak types, but you can
   5877     // also imagine there being C++ types with non-trivial default
   5878     // constructors that merely set all fields to null.
   5879     if (!ID->hasNonZeroConstructors())
   5880       flags |= NonFragileABI_Class_HasCXXDestructorOnly;
   5881   }
   5882 
   5883   if (hasObjCExceptionAttribute(CGM.getContext(), ID->getClassInterface()))
   5884     flags |= NonFragileABI_Class_Exception;
   5885 
   5886   if (!ID->getClassInterface()->getSuperClass()) {
   5887     flags |= NonFragileABI_Class_Root;
   5888     SuperClassGV = 0;
   5889   } else {
   5890     // Has a root. Current class is not a root.
   5891     std::string RootClassName =
   5892       ID->getClassInterface()->getSuperClass()->getNameAsString();
   5893     SuperClassGV = GetClassGlobal(ObjCClassName + RootClassName);
   5894     if (ID->getClassInterface()->getSuperClass()->isWeakImported())
   5895       SuperClassGV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
   5896   }
   5897   GetClassSizeInfo(ID, InstanceStart, InstanceSize);
   5898   CLASS_RO_GV = BuildClassRoTInitializer(flags,
   5899                                          InstanceStart,
   5900                                          InstanceSize,
   5901                                          ID);
   5902 
   5903   TClassName = ObjCClassName + ClassName;
   5904   llvm::GlobalVariable *ClassMD =
   5905     BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
   5906                        classIsHidden);
   5907   DefinedClasses.push_back(ClassMD);
   5908 
   5909   // Determine if this class is also "non-lazy".
   5910   if (ImplementationIsNonLazy(ID))
   5911     DefinedNonLazyClasses.push_back(ClassMD);
   5912 
   5913   // Force the definition of the EHType if necessary.
   5914   if (flags & NonFragileABI_Class_Exception)
   5915     GetInterfaceEHType(ID->getClassInterface(), true);
   5916   // Make sure method definition entries are all clear for next implementation.
   5917   MethodDefinitions.clear();
   5918 }
   5919 
   5920 /// GenerateProtocolRef - This routine is called to generate code for
   5921 /// a protocol reference expression; as in:
   5922 /// @code
   5923 ///   @protocol(Proto1);
   5924 /// @endcode
   5925 /// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
   5926 /// which will hold address of the protocol meta-data.
   5927 ///
   5928 llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CodeGenFunction &CGF,
   5929                                                          const ObjCProtocolDecl *PD) {
   5930 
   5931   // This routine is called for @protocol only. So, we must build definition
   5932   // of protocol's meta-data (not a reference to it!)
   5933   //
   5934   llvm::Constant *Init =
   5935     llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
   5936                                    ObjCTypes.getExternalProtocolPtrTy());
   5937 
   5938   std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
   5939   ProtocolName += PD->getName();
   5940 
   5941   llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
   5942   if (PTGV)
   5943     return CGF.Builder.CreateLoad(PTGV);
   5944   PTGV = new llvm::GlobalVariable(
   5945     CGM.getModule(),
   5946     Init->getType(), false,
   5947     llvm::GlobalValue::WeakAnyLinkage,
   5948     Init,
   5949     ProtocolName);
   5950   PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
   5951   PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
   5952   CGM.AddUsedGlobal(PTGV);
   5953   return CGF.Builder.CreateLoad(PTGV);
   5954 }
   5955 
   5956 /// GenerateCategory - Build metadata for a category implementation.
   5957 /// struct _category_t {
   5958 ///   const char * const name;
   5959 ///   struct _class_t *const cls;
   5960 ///   const struct _method_list_t * const instance_methods;
   5961 ///   const struct _method_list_t * const class_methods;
   5962 ///   const struct _protocol_list_t * const protocols;
   5963 ///   const struct _prop_list_t * const properties;
   5964 /// }
   5965 ///
   5966 void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
   5967   const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
   5968   const char *Prefix = "\01l_OBJC_$_CATEGORY_";
   5969   std::string ExtCatName(Prefix + Interface->getNameAsString()+
   5970                          "_$_" + OCD->getNameAsString());
   5971   std::string ExtClassName(getClassSymbolPrefix() +
   5972                            Interface->getNameAsString());
   5973 
   5974   llvm::Constant *Values[6];
   5975   Values[0] = GetClassName(OCD->getIdentifier());
   5976   // meta-class entry symbol
   5977   llvm::GlobalVariable *ClassGV = GetClassGlobal(ExtClassName);
   5978   if (Interface->isWeakImported())
   5979     ClassGV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
   5980 
   5981   Values[1] = ClassGV;
   5982   std::vector<llvm::Constant*> Methods;
   5983   std::string MethodListName(Prefix);
   5984   MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
   5985     "_$_" + OCD->getNameAsString();
   5986 
   5987   for (ObjCCategoryImplDecl::instmeth_iterator
   5988          i = OCD->instmeth_begin(), e = OCD->instmeth_end(); i != e; ++i) {
   5989     // Instance methods should always be defined.
   5990     Methods.push_back(GetMethodConstant(*i));
   5991   }
   5992 
   5993   Values[2] = EmitMethodList(MethodListName,
   5994                              "__DATA, __objc_const",
   5995                              Methods);
   5996 
   5997   MethodListName = Prefix;
   5998   MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
   5999     OCD->getNameAsString();
   6000   Methods.clear();
   6001   for (ObjCCategoryImplDecl::classmeth_iterator
   6002          i = OCD->classmeth_begin(), e = OCD->classmeth_end(); i != e; ++i) {
   6003     // Class methods should always be defined.
   6004     Methods.push_back(GetMethodConstant(*i));
   6005   }
   6006 
   6007   Values[3] = EmitMethodList(MethodListName,
   6008                              "__DATA, __objc_const",
   6009                              Methods);
   6010   const ObjCCategoryDecl *Category =
   6011     Interface->FindCategoryDeclaration(OCD->getIdentifier());
   6012   if (Category) {
   6013     SmallString<256> ExtName;
   6014     llvm::raw_svector_ostream(ExtName) << Interface->getName() << "_$_"
   6015                                        << OCD->getName();
   6016     Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
   6017                                  + Interface->getName() + "_$_"
   6018                                  + Category->getName(),
   6019                                  Category->protocol_begin(),
   6020                                  Category->protocol_end());
   6021     Values[5] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(),
   6022                                  OCD, Category, ObjCTypes);
   6023   } else {
   6024     Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
   6025     Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
   6026   }
   6027 
   6028   llvm::Constant *Init =
   6029     llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
   6030                               Values);
   6031   llvm::GlobalVariable *GCATV
   6032     = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.CategorynfABITy,
   6033                                false,
   6034                                llvm::GlobalValue::InternalLinkage,
   6035                                Init,
   6036                                ExtCatName);
   6037   GCATV->setAlignment(
   6038     CGM.getDataLayout().getABITypeAlignment(ObjCTypes.CategorynfABITy));
   6039   GCATV->setSection("__DATA, __objc_const");
   6040   CGM.AddUsedGlobal(GCATV);
   6041   DefinedCategories.push_back(GCATV);
   6042 
   6043   // Determine if this category is also "non-lazy".
   6044   if (ImplementationIsNonLazy(OCD))
   6045     DefinedNonLazyCategories.push_back(GCATV);
   6046   // method definition entries must be clear for next implementation.
   6047   MethodDefinitions.clear();
   6048 }
   6049 
   6050 /// GetMethodConstant - Return a struct objc_method constant for the
   6051 /// given method if it has been defined. The result is null if the
   6052 /// method has not been defined. The return value has type MethodPtrTy.
   6053 llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
   6054   const ObjCMethodDecl *MD) {
   6055   llvm::Function *Fn = GetMethodDefinition(MD);
   6056   if (!Fn)
   6057     return 0;
   6058 
   6059   llvm::Constant *Method[] = {
   6060     llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
   6061                                    ObjCTypes.SelectorPtrTy),
   6062     GetMethodVarType(MD),
   6063     llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy)
   6064   };
   6065   return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
   6066 }
   6067 
   6068 /// EmitMethodList - Build meta-data for method declarations
   6069 /// struct _method_list_t {
   6070 ///   uint32_t entsize;  // sizeof(struct _objc_method)
   6071 ///   uint32_t method_count;
   6072 ///   struct _objc_method method_list[method_count];
   6073 /// }
   6074 ///
   6075 llvm::Constant *
   6076 CGObjCNonFragileABIMac::EmitMethodList(Twine Name,
   6077                                        const char *Section,
   6078                                        ArrayRef<llvm::Constant*> Methods) {
   6079   // Return null for empty list.
   6080   if (Methods.empty())
   6081     return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
   6082 
   6083   llvm::Constant *Values[3];
   6084   // sizeof(struct _objc_method)
   6085   unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.MethodTy);
   6086   Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
   6087   // method_count
   6088   Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
   6089   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
   6090                                              Methods.size());
   6091   Values[2] = llvm::ConstantArray::get(AT, Methods);
   6092   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
   6093 
   6094   llvm::GlobalVariable *GV =
   6095     new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
   6096                              llvm::GlobalValue::InternalLinkage, Init, Name);
   6097   GV->setAlignment(CGM.getDataLayout().getABITypeAlignment(Init->getType()));
   6098   GV->setSection(Section);
   6099   CGM.AddUsedGlobal(GV);
   6100   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListnfABIPtrTy);
   6101 }
   6102 
   6103 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
   6104 /// the given ivar.
   6105 llvm::GlobalVariable *
   6106 CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
   6107                                                const ObjCIvarDecl *Ivar) {
   6108   const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();
   6109   std::string Name = "OBJC_IVAR_$_" + Container->getNameAsString() +
   6110     '.' + Ivar->getNameAsString();
   6111   llvm::GlobalVariable *IvarOffsetGV =
   6112     CGM.getModule().getGlobalVariable(Name);
   6113   if (!IvarOffsetGV)
   6114     IvarOffsetGV =
   6115       new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.LongTy,
   6116                                false,
   6117                                llvm::GlobalValue::ExternalLinkage,
   6118                                0,
   6119                                Name);
   6120   return IvarOffsetGV;
   6121 }
   6122 
   6123 llvm::Constant *
   6124 CGObjCNonFragileABIMac::EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
   6125                                           const ObjCIvarDecl *Ivar,
   6126                                           unsigned long int Offset) {
   6127   llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
   6128   IvarOffsetGV->setInitializer(llvm::ConstantInt::get(ObjCTypes.LongTy,
   6129                                                       Offset));
   6130   IvarOffsetGV->setAlignment(
   6131     CGM.getDataLayout().getABITypeAlignment(ObjCTypes.LongTy));
   6132 
   6133   // FIXME: This matches gcc, but shouldn't the visibility be set on the use as
   6134   // well (i.e., in ObjCIvarOffsetVariable).
   6135   if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
   6136       Ivar->getAccessControl() == ObjCIvarDecl::Package ||
   6137       ID->getVisibility() == HiddenVisibility)
   6138     IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
   6139   else
   6140     IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
   6141   IvarOffsetGV->setSection("__DATA, __objc_ivar");
   6142   return IvarOffsetGV;
   6143 }
   6144 
   6145 /// EmitIvarList - Emit the ivar list for the given
   6146 /// implementation. The return value has type
   6147 /// IvarListnfABIPtrTy.
   6148 ///  struct _ivar_t {
   6149 ///   unsigned long int *offset;  // pointer to ivar offset location
   6150 ///   char *name;
   6151 ///   char *type;
   6152 ///   uint32_t alignment;
   6153 ///   uint32_t size;
   6154 /// }
   6155 /// struct _ivar_list_t {
   6156 ///   uint32 entsize;  // sizeof(struct _ivar_t)
   6157 ///   uint32 count;
   6158 ///   struct _iver_t list[count];
   6159 /// }
   6160 ///
   6161 
   6162 llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
   6163   const ObjCImplementationDecl *ID) {
   6164 
   6165   std::vector<llvm::Constant*> Ivars;
   6166 
   6167   const ObjCInterfaceDecl *OID = ID->getClassInterface();
   6168   assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
   6169 
   6170   // FIXME. Consolidate this with similar code in GenerateClass.
   6171 
   6172   for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin();
   6173        IVD; IVD = IVD->getNextIvar()) {
   6174     // Ignore unnamed bit-fields.
   6175     if (!IVD->getDeclName())
   6176       continue;
   6177     llvm::Constant *Ivar[5];
   6178     Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
   6179                                 ComputeIvarBaseOffset(CGM, ID, IVD));
   6180     Ivar[1] = GetMethodVarName(IVD->getIdentifier());
   6181     Ivar[2] = GetMethodVarType(IVD);
   6182     llvm::Type *FieldTy =
   6183       CGM.getTypes().ConvertTypeForMem(IVD->getType());
   6184     unsigned Size = CGM.getDataLayout().getTypeAllocSize(FieldTy);
   6185     unsigned Align = CGM.getContext().getPreferredTypeAlign(
   6186       IVD->getType().getTypePtr()) >> 3;
   6187     Align = llvm::Log2_32(Align);
   6188     Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
   6189     // NOTE. Size of a bitfield does not match gcc's, because of the
   6190     // way bitfields are treated special in each. But I am told that
   6191     // 'size' for bitfield ivars is ignored by the runtime so it does
   6192     // not matter.  If it matters, there is enough info to get the
   6193     // bitfield right!
   6194     Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
   6195     Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
   6196   }
   6197   // Return null for empty list.
   6198   if (Ivars.empty())
   6199     return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
   6200 
   6201   llvm::Constant *Values[3];
   6202   unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.IvarnfABITy);
   6203   Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
   6204   Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
   6205   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
   6206                                              Ivars.size());
   6207   Values[2] = llvm::ConstantArray::get(AT, Ivars);
   6208   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
   6209   const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
   6210   llvm::GlobalVariable *GV =
   6211     new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
   6212                              llvm::GlobalValue::InternalLinkage,
   6213                              Init,
   6214                              Prefix + OID->getName());
   6215   GV->setAlignment(
   6216     CGM.getDataLayout().getABITypeAlignment(Init->getType()));
   6217   GV->setSection("__DATA, __objc_const");
   6218 
   6219   CGM.AddUsedGlobal(GV);
   6220   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListnfABIPtrTy);
   6221 }
   6222 
   6223 llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
   6224   const ObjCProtocolDecl *PD) {
   6225   llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
   6226 
   6227   if (!Entry) {
   6228     // We use the initializer as a marker of whether this is a forward
   6229     // reference or not. At module finalization we add the empty
   6230     // contents for protocols which were referenced but never defined.
   6231     Entry =
   6232       new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy, false,
   6233                                llvm::GlobalValue::ExternalLinkage,
   6234                                0,
   6235                                "\01l_OBJC_PROTOCOL_$_" + PD->getName());
   6236     Entry->setSection("__DATA,__datacoal_nt,coalesced");
   6237   }
   6238 
   6239   return Entry;
   6240 }
   6241 
   6242 /// GetOrEmitProtocol - Generate the protocol meta-data:
   6243 /// @code
   6244 /// struct _protocol_t {
   6245 ///   id isa;  // NULL
   6246 ///   const char * const protocol_name;
   6247 ///   const struct _protocol_list_t * protocol_list; // super protocols
   6248 ///   const struct method_list_t * const instance_methods;
   6249 ///   const struct method_list_t * const class_methods;
   6250 ///   const struct method_list_t *optionalInstanceMethods;
   6251 ///   const struct method_list_t *optionalClassMethods;
   6252 ///   const struct _prop_list_t * properties;
   6253 ///   const uint32_t size;  // sizeof(struct _protocol_t)
   6254 ///   const uint32_t flags;  // = 0
   6255 ///   const char ** extendedMethodTypes;
   6256 /// }
   6257 /// @endcode
   6258 ///
   6259 
   6260 llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
   6261   const ObjCProtocolDecl *PD) {
   6262   llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()];
   6263 
   6264   // Early exit if a defining object has already been generated.
   6265   if (Entry && Entry->hasInitializer())
   6266     return Entry;
   6267 
   6268   // Use the protocol definition, if there is one.
   6269   if (const ObjCProtocolDecl *Def = PD->getDefinition())
   6270     PD = Def;
   6271 
   6272   // Construct method lists.
   6273   std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
   6274   std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
   6275   std::vector<llvm::Constant*> MethodTypesExt, OptMethodTypesExt;
   6276   for (ObjCProtocolDecl::instmeth_iterator
   6277          i = PD->instmeth_begin(), e = PD->instmeth_end(); i != e; ++i) {
   6278     ObjCMethodDecl *MD = *i;
   6279     llvm::Constant *C = GetMethodDescriptionConstant(MD);
   6280     if (!C)
   6281       return GetOrEmitProtocolRef(PD);
   6282 
   6283     if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
   6284       OptInstanceMethods.push_back(C);
   6285       OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
   6286     } else {
   6287       InstanceMethods.push_back(C);
   6288       MethodTypesExt.push_back(GetMethodVarType(MD, true));
   6289     }
   6290   }
   6291 
   6292   for (ObjCProtocolDecl::classmeth_iterator
   6293          i = PD->classmeth_begin(), e = PD->classmeth_end(); i != e; ++i) {
   6294     ObjCMethodDecl *MD = *i;
   6295     llvm::Constant *C = GetMethodDescriptionConstant(MD);
   6296     if (!C)
   6297       return GetOrEmitProtocolRef(PD);
   6298 
   6299     if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
   6300       OptClassMethods.push_back(C);
   6301       OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
   6302     } else {
   6303       ClassMethods.push_back(C);
   6304       MethodTypesExt.push_back(GetMethodVarType(MD, true));
   6305     }
   6306   }
   6307 
   6308   MethodTypesExt.insert(MethodTypesExt.end(),
   6309                         OptMethodTypesExt.begin(), OptMethodTypesExt.end());
   6310 
   6311   llvm::Constant *Values[11];
   6312   // isa is NULL
   6313   Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
   6314   Values[1] = GetClassName(PD->getIdentifier());
   6315   Values[2] = EmitProtocolList("\01l_OBJC_$_PROTOCOL_REFS_" + PD->getName(),
   6316                                PD->protocol_begin(),
   6317                                PD->protocol_end());
   6318 
   6319   Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
   6320                              + PD->getName(),
   6321                              "__DATA, __objc_const",
   6322                              InstanceMethods);
   6323   Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
   6324                              + PD->getName(),
   6325                              "__DATA, __objc_const",
   6326                              ClassMethods);
   6327   Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
   6328                              + PD->getName(),
   6329                              "__DATA, __objc_const",
   6330                              OptInstanceMethods);
   6331   Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
   6332                              + PD->getName(),
   6333                              "__DATA, __objc_const",
   6334                              OptClassMethods);
   6335   Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getName(),
   6336                                0, PD, ObjCTypes);
   6337   uint32_t Size =
   6338     CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolnfABITy);
   6339   Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
   6340   Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
   6341   Values[10] = EmitProtocolMethodTypes("\01l_OBJC_$_PROTOCOL_METHOD_TYPES_"
   6342                                        + PD->getName(),
   6343                                        MethodTypesExt, ObjCTypes);
   6344   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
   6345                                                    Values);
   6346 
   6347   if (Entry) {
   6348     // Already created, fix the linkage and update the initializer.
   6349     Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
   6350     Entry->setInitializer(Init);
   6351   } else {
   6352     Entry =
   6353       new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy,
   6354                                false, llvm::GlobalValue::WeakAnyLinkage, Init,
   6355                                "\01l_OBJC_PROTOCOL_$_" + PD->getName());
   6356     Entry->setAlignment(
   6357       CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ProtocolnfABITy));
   6358     Entry->setSection("__DATA,__datacoal_nt,coalesced");
   6359 
   6360     Protocols[PD->getIdentifier()] = Entry;
   6361   }
   6362   Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
   6363   CGM.AddUsedGlobal(Entry);
   6364 
   6365   // Use this protocol meta-data to build protocol list table in section
   6366   // __DATA, __objc_protolist
   6367   llvm::GlobalVariable *PTGV =
   6368     new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABIPtrTy,
   6369                              false, llvm::GlobalValue::WeakAnyLinkage, Entry,
   6370                              "\01l_OBJC_LABEL_PROTOCOL_$_" + PD->getName());
   6371   PTGV->setAlignment(
   6372     CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
   6373   PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
   6374   PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
   6375   CGM.AddUsedGlobal(PTGV);
   6376   return Entry;
   6377 }
   6378 
   6379 /// EmitProtocolList - Generate protocol list meta-data:
   6380 /// @code
   6381 /// struct _protocol_list_t {
   6382 ///   long protocol_count;   // Note, this is 32/64 bit
   6383 ///   struct _protocol_t[protocol_count];
   6384 /// }
   6385 /// @endcode
   6386 ///
   6387 llvm::Constant *
   6388 CGObjCNonFragileABIMac::EmitProtocolList(Twine Name,
   6389                                       ObjCProtocolDecl::protocol_iterator begin,
   6390                                       ObjCProtocolDecl::protocol_iterator end) {
   6391   SmallVector<llvm::Constant *, 16> ProtocolRefs;
   6392 
   6393   // Just return null for empty protocol lists
   6394   if (begin == end)
   6395     return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
   6396 
   6397   // FIXME: We shouldn't need to do this lookup here, should we?
   6398   SmallString<256> TmpName;
   6399   Name.toVector(TmpName);
   6400   llvm::GlobalVariable *GV =
   6401     CGM.getModule().getGlobalVariable(TmpName.str(), true);
   6402   if (GV)
   6403     return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListnfABIPtrTy);
   6404 
   6405   for (; begin != end; ++begin)
   6406     ProtocolRefs.push_back(GetProtocolRef(*begin));  // Implemented???
   6407 
   6408   // This list is null terminated.
   6409   ProtocolRefs.push_back(llvm::Constant::getNullValue(
   6410                            ObjCTypes.ProtocolnfABIPtrTy));
   6411 
   6412   llvm::Constant *Values[2];
   6413   Values[0] =
   6414     llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
   6415   Values[1] =
   6416     llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
   6417                                                   ProtocolRefs.size()),
   6418                              ProtocolRefs);
   6419 
   6420   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
   6421   GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
   6422                                 llvm::GlobalValue::InternalLinkage,
   6423                                 Init, Name);
   6424   GV->setSection("__DATA, __objc_const");
   6425   GV->setAlignment(
   6426     CGM.getDataLayout().getABITypeAlignment(Init->getType()));
   6427   CGM.AddUsedGlobal(GV);
   6428   return llvm::ConstantExpr::getBitCast(GV,
   6429                                         ObjCTypes.ProtocolListnfABIPtrTy);
   6430 }
   6431 
   6432 /// GetMethodDescriptionConstant - This routine build following meta-data:
   6433 /// struct _objc_method {
   6434 ///   SEL _cmd;
   6435 ///   char *method_type;
   6436 ///   char *_imp;
   6437 /// }
   6438 
   6439 llvm::Constant *
   6440 CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
   6441   llvm::Constant *Desc[3];
   6442   Desc[0] =
   6443     llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
   6444                                    ObjCTypes.SelectorPtrTy);
   6445   Desc[1] = GetMethodVarType(MD);
   6446   if (!Desc[1])
   6447     return 0;
   6448 
   6449   // Protocol methods have no implementation. So, this entry is always NULL.
   6450   Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
   6451   return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
   6452 }
   6453 
   6454 /// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
   6455 /// This code gen. amounts to generating code for:
   6456 /// @code
   6457 /// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
   6458 /// @encode
   6459 ///
   6460 LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
   6461                                                CodeGen::CodeGenFunction &CGF,
   6462                                                QualType ObjectTy,
   6463                                                llvm::Value *BaseValue,
   6464                                                const ObjCIvarDecl *Ivar,
   6465                                                unsigned CVRQualifiers) {
   6466   ObjCInterfaceDecl *ID = ObjectTy->getAs<ObjCObjectType>()->getInterface();
   6467   llvm::Value *Offset = EmitIvarOffset(CGF, ID, Ivar);
   6468 
   6469   if (IsIvarOffsetKnownIdempotent(CGF, ID, Ivar))
   6470     if (llvm::LoadInst *LI = cast<llvm::LoadInst>(Offset))
   6471       LI->setMetadata(CGM.getModule().getMDKindID("invariant.load"),
   6472                       llvm::MDNode::get(VMContext, ArrayRef<llvm::Value*>()));
   6473 
   6474   return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
   6475                                   Offset);
   6476 }
   6477 
   6478 llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
   6479   CodeGen::CodeGenFunction &CGF,
   6480   const ObjCInterfaceDecl *Interface,
   6481   const ObjCIvarDecl *Ivar) {
   6482   return CGF.Builder.CreateLoad(ObjCIvarOffsetVariable(Interface, Ivar),"ivar");
   6483 }
   6484 
   6485 static void appendSelectorForMessageRefTable(std::string &buffer,
   6486                                              Selector selector) {
   6487   if (selector.isUnarySelector()) {
   6488     buffer += selector.getNameForSlot(0);
   6489     return;
   6490   }
   6491 
   6492   for (unsigned i = 0, e = selector.getNumArgs(); i != e; ++i) {
   6493     buffer += selector.getNameForSlot(i);
   6494     buffer += '_';
   6495   }
   6496 }
   6497 
   6498 /// Emit a "v-table" message send.  We emit a weak hidden-visibility
   6499 /// struct, initially containing the selector pointer and a pointer to
   6500 /// a "fixup" variant of the appropriate objc_msgSend.  To call, we
   6501 /// load and call the function pointer, passing the address of the
   6502 /// struct as the second parameter.  The runtime determines whether
   6503 /// the selector is currently emitted using vtable dispatch; if so, it
   6504 /// substitutes a stub function which simply tail-calls through the
   6505 /// appropriate vtable slot, and if not, it substitues a stub function
   6506 /// which tail-calls objc_msgSend.  Both stubs adjust the selector
   6507 /// argument to correctly point to the selector.
   6508 RValue
   6509 CGObjCNonFragileABIMac::EmitVTableMessageSend(CodeGenFunction &CGF,
   6510                                               ReturnValueSlot returnSlot,
   6511                                               QualType resultType,
   6512                                               Selector selector,
   6513                                               llvm::Value *arg0,
   6514                                               QualType arg0Type,
   6515                                               bool isSuper,
   6516                                               const CallArgList &formalArgs,
   6517                                               const ObjCMethodDecl *method) {
   6518   // Compute the actual arguments.
   6519   CallArgList args;
   6520 
   6521   // First argument: the receiver / super-call structure.
   6522   if (!isSuper)
   6523     arg0 = CGF.Builder.CreateBitCast(arg0, ObjCTypes.ObjectPtrTy);
   6524   args.add(RValue::get(arg0), arg0Type);
   6525 
   6526   // Second argument: a pointer to the message ref structure.  Leave
   6527   // the actual argument value blank for now.
   6528   args.add(RValue::get(0), ObjCTypes.MessageRefCPtrTy);
   6529 
   6530   args.insert(args.end(), formalArgs.begin(), formalArgs.end());
   6531 
   6532   MessageSendInfo MSI = getMessageSendInfo(method, resultType, args);
   6533 
   6534   NullReturnState nullReturn;
   6535 
   6536   // Find the function to call and the mangled name for the message
   6537   // ref structure.  Using a different mangled name wouldn't actually
   6538   // be a problem; it would just be a waste.
   6539   //
   6540   // The runtime currently never uses vtable dispatch for anything
   6541   // except normal, non-super message-sends.
   6542   // FIXME: don't use this for that.
   6543   llvm::Constant *fn = 0;
   6544   std::string messageRefName("\01l_");
   6545   if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
   6546     if (isSuper) {
   6547       fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
   6548       messageRefName += "objc_msgSendSuper2_stret_fixup";
   6549     } else {
   6550       nullReturn.init(CGF, arg0);
   6551       fn = ObjCTypes.getMessageSendStretFixupFn();
   6552       messageRefName += "objc_msgSend_stret_fixup";
   6553     }
   6554   } else if (!isSuper && CGM.ReturnTypeUsesFPRet(resultType)) {
   6555     fn = ObjCTypes.getMessageSendFpretFixupFn();
   6556     messageRefName += "objc_msgSend_fpret_fixup";
   6557   } else {
   6558     if (isSuper) {
   6559       fn = ObjCTypes.getMessageSendSuper2FixupFn();
   6560       messageRefName += "objc_msgSendSuper2_fixup";
   6561     } else {
   6562       fn = ObjCTypes.getMessageSendFixupFn();
   6563       messageRefName += "objc_msgSend_fixup";
   6564     }
   6565   }
   6566   assert(fn && "CGObjCNonFragileABIMac::EmitMessageSend");
   6567   messageRefName += '_';
   6568 
   6569   // Append the selector name, except use underscores anywhere we
   6570   // would have used colons.
   6571   appendSelectorForMessageRefTable(messageRefName, selector);
   6572 
   6573   llvm::GlobalVariable *messageRef
   6574     = CGM.getModule().getGlobalVariable(messageRefName);
   6575   if (!messageRef) {
   6576     // Build the message ref structure.
   6577     llvm::Constant *values[] = { fn, GetMethodVarName(selector) };
   6578     llvm::Constant *init = llvm::ConstantStruct::getAnon(values);
   6579     messageRef = new llvm::GlobalVariable(CGM.getModule(),
   6580                                           init->getType(),
   6581                                           /*constant*/ false,
   6582                                           llvm::GlobalValue::WeakAnyLinkage,
   6583                                           init,
   6584                                           messageRefName);
   6585     messageRef->setVisibility(llvm::GlobalValue::HiddenVisibility);
   6586     messageRef->setAlignment(16);
   6587     messageRef->setSection("__DATA, __objc_msgrefs, coalesced");
   6588   }
   6589 
   6590   bool requiresnullCheck = false;
   6591   if (CGM.getLangOpts().ObjCAutoRefCount && method)
   6592     for (ObjCMethodDecl::param_const_iterator i = method->param_begin(),
   6593          e = method->param_end(); i != e; ++i) {
   6594       const ParmVarDecl *ParamDecl = (*i);
   6595       if (ParamDecl->hasAttr<NSConsumedAttr>()) {
   6596         if (!nullReturn.NullBB)
   6597           nullReturn.init(CGF, arg0);
   6598         requiresnullCheck = true;
   6599         break;
   6600       }
   6601     }
   6602 
   6603   llvm::Value *mref =
   6604     CGF.Builder.CreateBitCast(messageRef, ObjCTypes.MessageRefPtrTy);
   6605 
   6606   // Update the message ref argument.
   6607   args[1].RV = RValue::get(mref);
   6608 
   6609   // Load the function to call from the message ref table.
   6610   llvm::Value *callee = CGF.Builder.CreateStructGEP(mref, 0);
   6611   callee = CGF.Builder.CreateLoad(callee, "msgSend_fn");
   6612 
   6613   callee = CGF.Builder.CreateBitCast(callee, MSI.MessengerType);
   6614 
   6615   RValue result = CGF.EmitCall(MSI.CallInfo, callee, returnSlot, args);
   6616   return nullReturn.complete(CGF, result, resultType, formalArgs,
   6617                              requiresnullCheck ? method : 0);
   6618 }
   6619 
   6620 /// Generate code for a message send expression in the nonfragile abi.
   6621 CodeGen::RValue
   6622 CGObjCNonFragileABIMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
   6623                                             ReturnValueSlot Return,
   6624                                             QualType ResultType,
   6625                                             Selector Sel,
   6626                                             llvm::Value *Receiver,
   6627                                             const CallArgList &CallArgs,
   6628                                             const ObjCInterfaceDecl *Class,
   6629                                             const ObjCMethodDecl *Method) {
   6630   return isVTableDispatchedSelector(Sel)
   6631     ? EmitVTableMessageSend(CGF, Return, ResultType, Sel,
   6632                             Receiver, CGF.getContext().getObjCIdType(),
   6633                             false, CallArgs, Method)
   6634     : EmitMessageSend(CGF, Return, ResultType,
   6635                       EmitSelector(CGF, Sel),
   6636                       Receiver, CGF.getContext().getObjCIdType(),
   6637                       false, CallArgs, Method, ObjCTypes);
   6638 }
   6639 
   6640 llvm::GlobalVariable *
   6641 CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name) {
   6642   llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
   6643 
   6644   if (!GV) {
   6645     GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABITy,
   6646                                   false, llvm::GlobalValue::ExternalLinkage,
   6647                                   0, Name);
   6648   }
   6649 
   6650   return GV;
   6651 }
   6652 
   6653 llvm::Value *CGObjCNonFragileABIMac::EmitClassRefFromId(CodeGenFunction &CGF,
   6654                                                         IdentifierInfo *II) {
   6655   llvm::GlobalVariable *&Entry = ClassReferences[II];
   6656 
   6657   if (!Entry) {
   6658     std::string ClassName(getClassSymbolPrefix() + II->getName().str());
   6659     llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
   6660     Entry =
   6661     new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
   6662                              false, llvm::GlobalValue::InternalLinkage,
   6663                              ClassGV,
   6664                              "\01L_OBJC_CLASSLIST_REFERENCES_$_");
   6665     Entry->setAlignment(
   6666                         CGM.getDataLayout().getABITypeAlignment(
   6667                                                                 ObjCTypes.ClassnfABIPtrTy));
   6668     Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
   6669     CGM.AddUsedGlobal(Entry);
   6670   }
   6671 
   6672   return CGF.Builder.CreateLoad(Entry);
   6673 }
   6674 
   6675 llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CodeGenFunction &CGF,
   6676                                                   const ObjCInterfaceDecl *ID) {
   6677   return EmitClassRefFromId(CGF, ID->getIdentifier());
   6678 }
   6679 
   6680 llvm::Value *CGObjCNonFragileABIMac::EmitNSAutoreleasePoolClassRef(
   6681                                                     CodeGenFunction &CGF) {
   6682   IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
   6683   return EmitClassRefFromId(CGF, II);
   6684 }
   6685 
   6686 llvm::Value *
   6687 CGObjCNonFragileABIMac::EmitSuperClassRef(CodeGenFunction &CGF,
   6688                                           const ObjCInterfaceDecl *ID) {
   6689   llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
   6690 
   6691   if (!Entry) {
   6692     std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
   6693     llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
   6694     Entry =
   6695       new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
   6696                                false, llvm::GlobalValue::InternalLinkage,
   6697                                ClassGV,
   6698                                "\01L_OBJC_CLASSLIST_SUP_REFS_$_");
   6699     Entry->setAlignment(
   6700       CGM.getDataLayout().getABITypeAlignment(
   6701         ObjCTypes.ClassnfABIPtrTy));
   6702     Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
   6703     CGM.AddUsedGlobal(Entry);
   6704   }
   6705 
   6706   return CGF.Builder.CreateLoad(Entry);
   6707 }
   6708 
   6709 /// EmitMetaClassRef - Return a Value * of the address of _class_t
   6710 /// meta-data
   6711 ///
   6712 llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CodeGenFunction &CGF,
   6713                                                       const ObjCInterfaceDecl *ID) {
   6714   llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
   6715   if (Entry)
   6716     return CGF.Builder.CreateLoad(Entry);
   6717 
   6718   std::string MetaClassName(getMetaclassSymbolPrefix() + ID->getNameAsString());
   6719   llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
   6720   Entry =
   6721     new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy, false,
   6722                              llvm::GlobalValue::InternalLinkage,
   6723                              MetaClassGV,
   6724                              "\01L_OBJC_CLASSLIST_SUP_REFS_$_");
   6725   Entry->setAlignment(
   6726     CGM.getDataLayout().getABITypeAlignment(
   6727       ObjCTypes.ClassnfABIPtrTy));
   6728 
   6729   Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
   6730   CGM.AddUsedGlobal(Entry);
   6731 
   6732   return CGF.Builder.CreateLoad(Entry);
   6733 }
   6734 
   6735 /// GetClass - Return a reference to the class for the given interface
   6736 /// decl.
   6737 llvm::Value *CGObjCNonFragileABIMac::GetClass(CodeGenFunction &CGF,
   6738                                               const ObjCInterfaceDecl *ID) {
   6739   if (ID->isWeakImported()) {
   6740     std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
   6741     llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName);
   6742     ClassGV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
   6743   }
   6744 
   6745   return EmitClassRef(CGF, ID);
   6746 }
   6747 
   6748 /// Generates a message send where the super is the receiver.  This is
   6749 /// a message send to self with special delivery semantics indicating
   6750 /// which class's method should be called.
   6751 CodeGen::RValue
   6752 CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
   6753                                                  ReturnValueSlot Return,
   6754                                                  QualType ResultType,
   6755                                                  Selector Sel,
   6756                                                  const ObjCInterfaceDecl *Class,
   6757                                                  bool isCategoryImpl,
   6758                                                  llvm::Value *Receiver,
   6759                                                  bool IsClassMessage,
   6760                                                  const CodeGen::CallArgList &CallArgs,
   6761                                                  const ObjCMethodDecl *Method) {
   6762   // ...
   6763   // Create and init a super structure; this is a (receiver, class)
   6764   // pair we will pass to objc_msgSendSuper.
   6765   llvm::Value *ObjCSuper =
   6766     CGF.CreateTempAlloca(ObjCTypes.SuperTy, "objc_super");
   6767 
   6768   llvm::Value *ReceiverAsObject =
   6769     CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
   6770   CGF.Builder.CreateStore(ReceiverAsObject,
   6771                           CGF.Builder.CreateStructGEP(ObjCSuper, 0));
   6772 
   6773   // If this is a class message the metaclass is passed as the target.
   6774   llvm::Value *Target;
   6775   if (IsClassMessage)
   6776       Target = EmitMetaClassRef(CGF, Class);
   6777   else
   6778     Target = EmitSuperClassRef(CGF, Class);
   6779 
   6780   // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
   6781   // ObjCTypes types.
   6782   llvm::Type *ClassTy =
   6783     CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
   6784   Target = CGF.Builder.CreateBitCast(Target, ClassTy);
   6785   CGF.Builder.CreateStore(Target,
   6786                           CGF.Builder.CreateStructGEP(ObjCSuper, 1));
   6787 
   6788   return (isVTableDispatchedSelector(Sel))
   6789     ? EmitVTableMessageSend(CGF, Return, ResultType, Sel,
   6790                             ObjCSuper, ObjCTypes.SuperPtrCTy,
   6791                             true, CallArgs, Method)
   6792     : EmitMessageSend(CGF, Return, ResultType,
   6793                       EmitSelector(CGF, Sel),
   6794                       ObjCSuper, ObjCTypes.SuperPtrCTy,
   6795                       true, CallArgs, Method, ObjCTypes);
   6796 }
   6797 
   6798 llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CodeGenFunction &CGF,
   6799                                                   Selector Sel, bool lval) {
   6800   llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
   6801 
   6802   if (!Entry) {
   6803     llvm::Constant *Casted =
   6804       llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
   6805                                      ObjCTypes.SelectorPtrTy);
   6806     Entry =
   6807       new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.SelectorPtrTy, false,
   6808                                llvm::GlobalValue::InternalLinkage,
   6809                                Casted, "\01L_OBJC_SELECTOR_REFERENCES_");
   6810     Entry->setExternallyInitialized(true);
   6811     Entry->setSection("__DATA, __objc_selrefs, literal_pointers, no_dead_strip");
   6812     CGM.AddUsedGlobal(Entry);
   6813   }
   6814 
   6815   if (lval)
   6816     return Entry;
   6817   llvm::LoadInst* LI = CGF.Builder.CreateLoad(Entry);
   6818 
   6819   LI->setMetadata(CGM.getModule().getMDKindID("invariant.load"),
   6820                   llvm::MDNode::get(VMContext,
   6821                                     ArrayRef<llvm::Value*>()));
   6822   return LI;
   6823 }
   6824 /// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
   6825 /// objc_assign_ivar (id src, id *dst, ptrdiff_t)
   6826 ///
   6827 void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
   6828                                                 llvm::Value *src,
   6829                                                 llvm::Value *dst,
   6830                                                 llvm::Value *ivarOffset) {
   6831   llvm::Type * SrcTy = src->getType();
   6832   if (!isa<llvm::PointerType>(SrcTy)) {
   6833     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
   6834     assert(Size <= 8 && "does not support size > 8");
   6835     src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
   6836            : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
   6837     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
   6838   }
   6839   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
   6840   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
   6841   llvm::Value *args[] = { src, dst, ivarOffset };
   6842   CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args);
   6843 }
   6844 
   6845 /// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
   6846 /// objc_assign_strongCast (id src, id *dst)
   6847 ///
   6848 void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
   6849   CodeGen::CodeGenFunction &CGF,
   6850   llvm::Value *src, llvm::Value *dst) {
   6851   llvm::Type * SrcTy = src->getType();
   6852   if (!isa<llvm::PointerType>(SrcTy)) {
   6853     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
   6854     assert(Size <= 8 && "does not support size > 8");
   6855     src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
   6856            : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
   6857     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
   6858   }
   6859   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
   6860   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
   6861   llvm::Value *args[] = { src, dst };
   6862   CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(),
   6863                               args, "weakassign");
   6864 }
   6865 
   6866 void CGObjCNonFragileABIMac::EmitGCMemmoveCollectable(
   6867   CodeGen::CodeGenFunction &CGF,
   6868   llvm::Value *DestPtr,
   6869   llvm::Value *SrcPtr,
   6870   llvm::Value *Size) {
   6871   SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
   6872   DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
   6873   llvm::Value *args[] = { DestPtr, SrcPtr, Size };
   6874   CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args);
   6875 }
   6876 
   6877 /// EmitObjCWeakRead - Code gen for loading value of a __weak
   6878 /// object: objc_read_weak (id *src)
   6879 ///
   6880 llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
   6881   CodeGen::CodeGenFunction &CGF,
   6882   llvm::Value *AddrWeakObj) {
   6883   llvm::Type* DestTy =
   6884     cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
   6885   AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
   6886   llvm::Value *read_weak =
   6887     CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(),
   6888                                 AddrWeakObj, "weakread");
   6889   read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
   6890   return read_weak;
   6891 }
   6892 
   6893 /// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
   6894 /// objc_assign_weak (id src, id *dst)
   6895 ///
   6896 void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
   6897                                                 llvm::Value *src, llvm::Value *dst) {
   6898   llvm::Type * SrcTy = src->getType();
   6899   if (!isa<llvm::PointerType>(SrcTy)) {
   6900     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
   6901     assert(Size <= 8 && "does not support size > 8");
   6902     src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
   6903            : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
   6904     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
   6905   }
   6906   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
   6907   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
   6908   llvm::Value *args[] = { src, dst };
   6909   CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(),
   6910                               args, "weakassign");
   6911 }
   6912 
   6913 /// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
   6914 /// objc_assign_global (id src, id *dst)
   6915 ///
   6916 void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
   6917                                           llvm::Value *src, llvm::Value *dst,
   6918                                           bool threadlocal) {
   6919   llvm::Type * SrcTy = src->getType();
   6920   if (!isa<llvm::PointerType>(SrcTy)) {
   6921     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
   6922     assert(Size <= 8 && "does not support size > 8");
   6923     src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
   6924            : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
   6925     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
   6926   }
   6927   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
   6928   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
   6929   llvm::Value *args[] = { src, dst };
   6930   if (!threadlocal)
   6931     CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(),
   6932                                 args, "globalassign");
   6933   else
   6934     CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(),
   6935                                 args, "threadlocalassign");
   6936 }
   6937 
   6938 void
   6939 CGObjCNonFragileABIMac::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
   6940                                              const ObjCAtSynchronizedStmt &S) {
   6941   EmitAtSynchronizedStmt(CGF, S,
   6942       cast<llvm::Function>(ObjCTypes.getSyncEnterFn()),
   6943       cast<llvm::Function>(ObjCTypes.getSyncExitFn()));
   6944 }
   6945 
   6946 llvm::Constant *
   6947 CGObjCNonFragileABIMac::GetEHType(QualType T) {
   6948   // There's a particular fixed type info for 'id'.
   6949   if (T->isObjCIdType() ||
   6950       T->isObjCQualifiedIdType()) {
   6951     llvm::Constant *IDEHType =
   6952       CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
   6953     if (!IDEHType)
   6954       IDEHType =
   6955         new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy,
   6956                                  false,
   6957                                  llvm::GlobalValue::ExternalLinkage,
   6958                                  0, "OBJC_EHTYPE_id");
   6959     return IDEHType;
   6960   }
   6961 
   6962   // All other types should be Objective-C interface pointer types.
   6963   const ObjCObjectPointerType *PT =
   6964     T->getAs<ObjCObjectPointerType>();
   6965   assert(PT && "Invalid @catch type.");
   6966   const ObjCInterfaceType *IT = PT->getInterfaceType();
   6967   assert(IT && "Invalid @catch type.");
   6968   return GetInterfaceEHType(IT->getDecl(), false);
   6969 }
   6970 
   6971 void CGObjCNonFragileABIMac::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
   6972                                          const ObjCAtTryStmt &S) {
   6973   EmitTryCatchStmt(CGF, S,
   6974       cast<llvm::Function>(ObjCTypes.getObjCBeginCatchFn()),
   6975       cast<llvm::Function>(ObjCTypes.getObjCEndCatchFn()),
   6976       cast<llvm::Function>(ObjCTypes.getExceptionRethrowFn()));
   6977 }
   6978 
   6979 /// EmitThrowStmt - Generate code for a throw statement.
   6980 void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
   6981                                            const ObjCAtThrowStmt &S,
   6982                                            bool ClearInsertionPoint) {
   6983   if (const Expr *ThrowExpr = S.getThrowExpr()) {
   6984     llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
   6985     Exception = CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
   6986     CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionThrowFn(), Exception)
   6987       .setDoesNotReturn();
   6988   } else {
   6989     CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionRethrowFn())
   6990       .setDoesNotReturn();
   6991   }
   6992 
   6993   CGF.Builder.CreateUnreachable();
   6994   if (ClearInsertionPoint)
   6995     CGF.Builder.ClearInsertionPoint();
   6996 }
   6997 
   6998 llvm::Constant *
   6999 CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
   7000                                            bool ForDefinition) {
   7001   llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
   7002 
   7003   // If we don't need a definition, return the entry if found or check
   7004   // if we use an external reference.
   7005   if (!ForDefinition) {
   7006     if (Entry)
   7007       return Entry;
   7008 
   7009     // If this type (or a super class) has the __objc_exception__
   7010     // attribute, emit an external reference.
   7011     if (hasObjCExceptionAttribute(CGM.getContext(), ID))
   7012       return Entry =
   7013         new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false,
   7014                                  llvm::GlobalValue::ExternalLinkage,
   7015                                  0,
   7016                                  ("OBJC_EHTYPE_$_" +
   7017                                   ID->getIdentifier()->getName()));
   7018   }
   7019 
   7020   // Otherwise we need to either make a new entry or fill in the
   7021   // initializer.
   7022   assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
   7023   std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
   7024   std::string VTableName = "objc_ehtype_vtable";
   7025   llvm::GlobalVariable *VTableGV =
   7026     CGM.getModule().getGlobalVariable(VTableName);
   7027   if (!VTableGV)
   7028     VTableGV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.Int8PtrTy,
   7029                                         false,
   7030                                         llvm::GlobalValue::ExternalLinkage,
   7031                                         0, VTableName);
   7032 
   7033   llvm::Value *VTableIdx = llvm::ConstantInt::get(CGM.Int32Ty, 2);
   7034 
   7035   llvm::Constant *Values[] = {
   7036     llvm::ConstantExpr::getGetElementPtr(VTableGV, VTableIdx),
   7037     GetClassName(ID->getIdentifier()),
   7038     GetClassGlobal(ClassName)
   7039   };
   7040   llvm::Constant *Init =
   7041     llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
   7042 
   7043   if (Entry) {
   7044     Entry->setInitializer(Init);
   7045   } else {
   7046     Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false,
   7047                                      llvm::GlobalValue::WeakAnyLinkage,
   7048                                      Init,
   7049                                      ("OBJC_EHTYPE_$_" +
   7050                                       ID->getIdentifier()->getName()));
   7051   }
   7052 
   7053   if (ID->getVisibility() == HiddenVisibility)
   7054     Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
   7055   Entry->setAlignment(CGM.getDataLayout().getABITypeAlignment(
   7056       ObjCTypes.EHTypeTy));
   7057 
   7058   if (ForDefinition) {
   7059     Entry->setSection("__DATA,__objc_const");
   7060     Entry->setLinkage(llvm::GlobalValue::ExternalLinkage);
   7061   } else {
   7062     Entry->setSection("__DATA,__datacoal_nt,coalesced");
   7063   }
   7064 
   7065   return Entry;
   7066 }
   7067 
   7068 /* *** */
   7069 
   7070 CodeGen::CGObjCRuntime *
   7071 CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
   7072   switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
   7073   case ObjCRuntime::FragileMacOSX:
   7074   return new CGObjCMac(CGM);
   7075 
   7076   case ObjCRuntime::MacOSX:
   7077   case ObjCRuntime::iOS:
   7078     return new CGObjCNonFragileABIMac(CGM);
   7079 
   7080   case ObjCRuntime::GNUstep:
   7081   case ObjCRuntime::GCC:
   7082   case ObjCRuntime::ObjFW:
   7083     llvm_unreachable("these runtimes are not Mac runtimes");
   7084   }
   7085   llvm_unreachable("bad runtime");
   7086 }
   7087