clang API Documentation

CGObjCMac.cpp
Go to the documentation of this file.
00001 //===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This provides Objective-C code generation targeting the Apple runtime.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "CGObjCRuntime.h"
00015 #include "CGBlocks.h"
00016 #include "CGCleanup.h"
00017 #include "CGRecordLayout.h"
00018 #include "CodeGenFunction.h"
00019 #include "CodeGenModule.h"
00020 #include "clang/AST/ASTContext.h"
00021 #include "clang/AST/Decl.h"
00022 #include "clang/AST/DeclObjC.h"
00023 #include "clang/AST/RecordLayout.h"
00024 #include "clang/AST/StmtObjC.h"
00025 #include "clang/Basic/LangOptions.h"
00026 #include "clang/CodeGen/CGFunctionInfo.h"
00027 #include "clang/Frontend/CodeGenOptions.h"
00028 #include "llvm/ADT/DenseSet.h"
00029 #include "llvm/ADT/SetVector.h"
00030 #include "llvm/ADT/SmallPtrSet.h"
00031 #include "llvm/ADT/SmallString.h"
00032 #include "llvm/IR/CallSite.h"
00033 #include "llvm/IR/DataLayout.h"
00034 #include "llvm/IR/InlineAsm.h"
00035 #include "llvm/IR/IntrinsicInst.h"
00036 #include "llvm/IR/LLVMContext.h"
00037 #include "llvm/IR/Module.h"
00038 #include "llvm/Support/raw_ostream.h"
00039 #include <cstdio>
00040 
00041 using namespace clang;
00042 using namespace CodeGen;
00043 
00044 namespace {
00045 
00046 // FIXME: We should find a nicer way to make the labels for metadata, string
00047 // concatenation is lame.
00048 
00049 class ObjCCommonTypesHelper {
00050 protected:
00051   llvm::LLVMContext &VMContext;
00052 
00053 private:
00054   // The types of these functions don't really matter because we
00055   // should always bitcast before calling them.
00056 
00057   /// id objc_msgSend (id, SEL, ...)
00058   /// 
00059   /// The default messenger, used for sends whose ABI is unchanged from
00060   /// the all-integer/pointer case.
00061   llvm::Constant *getMessageSendFn() const {
00062     // Add the non-lazy-bind attribute, since objc_msgSend is likely to
00063     // be called a lot.
00064     llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
00065     return
00066       CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
00067                                                         params, true),
00068                                 "objc_msgSend",
00069                                 llvm::AttributeSet::get(CGM.getLLVMContext(),
00070                                               llvm::AttributeSet::FunctionIndex,
00071                                                  llvm::Attribute::NonLazyBind));
00072   }
00073 
00074   /// void objc_msgSend_stret (id, SEL, ...)
00075   ///
00076   /// The messenger used when the return value is an aggregate returned
00077   /// by indirect reference in the first argument, and therefore the
00078   /// self and selector parameters are shifted over by one.
00079   llvm::Constant *getMessageSendStretFn() const {
00080     llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
00081     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy,
00082                                                              params, true),
00083                                      "objc_msgSend_stret");
00084 
00085   }
00086 
00087   /// [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
00088   ///
00089   /// The messenger used when the return value is returned on the x87
00090   /// floating-point stack; without a special entrypoint, the nil case
00091   /// would be unbalanced.
00092   llvm::Constant *getMessageSendFpretFn() const {
00093     llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
00094     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.DoubleTy,
00095                                                              params, true),
00096                                      "objc_msgSend_fpret");
00097 
00098   }
00099 
00100   /// _Complex long double objc_msgSend_fp2ret(id self, SEL op, ...)
00101   ///
00102   /// The messenger used when the return value is returned in two values on the
00103   /// x87 floating point stack; without a special entrypoint, the nil case
00104   /// would be unbalanced. Only used on 64-bit X86.
00105   llvm::Constant *getMessageSendFp2retFn() const {
00106     llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
00107     llvm::Type *longDoubleType = llvm::Type::getX86_FP80Ty(VMContext);
00108     llvm::Type *resultType = 
00109       llvm::StructType::get(longDoubleType, longDoubleType, NULL);
00110 
00111     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(resultType,
00112                                                              params, true),
00113                                      "objc_msgSend_fp2ret");
00114   }
00115 
00116   /// id objc_msgSendSuper(struct objc_super *super, SEL op, ...)
00117   ///
00118   /// The messenger used for super calls, which have different dispatch
00119   /// semantics.  The class passed is the superclass of the current
00120   /// class.
00121   llvm::Constant *getMessageSendSuperFn() const {
00122     llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy };
00123     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
00124                                                              params, true),
00125                                      "objc_msgSendSuper");
00126   }
00127 
00128   /// id objc_msgSendSuper2(struct objc_super *super, SEL op, ...)
00129   ///
00130   /// A slightly different messenger used for super calls.  The class
00131   /// passed is the current class.
00132   llvm::Constant *getMessageSendSuperFn2() const {
00133     llvm::Type *params[] = { SuperPtrTy, SelectorPtrTy };
00134     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
00135                                                              params, true),
00136                                      "objc_msgSendSuper2");
00137   }
00138 
00139   /// void objc_msgSendSuper_stret(void *stretAddr, struct objc_super *super,
00140   ///                              SEL op, ...)
00141   ///
00142   /// The messenger used for super calls which return an aggregate indirectly.
00143   llvm::Constant *getMessageSendSuperStretFn() const {
00144     llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy };
00145     return CGM.CreateRuntimeFunction(
00146       llvm::FunctionType::get(CGM.VoidTy, params, true),
00147       "objc_msgSendSuper_stret");
00148   }
00149 
00150   /// void objc_msgSendSuper2_stret(void * stretAddr, struct objc_super *super,
00151   ///                               SEL op, ...)
00152   ///
00153   /// objc_msgSendSuper_stret with the super2 semantics.
00154   llvm::Constant *getMessageSendSuperStretFn2() const {
00155     llvm::Type *params[] = { Int8PtrTy, SuperPtrTy, SelectorPtrTy };
00156     return CGM.CreateRuntimeFunction(
00157       llvm::FunctionType::get(CGM.VoidTy, params, true),
00158       "objc_msgSendSuper2_stret");
00159   }
00160 
00161   llvm::Constant *getMessageSendSuperFpretFn() const {
00162     // There is no objc_msgSendSuper_fpret? How can that work?
00163     return getMessageSendSuperFn();
00164   }
00165 
00166   llvm::Constant *getMessageSendSuperFpretFn2() const {
00167     // There is no objc_msgSendSuper_fpret? How can that work?
00168     return getMessageSendSuperFn2();
00169   }
00170 
00171 protected:
00172   CodeGen::CodeGenModule &CGM;
00173 
00174 public:
00175   llvm::Type *ShortTy, *IntTy, *LongTy, *LongLongTy;
00176   llvm::Type *Int8PtrTy, *Int8PtrPtrTy;
00177   llvm::Type *IvarOffsetVarTy;
00178 
00179   /// ObjectPtrTy - LLVM type for object handles (typeof(id))
00180   llvm::Type *ObjectPtrTy;
00181 
00182   /// PtrObjectPtrTy - LLVM type for id *
00183   llvm::Type *PtrObjectPtrTy;
00184 
00185   /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
00186   llvm::Type *SelectorPtrTy;
00187   
00188 private:
00189   /// ProtocolPtrTy - LLVM type for external protocol handles
00190   /// (typeof(Protocol))
00191   llvm::Type *ExternalProtocolPtrTy;
00192   
00193 public:
00194   llvm::Type *getExternalProtocolPtrTy() {
00195     if (!ExternalProtocolPtrTy) {
00196       // FIXME: It would be nice to unify this with the opaque type, so that the
00197       // IR comes out a bit cleaner.
00198       CodeGen::CodeGenTypes &Types = CGM.getTypes();
00199       ASTContext &Ctx = CGM.getContext();
00200       llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
00201       ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
00202     }
00203     
00204     return ExternalProtocolPtrTy;
00205   }
00206   
00207   // SuperCTy - clang type for struct objc_super.
00208   QualType SuperCTy;
00209   // SuperPtrCTy - clang type for struct objc_super *.
00210   QualType SuperPtrCTy;
00211 
00212   /// SuperTy - LLVM type for struct objc_super.
00213   llvm::StructType *SuperTy;
00214   /// SuperPtrTy - LLVM type for struct objc_super *.
00215   llvm::Type *SuperPtrTy;
00216 
00217   /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
00218   /// in GCC parlance).
00219   llvm::StructType *PropertyTy;
00220 
00221   /// PropertyListTy - LLVM type for struct objc_property_list
00222   /// (_prop_list_t in GCC parlance).
00223   llvm::StructType *PropertyListTy;
00224   /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
00225   llvm::Type *PropertyListPtrTy;
00226 
00227   // MethodTy - LLVM type for struct objc_method.
00228   llvm::StructType *MethodTy;
00229 
00230   /// CacheTy - LLVM type for struct objc_cache.
00231   llvm::Type *CacheTy;
00232   /// CachePtrTy - LLVM type for struct objc_cache *.
00233   llvm::Type *CachePtrTy;
00234   
00235   llvm::Constant *getGetPropertyFn() {
00236     CodeGen::CodeGenTypes &Types = CGM.getTypes();
00237     ASTContext &Ctx = CGM.getContext();
00238     // id objc_getProperty (id, SEL, ptrdiff_t, bool)
00239     SmallVector<CanQualType,4> Params;
00240     CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
00241     CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
00242     Params.push_back(IdType);
00243     Params.push_back(SelType);
00244     Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified());
00245     Params.push_back(Ctx.BoolTy);
00246     llvm::FunctionType *FTy =
00247       Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(IdType, false, Params,
00248                                                           FunctionType::ExtInfo(),
00249                                                           RequiredArgs::All));
00250     return CGM.CreateRuntimeFunction(FTy, "objc_getProperty");
00251   }
00252 
00253   llvm::Constant *getSetPropertyFn() {
00254     CodeGen::CodeGenTypes &Types = CGM.getTypes();
00255     ASTContext &Ctx = CGM.getContext();
00256     // void objc_setProperty (id, SEL, ptrdiff_t, id, bool, bool)
00257     SmallVector<CanQualType,6> Params;
00258     CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
00259     CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
00260     Params.push_back(IdType);
00261     Params.push_back(SelType);
00262     Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified());
00263     Params.push_back(IdType);
00264     Params.push_back(Ctx.BoolTy);
00265     Params.push_back(Ctx.BoolTy);
00266     llvm::FunctionType *FTy =
00267       Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(Ctx.VoidTy, false,
00268                                                           Params,
00269                                                           FunctionType::ExtInfo(),
00270                                                           RequiredArgs::All));
00271     return CGM.CreateRuntimeFunction(FTy, "objc_setProperty");
00272   }
00273 
00274   llvm::Constant *getOptimizedSetPropertyFn(bool atomic, bool copy) {
00275     CodeGen::CodeGenTypes &Types = CGM.getTypes();
00276     ASTContext &Ctx = CGM.getContext();
00277     // void objc_setProperty_atomic(id self, SEL _cmd, 
00278     //                              id newValue, ptrdiff_t offset);
00279     // void objc_setProperty_nonatomic(id self, SEL _cmd, 
00280     //                                 id newValue, ptrdiff_t offset);
00281     // void objc_setProperty_atomic_copy(id self, SEL _cmd, 
00282     //                                   id newValue, ptrdiff_t offset);
00283     // void objc_setProperty_nonatomic_copy(id self, SEL _cmd, 
00284     //                                      id newValue, ptrdiff_t offset);
00285     
00286     SmallVector<CanQualType,4> Params;
00287     CanQualType IdType = Ctx.getCanonicalParamType(Ctx.getObjCIdType());
00288     CanQualType SelType = Ctx.getCanonicalParamType(Ctx.getObjCSelType());
00289     Params.push_back(IdType);
00290     Params.push_back(SelType);
00291     Params.push_back(IdType);
00292     Params.push_back(Ctx.getPointerDiffType()->getCanonicalTypeUnqualified());
00293     llvm::FunctionType *FTy =
00294     Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(Ctx.VoidTy, false,
00295                                                         Params,
00296                                                         FunctionType::ExtInfo(),
00297                                                         RequiredArgs::All));
00298     const char *name;
00299     if (atomic && copy)
00300       name = "objc_setProperty_atomic_copy";
00301     else if (atomic && !copy)
00302       name = "objc_setProperty_atomic";
00303     else if (!atomic && copy)
00304       name = "objc_setProperty_nonatomic_copy";
00305     else
00306       name = "objc_setProperty_nonatomic";
00307       
00308     return CGM.CreateRuntimeFunction(FTy, name);
00309   }
00310   
00311   llvm::Constant *getCopyStructFn() {
00312     CodeGen::CodeGenTypes &Types = CGM.getTypes();
00313     ASTContext &Ctx = CGM.getContext();
00314     // void objc_copyStruct (void *, const void *, size_t, bool, bool)
00315     SmallVector<CanQualType,5> Params;
00316     Params.push_back(Ctx.VoidPtrTy);
00317     Params.push_back(Ctx.VoidPtrTy);
00318     Params.push_back(Ctx.LongTy);
00319     Params.push_back(Ctx.BoolTy);
00320     Params.push_back(Ctx.BoolTy);
00321     llvm::FunctionType *FTy =
00322       Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(Ctx.VoidTy, false,
00323                                                           Params,
00324                                                           FunctionType::ExtInfo(),
00325                                                           RequiredArgs::All));
00326     return CGM.CreateRuntimeFunction(FTy, "objc_copyStruct");
00327   }
00328   
00329   /// This routine declares and returns address of:
00330   /// void objc_copyCppObjectAtomic(
00331   ///         void *dest, const void *src, 
00332   ///         void (*copyHelper) (void *dest, const void *source));
00333   llvm::Constant *getCppAtomicObjectFunction() {
00334     CodeGen::CodeGenTypes &Types = CGM.getTypes();
00335     ASTContext &Ctx = CGM.getContext();
00336     /// void objc_copyCppObjectAtomic(void *dest, const void *src, void *helper);
00337     SmallVector<CanQualType,3> Params;
00338     Params.push_back(Ctx.VoidPtrTy);
00339     Params.push_back(Ctx.VoidPtrTy);
00340     Params.push_back(Ctx.VoidPtrTy);
00341     llvm::FunctionType *FTy =
00342       Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(Ctx.VoidTy, false,
00343                                                           Params,
00344                                                           FunctionType::ExtInfo(),
00345                                                           RequiredArgs::All));
00346     return CGM.CreateRuntimeFunction(FTy, "objc_copyCppObjectAtomic");
00347   }
00348   
00349   llvm::Constant *getEnumerationMutationFn() {
00350     CodeGen::CodeGenTypes &Types = CGM.getTypes();
00351     ASTContext &Ctx = CGM.getContext();
00352     // void objc_enumerationMutation (id)
00353     SmallVector<CanQualType,1> Params;
00354     Params.push_back(Ctx.getCanonicalParamType(Ctx.getObjCIdType()));
00355     llvm::FunctionType *FTy =
00356       Types.GetFunctionType(Types.arrangeLLVMFunctionInfo(Ctx.VoidTy, false,
00357                                                           Params,
00358                                                           FunctionType::ExtInfo(),
00359                                                       RequiredArgs::All));
00360     return CGM.CreateRuntimeFunction(FTy, "objc_enumerationMutation");
00361   }
00362 
00363   /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
00364   llvm::Constant *getGcReadWeakFn() {
00365     // id objc_read_weak (id *)
00366     llvm::Type *args[] = { ObjectPtrTy->getPointerTo() };
00367     llvm::FunctionType *FTy =
00368       llvm::FunctionType::get(ObjectPtrTy, args, false);
00369     return CGM.CreateRuntimeFunction(FTy, "objc_read_weak");
00370   }
00371 
00372   /// GcAssignWeakFn -- LLVM objc_assign_weak function.
00373   llvm::Constant *getGcAssignWeakFn() {
00374     // id objc_assign_weak (id, id *)
00375     llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
00376     llvm::FunctionType *FTy =
00377       llvm::FunctionType::get(ObjectPtrTy, args, false);
00378     return CGM.CreateRuntimeFunction(FTy, "objc_assign_weak");
00379   }
00380 
00381   /// GcAssignGlobalFn -- LLVM objc_assign_global function.
00382   llvm::Constant *getGcAssignGlobalFn() {
00383     // id objc_assign_global(id, id *)
00384     llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
00385     llvm::FunctionType *FTy =
00386       llvm::FunctionType::get(ObjectPtrTy, args, false);
00387     return CGM.CreateRuntimeFunction(FTy, "objc_assign_global");
00388   }
00389 
00390   /// GcAssignThreadLocalFn -- LLVM objc_assign_threadlocal function.
00391   llvm::Constant *getGcAssignThreadLocalFn() {
00392     // id objc_assign_threadlocal(id src, id * dest)
00393     llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
00394     llvm::FunctionType *FTy =
00395       llvm::FunctionType::get(ObjectPtrTy, args, false);
00396     return CGM.CreateRuntimeFunction(FTy, "objc_assign_threadlocal");
00397   }
00398   
00399   /// GcAssignIvarFn -- LLVM objc_assign_ivar function.
00400   llvm::Constant *getGcAssignIvarFn() {
00401     // id objc_assign_ivar(id, id *, ptrdiff_t)
00402     llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo(),
00403                            CGM.PtrDiffTy };
00404     llvm::FunctionType *FTy =
00405       llvm::FunctionType::get(ObjectPtrTy, args, false);
00406     return CGM.CreateRuntimeFunction(FTy, "objc_assign_ivar");
00407   }
00408 
00409   /// GcMemmoveCollectableFn -- LLVM objc_memmove_collectable function.
00410   llvm::Constant *GcMemmoveCollectableFn() {
00411     // void *objc_memmove_collectable(void *dst, const void *src, size_t size)
00412     llvm::Type *args[] = { Int8PtrTy, Int8PtrTy, LongTy };
00413     llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, args, false);
00414     return CGM.CreateRuntimeFunction(FTy, "objc_memmove_collectable");
00415   }
00416 
00417   /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
00418   llvm::Constant *getGcAssignStrongCastFn() {
00419     // id objc_assign_strongCast(id, id *)
00420     llvm::Type *args[] = { ObjectPtrTy, ObjectPtrTy->getPointerTo() };
00421     llvm::FunctionType *FTy =
00422       llvm::FunctionType::get(ObjectPtrTy, args, false);
00423     return CGM.CreateRuntimeFunction(FTy, "objc_assign_strongCast");
00424   }
00425 
00426   /// ExceptionThrowFn - LLVM objc_exception_throw function.
00427   llvm::Constant *getExceptionThrowFn() {
00428     // void objc_exception_throw(id)
00429     llvm::Type *args[] = { ObjectPtrTy };
00430     llvm::FunctionType *FTy =
00431       llvm::FunctionType::get(CGM.VoidTy, args, false);
00432     return CGM.CreateRuntimeFunction(FTy, "objc_exception_throw");
00433   }
00434 
00435   /// ExceptionRethrowFn - LLVM objc_exception_rethrow function.
00436   llvm::Constant *getExceptionRethrowFn() {
00437     // void objc_exception_rethrow(void)
00438     llvm::FunctionType *FTy = llvm::FunctionType::get(CGM.VoidTy, false);
00439     return CGM.CreateRuntimeFunction(FTy, "objc_exception_rethrow");
00440   }
00441   
00442   /// SyncEnterFn - LLVM object_sync_enter function.
00443   llvm::Constant *getSyncEnterFn() {
00444     // int objc_sync_enter (id)
00445     llvm::Type *args[] = { ObjectPtrTy };
00446     llvm::FunctionType *FTy =
00447       llvm::FunctionType::get(CGM.IntTy, args, false);
00448     return CGM.CreateRuntimeFunction(FTy, "objc_sync_enter");
00449   }
00450 
00451   /// SyncExitFn - LLVM object_sync_exit function.
00452   llvm::Constant *getSyncExitFn() {
00453     // int objc_sync_exit (id)
00454     llvm::Type *args[] = { ObjectPtrTy };
00455     llvm::FunctionType *FTy =
00456       llvm::FunctionType::get(CGM.IntTy, args, false);
00457     return CGM.CreateRuntimeFunction(FTy, "objc_sync_exit");
00458   }
00459 
00460   llvm::Constant *getSendFn(bool IsSuper) const {
00461     return IsSuper ? getMessageSendSuperFn() : getMessageSendFn();
00462   }
00463 
00464   llvm::Constant *getSendFn2(bool IsSuper) const {
00465     return IsSuper ? getMessageSendSuperFn2() : getMessageSendFn();
00466   }
00467 
00468   llvm::Constant *getSendStretFn(bool IsSuper) const {
00469     return IsSuper ? getMessageSendSuperStretFn() : getMessageSendStretFn();
00470   }
00471 
00472   llvm::Constant *getSendStretFn2(bool IsSuper) const {
00473     return IsSuper ? getMessageSendSuperStretFn2() : getMessageSendStretFn();
00474   }
00475 
00476   llvm::Constant *getSendFpretFn(bool IsSuper) const {
00477     return IsSuper ? getMessageSendSuperFpretFn() : getMessageSendFpretFn();
00478   }
00479 
00480   llvm::Constant *getSendFpretFn2(bool IsSuper) const {
00481     return IsSuper ? getMessageSendSuperFpretFn2() : getMessageSendFpretFn();
00482   }
00483 
00484   llvm::Constant *getSendFp2retFn(bool IsSuper) const {
00485     return IsSuper ? getMessageSendSuperFn() : getMessageSendFp2retFn();
00486   }
00487 
00488   llvm::Constant *getSendFp2RetFn2(bool IsSuper) const {
00489     return IsSuper ? getMessageSendSuperFn2() : getMessageSendFp2retFn();
00490   }
00491 
00492   ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm);
00493   ~ObjCCommonTypesHelper(){}
00494 };
00495 
00496 /// ObjCTypesHelper - Helper class that encapsulates lazy
00497 /// construction of varies types used during ObjC generation.
00498 class ObjCTypesHelper : public ObjCCommonTypesHelper {
00499 public:
00500   /// SymtabTy - LLVM type for struct objc_symtab.
00501   llvm::StructType *SymtabTy;
00502   /// SymtabPtrTy - LLVM type for struct objc_symtab *.
00503   llvm::Type *SymtabPtrTy;
00504   /// ModuleTy - LLVM type for struct objc_module.
00505   llvm::StructType *ModuleTy;
00506 
00507   /// ProtocolTy - LLVM type for struct objc_protocol.
00508   llvm::StructType *ProtocolTy;
00509   /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
00510   llvm::Type *ProtocolPtrTy;
00511   /// ProtocolExtensionTy - LLVM type for struct
00512   /// objc_protocol_extension.
00513   llvm::StructType *ProtocolExtensionTy;
00514   /// ProtocolExtensionTy - LLVM type for struct
00515   /// objc_protocol_extension *.
00516   llvm::Type *ProtocolExtensionPtrTy;
00517   /// MethodDescriptionTy - LLVM type for struct
00518   /// objc_method_description.
00519   llvm::StructType *MethodDescriptionTy;
00520   /// MethodDescriptionListTy - LLVM type for struct
00521   /// objc_method_description_list.
00522   llvm::StructType *MethodDescriptionListTy;
00523   /// MethodDescriptionListPtrTy - LLVM type for struct
00524   /// objc_method_description_list *.
00525   llvm::Type *MethodDescriptionListPtrTy;
00526   /// ProtocolListTy - LLVM type for struct objc_property_list.
00527   llvm::StructType *ProtocolListTy;
00528   /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
00529   llvm::Type *ProtocolListPtrTy;
00530   /// CategoryTy - LLVM type for struct objc_category.
00531   llvm::StructType *CategoryTy;
00532   /// ClassTy - LLVM type for struct objc_class.
00533   llvm::StructType *ClassTy;
00534   /// ClassPtrTy - LLVM type for struct objc_class *.
00535   llvm::Type *ClassPtrTy;
00536   /// ClassExtensionTy - LLVM type for struct objc_class_ext.
00537   llvm::StructType *ClassExtensionTy;
00538   /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
00539   llvm::Type *ClassExtensionPtrTy;
00540   // IvarTy - LLVM type for struct objc_ivar.
00541   llvm::StructType *IvarTy;
00542   /// IvarListTy - LLVM type for struct objc_ivar_list.
00543   llvm::Type *IvarListTy;
00544   /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
00545   llvm::Type *IvarListPtrTy;
00546   /// MethodListTy - LLVM type for struct objc_method_list.
00547   llvm::Type *MethodListTy;
00548   /// MethodListPtrTy - LLVM type for struct objc_method_list *.
00549   llvm::Type *MethodListPtrTy;
00550 
00551   /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
00552   llvm::Type *ExceptionDataTy;
00553   
00554   /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
00555   llvm::Constant *getExceptionTryEnterFn() {
00556     llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
00557     return CGM.CreateRuntimeFunction(
00558       llvm::FunctionType::get(CGM.VoidTy, params, false),
00559       "objc_exception_try_enter");
00560   }
00561 
00562   /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
00563   llvm::Constant *getExceptionTryExitFn() {
00564     llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
00565     return CGM.CreateRuntimeFunction(
00566       llvm::FunctionType::get(CGM.VoidTy, params, false),
00567       "objc_exception_try_exit");
00568   }
00569 
00570   /// ExceptionExtractFn - LLVM objc_exception_extract function.
00571   llvm::Constant *getExceptionExtractFn() {
00572     llvm::Type *params[] = { ExceptionDataTy->getPointerTo() };
00573     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
00574                                                              params, false),
00575                                      "objc_exception_extract");
00576   }
00577 
00578   /// ExceptionMatchFn - LLVM objc_exception_match function.
00579   llvm::Constant *getExceptionMatchFn() {
00580     llvm::Type *params[] = { ClassPtrTy, ObjectPtrTy };
00581     return CGM.CreateRuntimeFunction(
00582       llvm::FunctionType::get(CGM.Int32Ty, params, false),
00583       "objc_exception_match");
00584 
00585   }
00586 
00587   /// SetJmpFn - LLVM _setjmp function.
00588   llvm::Constant *getSetJmpFn() {
00589     // This is specifically the prototype for x86.
00590     llvm::Type *params[] = { CGM.Int32Ty->getPointerTo() };
00591     return
00592       CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.Int32Ty,
00593                                                         params, false),
00594                                 "_setjmp",
00595                                 llvm::AttributeSet::get(CGM.getLLVMContext(),
00596                                               llvm::AttributeSet::FunctionIndex,
00597                                                  llvm::Attribute::NonLazyBind));
00598   }
00599 
00600 public:
00601   ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
00602   ~ObjCTypesHelper() {}
00603 };
00604 
00605 /// ObjCNonFragileABITypesHelper - will have all types needed by objective-c's
00606 /// modern abi
00607 class ObjCNonFragileABITypesHelper : public ObjCCommonTypesHelper {
00608 public:
00609 
00610   // MethodListnfABITy - LLVM for struct _method_list_t
00611   llvm::StructType *MethodListnfABITy;
00612 
00613   // MethodListnfABIPtrTy - LLVM for struct _method_list_t*
00614   llvm::Type *MethodListnfABIPtrTy;
00615 
00616   // ProtocolnfABITy = LLVM for struct _protocol_t
00617   llvm::StructType *ProtocolnfABITy;
00618 
00619   // ProtocolnfABIPtrTy = LLVM for struct _protocol_t*
00620   llvm::Type *ProtocolnfABIPtrTy;
00621 
00622   // ProtocolListnfABITy - LLVM for struct _objc_protocol_list
00623   llvm::StructType *ProtocolListnfABITy;
00624 
00625   // ProtocolListnfABIPtrTy - LLVM for struct _objc_protocol_list*
00626   llvm::Type *ProtocolListnfABIPtrTy;
00627 
00628   // ClassnfABITy - LLVM for struct _class_t
00629   llvm::StructType *ClassnfABITy;
00630 
00631   // ClassnfABIPtrTy - LLVM for struct _class_t*
00632   llvm::Type *ClassnfABIPtrTy;
00633 
00634   // IvarnfABITy - LLVM for struct _ivar_t
00635   llvm::StructType *IvarnfABITy;
00636 
00637   // IvarListnfABITy - LLVM for struct _ivar_list_t
00638   llvm::StructType *IvarListnfABITy;
00639 
00640   // IvarListnfABIPtrTy = LLVM for struct _ivar_list_t*
00641   llvm::Type *IvarListnfABIPtrTy;
00642 
00643   // ClassRonfABITy - LLVM for struct _class_ro_t
00644   llvm::StructType *ClassRonfABITy;
00645 
00646   // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
00647   llvm::Type *ImpnfABITy;
00648 
00649   // CategorynfABITy - LLVM for struct _category_t
00650   llvm::StructType *CategorynfABITy;
00651 
00652   // New types for nonfragile abi messaging.
00653 
00654   // MessageRefTy - LLVM for:
00655   // struct _message_ref_t {
00656   //   IMP messenger;
00657   //   SEL name;
00658   // };
00659   llvm::StructType *MessageRefTy;
00660   // MessageRefCTy - clang type for struct _message_ref_t
00661   QualType MessageRefCTy;
00662 
00663   // MessageRefPtrTy - LLVM for struct _message_ref_t*
00664   llvm::Type *MessageRefPtrTy;
00665   // MessageRefCPtrTy - clang type for struct _message_ref_t*
00666   QualType MessageRefCPtrTy;
00667 
00668   // MessengerTy - Type of the messenger (shown as IMP above)
00669   llvm::FunctionType *MessengerTy;
00670 
00671   // SuperMessageRefTy - LLVM for:
00672   // struct _super_message_ref_t {
00673   //   SUPER_IMP messenger;
00674   //   SEL name;
00675   // };
00676   llvm::StructType *SuperMessageRefTy;
00677 
00678   // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
00679   llvm::Type *SuperMessageRefPtrTy;
00680 
00681   llvm::Constant *getMessageSendFixupFn() {
00682     // id objc_msgSend_fixup(id, struct message_ref_t*, ...)
00683     llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
00684     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
00685                                                              params, true),
00686                                      "objc_msgSend_fixup");
00687   }
00688 
00689   llvm::Constant *getMessageSendFpretFixupFn() {
00690     // id objc_msgSend_fpret_fixup(id, struct message_ref_t*, ...)
00691     llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
00692     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
00693                                                              params, true),
00694                                      "objc_msgSend_fpret_fixup");
00695   }
00696 
00697   llvm::Constant *getMessageSendStretFixupFn() {
00698     // id objc_msgSend_stret_fixup(id, struct message_ref_t*, ...)
00699     llvm::Type *params[] = { ObjectPtrTy, MessageRefPtrTy };
00700     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
00701                                                              params, true),
00702                                      "objc_msgSend_stret_fixup");
00703   }
00704 
00705   llvm::Constant *getMessageSendSuper2FixupFn() {
00706     // id objc_msgSendSuper2_fixup (struct objc_super *,
00707     //                              struct _super_message_ref_t*, ...)
00708     llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy };
00709     return  CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
00710                                                               params, true),
00711                                       "objc_msgSendSuper2_fixup");
00712   }
00713 
00714   llvm::Constant *getMessageSendSuper2StretFixupFn() {
00715     // id objc_msgSendSuper2_stret_fixup(struct objc_super *,
00716     //                                   struct _super_message_ref_t*, ...)
00717     llvm::Type *params[] = { SuperPtrTy, SuperMessageRefPtrTy };
00718     return  CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
00719                                                               params, true),
00720                                       "objc_msgSendSuper2_stret_fixup");
00721   }
00722 
00723   llvm::Constant *getObjCEndCatchFn() {
00724     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy, false),
00725                                      "objc_end_catch");
00726 
00727   }
00728 
00729   llvm::Constant *getObjCBeginCatchFn() {
00730     llvm::Type *params[] = { Int8PtrTy };
00731     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(Int8PtrTy,
00732                                                              params, false),
00733                                      "objc_begin_catch");
00734   }
00735 
00736   llvm::StructType *EHTypeTy;
00737   llvm::Type *EHTypePtrTy;
00738   
00739   ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm);
00740   ~ObjCNonFragileABITypesHelper(){}
00741 };
00742 
00743 class CGObjCCommonMac : public CodeGen::CGObjCRuntime {
00744 public:
00745   // FIXME - accessibility
00746   class GC_IVAR {
00747   public:
00748     unsigned ivar_bytepos;
00749     unsigned ivar_size;
00750     GC_IVAR(unsigned bytepos = 0, unsigned size = 0)
00751       : ivar_bytepos(bytepos), ivar_size(size) {}
00752 
00753     // Allow sorting based on byte pos.
00754     bool operator<(const GC_IVAR &b) const {
00755       return ivar_bytepos < b.ivar_bytepos;
00756     }
00757   };
00758 
00759   class SKIP_SCAN {
00760   public:
00761     unsigned skip;
00762     unsigned scan;
00763     SKIP_SCAN(unsigned _skip = 0, unsigned _scan = 0)
00764       : skip(_skip), scan(_scan) {}
00765   };
00766 
00767   /// opcode for captured block variables layout 'instructions'.
00768   /// In the following descriptions, 'I' is the value of the immediate field.
00769   /// (field following the opcode).
00770   ///
00771   enum BLOCK_LAYOUT_OPCODE {
00772     /// An operator which affects how the following layout should be
00773     /// interpreted.
00774     ///   I == 0: Halt interpretation and treat everything else as
00775     ///           a non-pointer.  Note that this instruction is equal
00776     ///           to '\0'.
00777     ///   I != 0: Currently unused.
00778     BLOCK_LAYOUT_OPERATOR            = 0,
00779     
00780     /// The next I+1 bytes do not contain a value of object pointer type.
00781     /// Note that this can leave the stream unaligned, meaning that
00782     /// subsequent word-size instructions do not begin at a multiple of
00783     /// the pointer size.
00784     BLOCK_LAYOUT_NON_OBJECT_BYTES    = 1,
00785     
00786     /// The next I+1 words do not contain a value of object pointer type.
00787     /// This is simply an optimized version of BLOCK_LAYOUT_BYTES for
00788     /// when the required skip quantity is a multiple of the pointer size.
00789     BLOCK_LAYOUT_NON_OBJECT_WORDS    = 2,
00790     
00791     /// The next I+1 words are __strong pointers to Objective-C
00792     /// objects or blocks.
00793     BLOCK_LAYOUT_STRONG              = 3,
00794     
00795     /// The next I+1 words are pointers to __block variables.
00796     BLOCK_LAYOUT_BYREF               = 4,
00797     
00798     /// The next I+1 words are __weak pointers to Objective-C
00799     /// objects or blocks.
00800     BLOCK_LAYOUT_WEAK                = 5,
00801     
00802     /// The next I+1 words are __unsafe_unretained pointers to
00803     /// Objective-C objects or blocks.
00804     BLOCK_LAYOUT_UNRETAINED          = 6
00805     
00806     /// The next I+1 words are block or object pointers with some
00807     /// as-yet-unspecified ownership semantics.  If we add more
00808     /// flavors of ownership semantics, values will be taken from
00809     /// this range.
00810     ///
00811     /// This is included so that older tools can at least continue
00812     /// processing the layout past such things.
00813     //BLOCK_LAYOUT_OWNERSHIP_UNKNOWN = 7..10,
00814     
00815     /// All other opcodes are reserved.  Halt interpretation and
00816     /// treat everything else as opaque.
00817   };
00818  
00819   class RUN_SKIP {
00820   public:
00821     enum BLOCK_LAYOUT_OPCODE opcode;
00822     CharUnits block_var_bytepos;
00823     CharUnits block_var_size;
00824     RUN_SKIP(enum BLOCK_LAYOUT_OPCODE Opcode = BLOCK_LAYOUT_OPERATOR,
00825              CharUnits BytePos = CharUnits::Zero(),
00826              CharUnits Size = CharUnits::Zero())
00827     : opcode(Opcode), block_var_bytepos(BytePos),  block_var_size(Size) {}
00828     
00829     // Allow sorting based on byte pos.
00830     bool operator<(const RUN_SKIP &b) const {
00831       return block_var_bytepos < b.block_var_bytepos;
00832     }
00833   };
00834   
00835 protected:
00836   llvm::LLVMContext &VMContext;
00837   // FIXME! May not be needing this after all.
00838   unsigned ObjCABI;
00839 
00840   // gc ivar layout bitmap calculation helper caches.
00841   SmallVector<GC_IVAR, 16> SkipIvars;
00842   SmallVector<GC_IVAR, 16> IvarsInfo;
00843   
00844   // arc/mrr layout of captured block literal variables.
00845   SmallVector<RUN_SKIP, 16> RunSkipBlockVars;
00846 
00847   /// LazySymbols - Symbols to generate a lazy reference for. See
00848   /// DefinedSymbols and FinishModule().
00849   llvm::SetVector<IdentifierInfo*> LazySymbols;
00850 
00851   /// DefinedSymbols - External symbols which are defined by this
00852   /// module. The symbols in this list and LazySymbols are used to add
00853   /// special linker symbols which ensure that Objective-C modules are
00854   /// linked properly.
00855   llvm::SetVector<IdentifierInfo*> DefinedSymbols;
00856 
00857   /// ClassNames - uniqued class names.
00858   llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
00859 
00860   /// MethodVarNames - uniqued method variable names.
00861   llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
00862 
00863   /// DefinedCategoryNames - list of category names in form Class_Category.
00864   llvm::SetVector<std::string> DefinedCategoryNames;
00865 
00866   /// MethodVarTypes - uniqued method type signatures. We have to use
00867   /// a StringMap here because have no other unique reference.
00868   llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
00869 
00870   /// MethodDefinitions - map of methods which have been defined in
00871   /// this translation unit.
00872   llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
00873 
00874   /// PropertyNames - uniqued method variable names.
00875   llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
00876 
00877   /// ClassReferences - uniqued class references.
00878   llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
00879 
00880   /// SelectorReferences - uniqued selector references.
00881   llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
00882 
00883   /// Protocols - Protocols for which an objc_protocol structure has
00884   /// been emitted. Forward declarations are handled by creating an
00885   /// empty structure whose initializer is filled in when/if defined.
00886   llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
00887 
00888   /// DefinedProtocols - Protocols which have actually been
00889   /// defined. We should not need this, see FIXME in GenerateProtocol.
00890   llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
00891 
00892   /// DefinedClasses - List of defined classes.
00893   SmallVector<llvm::GlobalValue*, 16> DefinedClasses;
00894   
00895   /// ImplementedClasses - List of @implemented classes.
00896   SmallVector<const ObjCInterfaceDecl*, 16> ImplementedClasses;
00897 
00898   /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
00899   SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyClasses;
00900 
00901   /// DefinedCategories - List of defined categories.
00902   SmallVector<llvm::GlobalValue*, 16> DefinedCategories;
00903 
00904   /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
00905   SmallVector<llvm::GlobalValue*, 16> DefinedNonLazyCategories;
00906 
00907   /// GetNameForMethod - Return a name for the given method.
00908   /// \param[out] NameOut - The return value.
00909   void GetNameForMethod(const ObjCMethodDecl *OMD,
00910                         const ObjCContainerDecl *CD,
00911                         SmallVectorImpl<char> &NameOut);
00912 
00913   /// GetMethodVarName - Return a unique constant for the given
00914   /// selector's name. The return value has type char *.
00915   llvm::Constant *GetMethodVarName(Selector Sel);
00916   llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
00917 
00918   /// GetMethodVarType - Return a unique constant for the given
00919   /// method's type encoding string. The return value has type char *.
00920 
00921   // FIXME: This is a horrible name.
00922   llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D,
00923                                    bool Extended = false);
00924   llvm::Constant *GetMethodVarType(const FieldDecl *D);
00925 
00926   /// GetPropertyName - Return a unique constant for the given
00927   /// name. The return value has type char *.
00928   llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
00929 
00930   // FIXME: This can be dropped once string functions are unified.
00931   llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
00932                                         const Decl *Container);
00933 
00934   /// GetClassName - Return a unique constant for the given selector's
00935   /// name. The return value has type char *.
00936   llvm::Constant *GetClassName(IdentifierInfo *Ident);
00937 
00938   llvm::Function *GetMethodDefinition(const ObjCMethodDecl *MD);
00939 
00940   /// BuildIvarLayout - Builds ivar layout bitmap for the class
00941   /// implementation for the __strong or __weak case.
00942   ///
00943   llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
00944                                   bool ForStrongLayout);
00945   
00946   llvm::Constant *BuildIvarLayoutBitmap(std::string &BitMap);
00947 
00948   void BuildAggrIvarRecordLayout(const RecordType *RT,
00949                                  unsigned int BytePos, bool ForStrongLayout,
00950                                  bool &HasUnion);
00951   void BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
00952                            const llvm::StructLayout *Layout,
00953                            const RecordDecl *RD,
00954                            ArrayRef<const FieldDecl*> RecFields,
00955                            unsigned int BytePos, bool ForStrongLayout,
00956                            bool &HasUnion);
00957   
00958   Qualifiers::ObjCLifetime getBlockCaptureLifetime(QualType QT, bool ByrefLayout);
00959   
00960   void UpdateRunSkipBlockVars(bool IsByref,
00961                               Qualifiers::ObjCLifetime LifeTime,
00962                               CharUnits FieldOffset,
00963                               CharUnits FieldSize);
00964   
00965   void BuildRCBlockVarRecordLayout(const RecordType *RT,
00966                                    CharUnits BytePos, bool &HasUnion,
00967                                    bool ByrefLayout=false);
00968   
00969   void BuildRCRecordLayout(const llvm::StructLayout *RecLayout,
00970                            const RecordDecl *RD,
00971                            ArrayRef<const FieldDecl*> RecFields,
00972                            CharUnits BytePos, bool &HasUnion,
00973                            bool ByrefLayout);
00974   
00975   uint64_t InlineLayoutInstruction(SmallVectorImpl<unsigned char> &Layout);
00976   
00977   llvm::Constant *getBitmapBlockLayout(bool ComputeByrefLayout);
00978   
00979 
00980   /// GetIvarLayoutName - Returns a unique constant for the given
00981   /// ivar layout bitmap.
00982   llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
00983                                     const ObjCCommonTypesHelper &ObjCTypes);
00984 
00985   /// EmitPropertyList - Emit the given property list. The return
00986   /// value has type PropertyListPtrTy.
00987   llvm::Constant *EmitPropertyList(Twine Name,
00988                                    const Decl *Container,
00989                                    const ObjCContainerDecl *OCD,
00990                                    const ObjCCommonTypesHelper &ObjCTypes);
00991 
00992   /// EmitProtocolMethodTypes - Generate the array of extended method type 
00993   /// strings. The return value has type Int8PtrPtrTy.
00994   llvm::Constant *EmitProtocolMethodTypes(Twine Name, 
00995                                           ArrayRef<llvm::Constant*> MethodTypes,
00996                                        const ObjCCommonTypesHelper &ObjCTypes);
00997 
00998   /// PushProtocolProperties - Push protocol's property on the input stack.
00999   void PushProtocolProperties(
01000     llvm::SmallPtrSet<const IdentifierInfo*, 16> &PropertySet,
01001     SmallVectorImpl<llvm::Constant*> &Properties,
01002     const Decl *Container,
01003     const ObjCProtocolDecl *Proto,
01004     const ObjCCommonTypesHelper &ObjCTypes);
01005 
01006   /// GetProtocolRef - Return a reference to the internal protocol
01007   /// description, creating an empty one if it has not been
01008   /// defined. The return value has type ProtocolPtrTy.
01009   llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
01010 
01011   /// CreateMetadataVar - Create a global variable with internal
01012   /// linkage for use by the Objective-C runtime.
01013   ///
01014   /// This is a convenience wrapper which not only creates the
01015   /// variable, but also sets the section and alignment and adds the
01016   /// global to the "llvm.used" list.
01017   ///
01018   /// \param Name - The variable name.
01019   /// \param Init - The variable initializer; this is also used to
01020   /// define the type of the variable.
01021   /// \param Section - The section the variable should go into, or 0.
01022   /// \param Align - The alignment for the variable, or 0.
01023   /// \param AddToUsed - Whether the variable should be added to
01024   /// "llvm.used".
01025   llvm::GlobalVariable *CreateMetadataVar(Twine Name,
01026                                           llvm::Constant *Init,
01027                                           const char *Section,
01028                                           unsigned Align,
01029                                           bool AddToUsed);
01030 
01031   CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
01032                                   ReturnValueSlot Return,
01033                                   QualType ResultType,
01034                                   llvm::Value *Sel,
01035                                   llvm::Value *Arg0,
01036                                   QualType Arg0Ty,
01037                                   bool IsSuper,
01038                                   const CallArgList &CallArgs,
01039                                   const ObjCMethodDecl *OMD,
01040                                   const ObjCCommonTypesHelper &ObjCTypes);
01041 
01042   /// EmitImageInfo - Emit the image info marker used to encode some module
01043   /// level information.
01044   void EmitImageInfo();
01045 
01046 public:
01047   CGObjCCommonMac(CodeGen::CodeGenModule &cgm) :
01048     CGObjCRuntime(cgm), VMContext(cgm.getLLVMContext()) { }
01049 
01050   llvm::Constant *GenerateConstantString(const StringLiteral *SL) override;
01051 
01052   llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
01053                                  const ObjCContainerDecl *CD=0) override;
01054 
01055   void GenerateProtocol(const ObjCProtocolDecl *PD) override;
01056 
01057   /// GetOrEmitProtocol - Get the protocol object for the given
01058   /// declaration, emitting it if necessary. The return value has type
01059   /// ProtocolPtrTy.
01060   virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
01061 
01062   /// GetOrEmitProtocolRef - Get a forward reference to the protocol
01063   /// object for the given declaration, emitting it if needed. These
01064   /// forward references will be filled in with empty bodies if no
01065   /// definition is seen. The return value has type ProtocolPtrTy.
01066   virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
01067   llvm::Constant *BuildGCBlockLayout(CodeGen::CodeGenModule &CGM,
01068                                      const CGBlockInfo &blockInfo) override;
01069   llvm::Constant *BuildRCBlockLayout(CodeGen::CodeGenModule &CGM,
01070                                      const CGBlockInfo &blockInfo) override;
01071 
01072   llvm::Constant *BuildByrefLayout(CodeGen::CodeGenModule &CGM,
01073                                    QualType T) override;
01074 };
01075 
01076 class CGObjCMac : public CGObjCCommonMac {
01077 private:
01078   ObjCTypesHelper ObjCTypes;
01079 
01080   /// EmitModuleInfo - Another marker encoding module level
01081   /// information.
01082   void EmitModuleInfo();
01083 
01084   /// EmitModuleSymols - Emit module symbols, the list of defined
01085   /// classes and categories. The result has type SymtabPtrTy.
01086   llvm::Constant *EmitModuleSymbols();
01087 
01088   /// FinishModule - Write out global data structures at the end of
01089   /// processing a translation unit.
01090   void FinishModule();
01091 
01092   /// EmitClassExtension - Generate the class extension structure used
01093   /// to store the weak ivar layout and properties. The return value
01094   /// has type ClassExtensionPtrTy.
01095   llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
01096 
01097   /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
01098   /// for the given class.
01099   llvm::Value *EmitClassRef(CodeGenFunction &CGF,
01100                             const ObjCInterfaceDecl *ID);
01101   
01102   llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF,
01103                                   IdentifierInfo *II);
01104 
01105   llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
01106 
01107   /// EmitSuperClassRef - Emits reference to class's main metadata class.
01108   llvm::Value *EmitSuperClassRef(const ObjCInterfaceDecl *ID);
01109 
01110   /// EmitIvarList - Emit the ivar list for the given
01111   /// implementation. If ForClass is true the list of class ivars
01112   /// (i.e. metaclass ivars) is emitted, otherwise the list of
01113   /// interface ivars will be emitted. The return value has type
01114   /// IvarListPtrTy.
01115   llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
01116                                bool ForClass);
01117 
01118   /// EmitMetaClass - Emit a forward reference to the class structure
01119   /// for the metaclass of the given interface. The return value has
01120   /// type ClassPtrTy.
01121   llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
01122 
01123   /// EmitMetaClass - Emit a class structure for the metaclass of the
01124   /// given implementation. The return value has type ClassPtrTy.
01125   llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
01126                                 llvm::Constant *Protocols,
01127                                 ArrayRef<llvm::Constant*> Methods);
01128 
01129   llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
01130 
01131   llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
01132 
01133   /// EmitMethodList - Emit the method list for the given
01134   /// implementation. The return value has type MethodListPtrTy.
01135   llvm::Constant *EmitMethodList(Twine Name,
01136                                  const char *Section,
01137                                  ArrayRef<llvm::Constant*> Methods);
01138 
01139   /// EmitMethodDescList - Emit a method description list for a list of
01140   /// method declarations.
01141   ///  - TypeName: The name for the type containing the methods.
01142   ///  - IsProtocol: True iff these methods are for a protocol.
01143   ///  - ClassMethds: True iff these are class methods.
01144   ///  - Required: When true, only "required" methods are
01145   ///    listed. Similarly, when false only "optional" methods are
01146   ///    listed. For classes this should always be true.
01147   ///  - begin, end: The method list to output.
01148   ///
01149   /// The return value has type MethodDescriptionListPtrTy.
01150   llvm::Constant *EmitMethodDescList(Twine Name,
01151                                      const char *Section,
01152                                      ArrayRef<llvm::Constant*> Methods);
01153 
01154   /// GetOrEmitProtocol - Get the protocol object for the given
01155   /// declaration, emitting it if necessary. The return value has type
01156   /// ProtocolPtrTy.
01157   llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override;
01158 
01159   /// GetOrEmitProtocolRef - Get a forward reference to the protocol
01160   /// object for the given declaration, emitting it if needed. These
01161   /// forward references will be filled in with empty bodies if no
01162   /// definition is seen. The return value has type ProtocolPtrTy.
01163   llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) override;
01164 
01165   /// EmitProtocolExtension - Generate the protocol extension
01166   /// structure used to store optional instance and class methods, and
01167   /// protocol properties. The return value has type
01168   /// ProtocolExtensionPtrTy.
01169   llvm::Constant *
01170   EmitProtocolExtension(const ObjCProtocolDecl *PD,
01171                         ArrayRef<llvm::Constant*> OptInstanceMethods,
01172                         ArrayRef<llvm::Constant*> OptClassMethods,
01173                         ArrayRef<llvm::Constant*> MethodTypesExt);
01174 
01175   /// EmitProtocolList - Generate the list of referenced
01176   /// protocols. The return value has type ProtocolListPtrTy.
01177   llvm::Constant *EmitProtocolList(Twine Name,
01178                                    ObjCProtocolDecl::protocol_iterator begin,
01179                                    ObjCProtocolDecl::protocol_iterator end);
01180 
01181   /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
01182   /// for the given selector.
01183   llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel, 
01184                             bool lval=false);
01185 
01186 public:
01187   CGObjCMac(CodeGen::CodeGenModule &cgm);
01188 
01189   llvm::Function *ModuleInitFunction() override;
01190 
01191   CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
01192                                       ReturnValueSlot Return,
01193                                       QualType ResultType,
01194                                       Selector Sel, llvm::Value *Receiver,
01195                                       const CallArgList &CallArgs,
01196                                       const ObjCInterfaceDecl *Class,
01197                                       const ObjCMethodDecl *Method) override;
01198 
01199   CodeGen::RValue
01200   GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
01201                            ReturnValueSlot Return, QualType ResultType,
01202                            Selector Sel, const ObjCInterfaceDecl *Class,
01203                            bool isCategoryImpl, llvm::Value *Receiver,
01204                            bool IsClassMessage, const CallArgList &CallArgs,
01205                            const ObjCMethodDecl *Method) override;
01206 
01207   llvm::Value *GetClass(CodeGenFunction &CGF,
01208                         const ObjCInterfaceDecl *ID) override;
01209 
01210   llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
01211                            bool lval = false) override;
01212 
01213   /// The NeXT/Apple runtimes do not support typed selectors; just emit an
01214   /// untyped one.
01215   llvm::Value *GetSelector(CodeGenFunction &CGF,
01216                            const ObjCMethodDecl *Method) override;
01217 
01218   llvm::Constant *GetEHType(QualType T) override;
01219 
01220   void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
01221 
01222   void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
01223 
01224   void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override {}
01225 
01226   llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
01227                                    const ObjCProtocolDecl *PD) override;
01228 
01229   llvm::Constant *GetPropertyGetFunction() override;
01230   llvm::Constant *GetPropertySetFunction() override;
01231   llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
01232                                                   bool copy) override;
01233   llvm::Constant *GetGetStructFunction() override;
01234   llvm::Constant *GetSetStructFunction() override;
01235   llvm::Constant *GetCppAtomicObjectGetFunction() override;
01236   llvm::Constant *GetCppAtomicObjectSetFunction() override;
01237   llvm::Constant *EnumerationMutationFunction() override;
01238 
01239   void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
01240                    const ObjCAtTryStmt &S) override;
01241   void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
01242                             const ObjCAtSynchronizedStmt &S) override;
01243   void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const Stmt &S);
01244   void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S,
01245                      bool ClearInsertionPoint=true) override;
01246   llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
01247                                  llvm::Value *AddrWeakObj) override;
01248   void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
01249                           llvm::Value *src, llvm::Value *dst) override;
01250   void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
01251                             llvm::Value *src, llvm::Value *dest,
01252                             bool threadlocal = false) override;
01253   void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
01254                           llvm::Value *src, llvm::Value *dest,
01255                           llvm::Value *ivarOffset) override;
01256   void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
01257                                 llvm::Value *src, llvm::Value *dest) override;
01258   void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
01259                                 llvm::Value *dest, llvm::Value *src,
01260                                 llvm::Value *size) override;
01261 
01262   LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy,
01263                               llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
01264                               unsigned CVRQualifiers) override;
01265   llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
01266                               const ObjCInterfaceDecl *Interface,
01267                               const ObjCIvarDecl *Ivar) override;
01268 
01269   /// GetClassGlobal - Return the global variable for the Objective-C
01270   /// class of the given name.
01271   llvm::GlobalVariable *GetClassGlobal(const std::string &Name,
01272                                        bool Weak = false) override {
01273     llvm_unreachable("CGObjCMac::GetClassGlobal");
01274   }
01275 };
01276 
01277 class CGObjCNonFragileABIMac : public CGObjCCommonMac {
01278 private:
01279   ObjCNonFragileABITypesHelper ObjCTypes;
01280   llvm::GlobalVariable* ObjCEmptyCacheVar;
01281   llvm::GlobalVariable* ObjCEmptyVtableVar;
01282 
01283   /// SuperClassReferences - uniqued super class references.
01284   llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
01285 
01286   /// MetaClassReferences - uniqued meta class references.
01287   llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
01288 
01289   /// EHTypeReferences - uniqued class ehtype references.
01290   llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
01291 
01292   /// VTableDispatchMethods - List of methods for which we generate
01293   /// vtable-based message dispatch.
01294   llvm::DenseSet<Selector> VTableDispatchMethods;
01295 
01296   /// DefinedMetaClasses - List of defined meta-classes.
01297   std::vector<llvm::GlobalValue*> DefinedMetaClasses;
01298   
01299   /// isVTableDispatchedSelector - Returns true if SEL is a
01300   /// vtable-based selector.
01301   bool isVTableDispatchedSelector(Selector Sel);
01302 
01303   /// FinishNonFragileABIModule - Write out global data structures at the end of
01304   /// processing a translation unit.
01305   void FinishNonFragileABIModule();
01306 
01307   /// AddModuleClassList - Add the given list of class pointers to the
01308   /// module with the provided symbol and section names.
01309   void AddModuleClassList(ArrayRef<llvm::GlobalValue*> Container,
01310                           const char *SymbolName,
01311                           const char *SectionName);
01312 
01313   llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
01314                                               unsigned InstanceStart,
01315                                               unsigned InstanceSize,
01316                                               const ObjCImplementationDecl *ID);
01317   llvm::GlobalVariable * BuildClassMetaData(std::string &ClassName,
01318                                             llvm::Constant *IsAGV,
01319                                             llvm::Constant *SuperClassGV,
01320                                             llvm::Constant *ClassRoGV,
01321                                             bool HiddenVisibility,
01322                                             bool Weak);
01323 
01324   llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
01325 
01326   llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
01327 
01328   /// EmitMethodList - Emit the method list for the given
01329   /// implementation. The return value has type MethodListnfABITy.
01330   llvm::Constant *EmitMethodList(Twine Name,
01331                                  const char *Section,
01332                                  ArrayRef<llvm::Constant*> Methods);
01333   /// EmitIvarList - Emit the ivar list for the given
01334   /// implementation. If ForClass is true the list of class ivars
01335   /// (i.e. metaclass ivars) is emitted, otherwise the list of
01336   /// interface ivars will be emitted. The return value has type
01337   /// IvarListnfABIPtrTy.
01338   llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
01339 
01340   llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
01341                                     const ObjCIvarDecl *Ivar,
01342                                     unsigned long int offset);
01343 
01344   /// GetOrEmitProtocol - Get the protocol object for the given
01345   /// declaration, emitting it if necessary. The return value has type
01346   /// ProtocolPtrTy.
01347   llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override;
01348 
01349   /// GetOrEmitProtocolRef - Get a forward reference to the protocol
01350   /// object for the given declaration, emitting it if needed. These
01351   /// forward references will be filled in with empty bodies if no
01352   /// definition is seen. The return value has type ProtocolPtrTy.
01353   llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) override;
01354 
01355   /// EmitProtocolList - Generate the list of referenced
01356   /// protocols. The return value has type ProtocolListPtrTy.
01357   llvm::Constant *EmitProtocolList(Twine Name,
01358                                    ObjCProtocolDecl::protocol_iterator begin,
01359                                    ObjCProtocolDecl::protocol_iterator end);
01360 
01361   CodeGen::RValue EmitVTableMessageSend(CodeGen::CodeGenFunction &CGF,
01362                                         ReturnValueSlot Return,
01363                                         QualType ResultType,
01364                                         Selector Sel,
01365                                         llvm::Value *Receiver,
01366                                         QualType Arg0Ty,
01367                                         bool IsSuper,
01368                                         const CallArgList &CallArgs,
01369                                         const ObjCMethodDecl *Method);
01370   
01371   /// GetClassGlobal - Return the global variable for the Objective-C
01372   /// class of the given name.
01373   llvm::GlobalVariable *GetClassGlobal(const std::string &Name,
01374                                        bool Weak = false) override;
01375 
01376   /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
01377   /// for the given class reference.
01378   llvm::Value *EmitClassRef(CodeGenFunction &CGF,
01379                             const ObjCInterfaceDecl *ID);
01380   
01381   llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF,
01382                                   IdentifierInfo *II, bool Weak);
01383 
01384   llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
01385 
01386   /// EmitSuperClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
01387   /// for the given super class reference.
01388   llvm::Value *EmitSuperClassRef(CodeGenFunction &CGF,
01389                                  const ObjCInterfaceDecl *ID);
01390 
01391   /// EmitMetaClassRef - Return a Value * of the address of _class_t
01392   /// meta-data
01393   llvm::Value *EmitMetaClassRef(CodeGenFunction &CGF,
01394                                 const ObjCInterfaceDecl *ID);
01395 
01396   /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
01397   /// the given ivar.
01398   ///
01399   llvm::GlobalVariable * ObjCIvarOffsetVariable(
01400     const ObjCInterfaceDecl *ID,
01401     const ObjCIvarDecl *Ivar);
01402 
01403   /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
01404   /// for the given selector.
01405   llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel, 
01406                             bool lval=false);
01407 
01408   /// GetInterfaceEHType - Get the cached ehtype for the given Objective-C
01409   /// interface. The return value has type EHTypePtrTy.
01410   llvm::Constant *GetInterfaceEHType(const ObjCInterfaceDecl *ID,
01411                                   bool ForDefinition);
01412 
01413   const char *getMetaclassSymbolPrefix() const {
01414     return "OBJC_METACLASS_$_";
01415   }
01416 
01417   const char *getClassSymbolPrefix() const {
01418     return "OBJC_CLASS_$_";
01419   }
01420 
01421   void GetClassSizeInfo(const ObjCImplementationDecl *OID,
01422                         uint32_t &InstanceStart,
01423                         uint32_t &InstanceSize);
01424 
01425   // Shamelessly stolen from Analysis/CFRefCount.cpp
01426   Selector GetNullarySelector(const char* name) const {
01427     IdentifierInfo* II = &CGM.getContext().Idents.get(name);
01428     return CGM.getContext().Selectors.getSelector(0, &II);
01429   }
01430 
01431   Selector GetUnarySelector(const char* name) const {
01432     IdentifierInfo* II = &CGM.getContext().Idents.get(name);
01433     return CGM.getContext().Selectors.getSelector(1, &II);
01434   }
01435 
01436   /// ImplementationIsNonLazy - Check whether the given category or
01437   /// class implementation is "non-lazy".
01438   bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const;
01439 
01440   bool IsIvarOffsetKnownIdempotent(const CodeGen::CodeGenFunction &CGF,
01441                                    const ObjCIvarDecl *IV) {
01442     // Annotate the load as an invariant load iff inside an instance method
01443     // and ivar belongs to instance method's class and one of its super class.
01444     // This check is needed because the ivar offset is a lazily
01445     // initialised value that may depend on objc_msgSend to perform a fixup on
01446     // the first message dispatch.
01447     //
01448     // An additional opportunity to mark the load as invariant arises when the
01449     // base of the ivar access is a parameter to an Objective C method.
01450     // However, because the parameters are not available in the current
01451     // interface, we cannot perform this check.
01452     if (const ObjCMethodDecl *MD =
01453           dyn_cast_or_null<ObjCMethodDecl>(CGF.CurFuncDecl))
01454       if (MD->isInstanceMethod())
01455         if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
01456           return IV->getContainingInterface()->isSuperClassOf(ID);
01457     return false;
01458   }
01459 
01460 public:
01461   CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm);
01462   // FIXME. All stubs for now!
01463   llvm::Function *ModuleInitFunction() override;
01464 
01465   CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
01466                                       ReturnValueSlot Return,
01467                                       QualType ResultType, Selector Sel,
01468                                       llvm::Value *Receiver,
01469                                       const CallArgList &CallArgs,
01470                                       const ObjCInterfaceDecl *Class,
01471                                       const ObjCMethodDecl *Method) override;
01472 
01473   CodeGen::RValue
01474   GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
01475                            ReturnValueSlot Return, QualType ResultType,
01476                            Selector Sel, const ObjCInterfaceDecl *Class,
01477                            bool isCategoryImpl, llvm::Value *Receiver,
01478                            bool IsClassMessage, const CallArgList &CallArgs,
01479                            const ObjCMethodDecl *Method) override;
01480 
01481   llvm::Value *GetClass(CodeGenFunction &CGF,
01482                         const ObjCInterfaceDecl *ID) override;
01483 
01484   llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
01485                            bool lvalue = false) override
01486     { return EmitSelector(CGF, Sel, lvalue); }
01487 
01488   /// The NeXT/Apple runtimes do not support typed selectors; just emit an
01489   /// untyped one.
01490   llvm::Value *GetSelector(CodeGenFunction &CGF,
01491                            const ObjCMethodDecl *Method) override
01492     { return EmitSelector(CGF, Method->getSelector()); }
01493 
01494   void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
01495 
01496   void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
01497 
01498   void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override {}
01499 
01500   llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
01501                                    const ObjCProtocolDecl *PD) override;
01502 
01503   llvm::Constant *GetEHType(QualType T) override;
01504 
01505   llvm::Constant *GetPropertyGetFunction() override {
01506     return ObjCTypes.getGetPropertyFn();
01507   }
01508   llvm::Constant *GetPropertySetFunction() override {
01509     return ObjCTypes.getSetPropertyFn();
01510   }
01511 
01512   llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
01513                                                   bool copy) override {
01514     return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy);
01515   }
01516 
01517   llvm::Constant *GetSetStructFunction() override {
01518     return ObjCTypes.getCopyStructFn();
01519   }
01520   llvm::Constant *GetGetStructFunction() override {
01521     return ObjCTypes.getCopyStructFn();
01522   }
01523   llvm::Constant *GetCppAtomicObjectSetFunction() override {
01524     return ObjCTypes.getCppAtomicObjectFunction();
01525   }
01526   llvm::Constant *GetCppAtomicObjectGetFunction() override {
01527     return ObjCTypes.getCppAtomicObjectFunction();
01528   }
01529 
01530   llvm::Constant *EnumerationMutationFunction() override {
01531     return ObjCTypes.getEnumerationMutationFn();
01532   }
01533 
01534   void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
01535                    const ObjCAtTryStmt &S) override;
01536   void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
01537                             const ObjCAtSynchronizedStmt &S) override;
01538   void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S,
01539                      bool ClearInsertionPoint=true) override;
01540   llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
01541                                  llvm::Value *AddrWeakObj) override;
01542   void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
01543                           llvm::Value *src, llvm::Value *dst) override;
01544   void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
01545                             llvm::Value *src, llvm::Value *dest,
01546                             bool threadlocal = false) override;
01547   void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
01548                           llvm::Value *src, llvm::Value *dest,
01549                           llvm::Value *ivarOffset) override;
01550   void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
01551                                 llvm::Value *src, llvm::Value *dest) override;
01552   void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
01553                                 llvm::Value *dest, llvm::Value *src,
01554                                 llvm::Value *size) override;
01555   LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy,
01556                               llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
01557                               unsigned CVRQualifiers) override;
01558   llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
01559                               const ObjCInterfaceDecl *Interface,
01560                               const ObjCIvarDecl *Ivar) override;
01561 };
01562 
01563 /// A helper class for performing the null-initialization of a return
01564 /// value.
01565 struct NullReturnState {
01566   llvm::BasicBlock *NullBB;
01567   NullReturnState() : NullBB(0) {}
01568 
01569   /// Perform a null-check of the given receiver.
01570   void init(CodeGenFunction &CGF, llvm::Value *receiver) {
01571     // Make blocks for the null-receiver and call edges.
01572     NullBB = CGF.createBasicBlock("msgSend.null-receiver");
01573     llvm::BasicBlock *callBB = CGF.createBasicBlock("msgSend.call");
01574 
01575     // Check for a null receiver and, if there is one, jump to the
01576     // null-receiver block.  There's no point in trying to avoid it:
01577     // we're always going to put *something* there, because otherwise
01578     // we shouldn't have done this null-check in the first place.
01579     llvm::Value *isNull = CGF.Builder.CreateIsNull(receiver);
01580     CGF.Builder.CreateCondBr(isNull, NullBB, callBB);
01581 
01582     // Otherwise, start performing the call.
01583     CGF.EmitBlock(callBB);
01584   }
01585 
01586   /// Complete the null-return operation.  It is valid to call this
01587   /// regardless of whether 'init' has been called.
01588   RValue complete(CodeGenFunction &CGF, RValue result, QualType resultType,
01589                   const CallArgList &CallArgs,
01590                   const ObjCMethodDecl *Method) {
01591     // If we never had to do a null-check, just use the raw result.
01592     if (!NullBB) return result;
01593 
01594     // The continuation block.  This will be left null if we don't have an
01595     // IP, which can happen if the method we're calling is marked noreturn.
01596     llvm::BasicBlock *contBB = 0;
01597     
01598     // Finish the call path.
01599     llvm::BasicBlock *callBB = CGF.Builder.GetInsertBlock();
01600     if (callBB) {
01601       contBB = CGF.createBasicBlock("msgSend.cont");
01602       CGF.Builder.CreateBr(contBB);
01603     }
01604 
01605     // Okay, start emitting the null-receiver block.
01606     CGF.EmitBlock(NullBB);
01607     
01608     // Release any consumed arguments we've got.
01609     if (Method) {
01610       CallArgList::const_iterator I = CallArgs.begin();
01611       for (ObjCMethodDecl::param_const_iterator i = Method->param_begin(),
01612            e = Method->param_end(); i != e; ++i, ++I) {
01613         const ParmVarDecl *ParamDecl = (*i);
01614         if (ParamDecl->hasAttr<NSConsumedAttr>()) {
01615           RValue RV = I->RV;
01616           assert(RV.isScalar() && 
01617                  "NullReturnState::complete - arg not on object");
01618           CGF.EmitARCRelease(RV.getScalarVal(), ARCImpreciseLifetime);
01619         }
01620       }
01621     }
01622 
01623     // The phi code below assumes that we haven't needed any control flow yet.
01624     assert(CGF.Builder.GetInsertBlock() == NullBB);
01625 
01626     // If we've got a void return, just jump to the continuation block.
01627     if (result.isScalar() && resultType->isVoidType()) {
01628       // No jumps required if the message-send was noreturn.
01629       if (contBB) CGF.EmitBlock(contBB);
01630       return result;
01631     }
01632 
01633     // If we've got a scalar return, build a phi.
01634     if (result.isScalar()) {
01635       // Derive the null-initialization value.
01636       llvm::Constant *null = CGF.CGM.EmitNullConstant(resultType);
01637 
01638       // If no join is necessary, just flow out.
01639       if (!contBB) return RValue::get(null);
01640 
01641       // Otherwise, build a phi.
01642       CGF.EmitBlock(contBB);
01643       llvm::PHINode *phi = CGF.Builder.CreatePHI(null->getType(), 2);
01644       phi->addIncoming(result.getScalarVal(), callBB);
01645       phi->addIncoming(null, NullBB);
01646       return RValue::get(phi);
01647     }
01648 
01649     // If we've got an aggregate return, null the buffer out.
01650     // FIXME: maybe we should be doing things differently for all the
01651     // cases where the ABI has us returning (1) non-agg values in
01652     // memory or (2) agg values in registers.
01653     if (result.isAggregate()) {
01654       assert(result.isAggregate() && "null init of non-aggregate result?");
01655       CGF.EmitNullInitialization(result.getAggregateAddr(), resultType);
01656       if (contBB) CGF.EmitBlock(contBB);
01657       return result;
01658     }
01659 
01660     // Complex types.
01661     CGF.EmitBlock(contBB);
01662     CodeGenFunction::ComplexPairTy callResult = result.getComplexVal();
01663 
01664     // Find the scalar type and its zero value.
01665     llvm::Type *scalarTy = callResult.first->getType();
01666     llvm::Constant *scalarZero = llvm::Constant::getNullValue(scalarTy);
01667 
01668     // Build phis for both coordinates.
01669     llvm::PHINode *real = CGF.Builder.CreatePHI(scalarTy, 2);
01670     real->addIncoming(callResult.first, callBB);
01671     real->addIncoming(scalarZero, NullBB);
01672     llvm::PHINode *imag = CGF.Builder.CreatePHI(scalarTy, 2);
01673     imag->addIncoming(callResult.second, callBB);
01674     imag->addIncoming(scalarZero, NullBB);
01675     return RValue::getComplex(real, imag);
01676   }
01677 };
01678 
01679 } // end anonymous namespace
01680 
01681 /* *** Helper Functions *** */
01682 
01683 /// getConstantGEP() - Help routine to construct simple GEPs.
01684 static llvm::Constant *getConstantGEP(llvm::LLVMContext &VMContext,
01685                                       llvm::Constant *C,
01686                                       unsigned idx0,
01687                                       unsigned idx1) {
01688   llvm::Value *Idxs[] = {
01689     llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx0),
01690     llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), idx1)
01691   };
01692   return llvm::ConstantExpr::getGetElementPtr(C, Idxs);
01693 }
01694 
01695 /// hasObjCExceptionAttribute - Return true if this class or any super
01696 /// class has the __objc_exception__ attribute.
01697 static bool hasObjCExceptionAttribute(ASTContext &Context,
01698                                       const ObjCInterfaceDecl *OID) {
01699   if (OID->hasAttr<ObjCExceptionAttr>())
01700     return true;
01701   if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
01702     return hasObjCExceptionAttribute(Context, Super);
01703   return false;
01704 }
01705 
01706 /* *** CGObjCMac Public Interface *** */
01707 
01708 CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm) : CGObjCCommonMac(cgm),
01709                                                     ObjCTypes(cgm) {
01710   ObjCABI = 1;
01711   EmitImageInfo();
01712 }
01713 
01714 /// GetClass - Return a reference to the class for the given interface
01715 /// decl.
01716 llvm::Value *CGObjCMac::GetClass(CodeGenFunction &CGF,
01717                                  const ObjCInterfaceDecl *ID) {
01718   return EmitClassRef(CGF, ID);
01719 }
01720 
01721 /// GetSelector - Return the pointer to the unique'd string for this selector.
01722 llvm::Value *CGObjCMac::GetSelector(CodeGenFunction &CGF, Selector Sel, 
01723                                     bool lval) {
01724   return EmitSelector(CGF, Sel, lval);
01725 }
01726 llvm::Value *CGObjCMac::GetSelector(CodeGenFunction &CGF, const ObjCMethodDecl
01727                                     *Method) {
01728   return EmitSelector(CGF, Method->getSelector());
01729 }
01730 
01731 llvm::Constant *CGObjCMac::GetEHType(QualType T) {
01732   if (T->isObjCIdType() ||
01733       T->isObjCQualifiedIdType()) {
01734     return CGM.GetAddrOfRTTIDescriptor(
01735               CGM.getContext().getObjCIdRedefinitionType(), /*ForEH=*/true);
01736   }
01737   if (T->isObjCClassType() ||
01738       T->isObjCQualifiedClassType()) {
01739     return CGM.GetAddrOfRTTIDescriptor(
01740              CGM.getContext().getObjCClassRedefinitionType(), /*ForEH=*/true);
01741   }
01742   if (T->isObjCObjectPointerType())
01743     return CGM.GetAddrOfRTTIDescriptor(T,  /*ForEH=*/true);
01744   
01745   llvm_unreachable("asking for catch type for ObjC type in fragile runtime");
01746 }
01747 
01748 /// Generate a constant CFString object.
01749 /*
01750   struct __builtin_CFString {
01751   const int *isa; // point to __CFConstantStringClassReference
01752   int flags;
01753   const char *str;
01754   long length;
01755   };
01756 */
01757 
01758 /// or Generate a constant NSString object.
01759 /*
01760    struct __builtin_NSString {
01761      const int *isa; // point to __NSConstantStringClassReference
01762      const char *str;
01763      unsigned int length;
01764    };
01765 */
01766 
01767 llvm::Constant *CGObjCCommonMac::GenerateConstantString(
01768   const StringLiteral *SL) {
01769   return (CGM.getLangOpts().NoConstantCFStrings == 0 ? 
01770           CGM.GetAddrOfConstantCFString(SL) :
01771           CGM.GetAddrOfConstantString(SL));
01772 }
01773 
01774 enum {
01775   kCFTaggedObjectID_Integer = (1 << 1) + 1
01776 };
01777 
01778 /// Generates a message send where the super is the receiver.  This is
01779 /// a message send to self with special delivery semantics indicating
01780 /// which class's method should be called.
01781 CodeGen::RValue
01782 CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
01783                                     ReturnValueSlot Return,
01784                                     QualType ResultType,
01785                                     Selector Sel,
01786                                     const ObjCInterfaceDecl *Class,
01787                                     bool isCategoryImpl,
01788                                     llvm::Value *Receiver,
01789                                     bool IsClassMessage,
01790                                     const CodeGen::CallArgList &CallArgs,
01791                                     const ObjCMethodDecl *Method) {
01792   // Create and init a super structure; this is a (receiver, class)
01793   // pair we will pass to objc_msgSendSuper.
01794   llvm::Value *ObjCSuper =
01795     CGF.CreateTempAlloca(ObjCTypes.SuperTy, "objc_super");
01796   llvm::Value *ReceiverAsObject =
01797     CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
01798   CGF.Builder.CreateStore(ReceiverAsObject,
01799                           CGF.Builder.CreateStructGEP(ObjCSuper, 0));
01800 
01801   // If this is a class message the metaclass is passed as the target.
01802   llvm::Value *Target;
01803   if (IsClassMessage) {
01804     if (isCategoryImpl) {
01805       // Message sent to 'super' in a class method defined in a category
01806       // implementation requires an odd treatment.
01807       // If we are in a class method, we must retrieve the
01808       // _metaclass_ for the current class, pointed at by
01809       // the class's "isa" pointer.  The following assumes that
01810       // isa" is the first ivar in a class (which it must be).
01811       Target = EmitClassRef(CGF, Class->getSuperClass());
01812       Target = CGF.Builder.CreateStructGEP(Target, 0);
01813       Target = CGF.Builder.CreateLoad(Target);
01814     } else {
01815       llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
01816       llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
01817       llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
01818       Target = Super;
01819     }
01820   } 
01821   else if (isCategoryImpl)
01822     Target = EmitClassRef(CGF, Class->getSuperClass());
01823   else {
01824     llvm::Value *ClassPtr = EmitSuperClassRef(Class);
01825     ClassPtr = CGF.Builder.CreateStructGEP(ClassPtr, 1);
01826     Target = CGF.Builder.CreateLoad(ClassPtr);
01827   }
01828   // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
01829   // ObjCTypes types.
01830   llvm::Type *ClassTy =
01831     CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
01832   Target = CGF.Builder.CreateBitCast(Target, ClassTy);
01833   CGF.Builder.CreateStore(Target,
01834                           CGF.Builder.CreateStructGEP(ObjCSuper, 1));
01835   return EmitMessageSend(CGF, Return, ResultType,
01836                          EmitSelector(CGF, Sel),
01837                          ObjCSuper, ObjCTypes.SuperPtrCTy,
01838                          true, CallArgs, Method, ObjCTypes);
01839 }
01840 
01841 /// Generate code for a message send expression.
01842 CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
01843                                                ReturnValueSlot Return,
01844                                                QualType ResultType,
01845                                                Selector Sel,
01846                                                llvm::Value *Receiver,
01847                                                const CallArgList &CallArgs,
01848                                                const ObjCInterfaceDecl *Class,
01849                                                const ObjCMethodDecl *Method) {
01850   return EmitMessageSend(CGF, Return, ResultType,
01851                          EmitSelector(CGF, Sel),
01852                          Receiver, CGF.getContext().getObjCIdType(),
01853                          false, CallArgs, Method, ObjCTypes);
01854 }
01855 
01856 CodeGen::RValue
01857 CGObjCCommonMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
01858                                  ReturnValueSlot Return,
01859                                  QualType ResultType,
01860                                  llvm::Value *Sel,
01861                                  llvm::Value *Arg0,
01862                                  QualType Arg0Ty,
01863                                  bool IsSuper,
01864                                  const CallArgList &CallArgs,
01865                                  const ObjCMethodDecl *Method,
01866                                  const ObjCCommonTypesHelper &ObjCTypes) {
01867   CallArgList ActualArgs;
01868   if (!IsSuper)
01869     Arg0 = CGF.Builder.CreateBitCast(Arg0, ObjCTypes.ObjectPtrTy);
01870   ActualArgs.add(RValue::get(Arg0), Arg0Ty);
01871   ActualArgs.add(RValue::get(Sel), CGF.getContext().getObjCSelType());
01872   ActualArgs.addFrom(CallArgs);
01873 
01874   // If we're calling a method, use the formal signature.
01875   MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
01876 
01877   if (Method)
01878     assert(CGM.getContext().getCanonicalType(Method->getReturnType()) ==
01879                CGM.getContext().getCanonicalType(ResultType) &&
01880            "Result type mismatch!");
01881 
01882   NullReturnState nullReturn;
01883 
01884   llvm::Constant *Fn = NULL;
01885   if (CGM.ReturnSlotInterferesWithArgs(MSI.CallInfo)) {
01886     if (!IsSuper) nullReturn.init(CGF, Arg0);
01887     Fn = (ObjCABI == 2) ?  ObjCTypes.getSendStretFn2(IsSuper)
01888       : ObjCTypes.getSendStretFn(IsSuper);
01889   } else if (CGM.ReturnTypeUsesFPRet(ResultType)) {
01890     Fn = (ObjCABI == 2) ? ObjCTypes.getSendFpretFn2(IsSuper)
01891       : ObjCTypes.getSendFpretFn(IsSuper);
01892   } else if (CGM.ReturnTypeUsesFP2Ret(ResultType)) {
01893     Fn = (ObjCABI == 2) ? ObjCTypes.getSendFp2RetFn2(IsSuper)
01894       : ObjCTypes.getSendFp2retFn(IsSuper);
01895   } else {
01896     // arm64 uses objc_msgSend for stret methods and yet null receiver check
01897     // must be made for it.
01898     if (!IsSuper && CGM.ReturnTypeUsesSRet(MSI.CallInfo))
01899       nullReturn.init(CGF, Arg0);
01900     Fn = (ObjCABI == 2) ? ObjCTypes.getSendFn2(IsSuper)
01901       : ObjCTypes.getSendFn(IsSuper);
01902   }
01903   
01904   bool requiresnullCheck = false;
01905   if (CGM.getLangOpts().ObjCAutoRefCount && Method)
01906     for (const auto *ParamDecl : Method->params()) {
01907       if (ParamDecl->hasAttr<NSConsumedAttr>()) {
01908         if (!nullReturn.NullBB)
01909           nullReturn.init(CGF, Arg0);
01910         requiresnullCheck = true;
01911         break;
01912       }
01913     }
01914   
01915   Fn = llvm::ConstantExpr::getBitCast(Fn, MSI.MessengerType);
01916   RValue rvalue = CGF.EmitCall(MSI.CallInfo, Fn, Return, ActualArgs);
01917   return nullReturn.complete(CGF, rvalue, ResultType, CallArgs,
01918                              requiresnullCheck ? Method : 0);
01919 }
01920 
01921 static Qualifiers::GC GetGCAttrTypeForType(ASTContext &Ctx, QualType FQT) {
01922   if (FQT.isObjCGCStrong())
01923     return Qualifiers::Strong;
01924   
01925   if (FQT.isObjCGCWeak() || FQT.getObjCLifetime() == Qualifiers::OCL_Weak)
01926     return Qualifiers::Weak;
01927   
01928   // check for __unsafe_unretained
01929   if (FQT.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
01930     return Qualifiers::GCNone;
01931   
01932   if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType())
01933     return Qualifiers::Strong;
01934   
01935   if (const PointerType *PT = FQT->getAs<PointerType>())
01936     return GetGCAttrTypeForType(Ctx, PT->getPointeeType());
01937   
01938   return Qualifiers::GCNone;
01939 }
01940 
01941 llvm::Constant *CGObjCCommonMac::BuildGCBlockLayout(CodeGenModule &CGM,
01942                                                 const CGBlockInfo &blockInfo) {
01943   
01944   llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
01945   if (CGM.getLangOpts().getGC() == LangOptions::NonGC &&
01946       !CGM.getLangOpts().ObjCAutoRefCount)
01947     return nullPtr;
01948 
01949   bool hasUnion = false;
01950   SkipIvars.clear();
01951   IvarsInfo.clear();
01952   unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
01953   unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
01954   
01955   // __isa is the first field in block descriptor and must assume by runtime's
01956   // convention that it is GC'able.
01957   IvarsInfo.push_back(GC_IVAR(0, 1));
01958 
01959   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
01960 
01961   // Calculate the basic layout of the block structure.
01962   const llvm::StructLayout *layout =
01963     CGM.getDataLayout().getStructLayout(blockInfo.StructureType);
01964 
01965   // Ignore the optional 'this' capture: C++ objects are not assumed
01966   // to be GC'ed.
01967 
01968   // Walk the captured variables.
01969   for (const auto &CI : blockDecl->captures()) {
01970     const VarDecl *variable = CI.getVariable();
01971     QualType type = variable->getType();
01972 
01973     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
01974 
01975     // Ignore constant captures.
01976     if (capture.isConstant()) continue;
01977 
01978     uint64_t fieldOffset = layout->getElementOffset(capture.getIndex());
01979 
01980     // __block variables are passed by their descriptor address.
01981     if (CI.isByRef()) {
01982       IvarsInfo.push_back(GC_IVAR(fieldOffset, /*size in words*/ 1));
01983       continue;
01984     }
01985 
01986     assert(!type->isArrayType() && "array variable should not be caught");
01987     if (const RecordType *record = type->getAs<RecordType>()) {
01988       BuildAggrIvarRecordLayout(record, fieldOffset, true, hasUnion);
01989       continue;
01990     }
01991       
01992     Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), type);
01993     unsigned fieldSize = CGM.getContext().getTypeSize(type);
01994 
01995     if (GCAttr == Qualifiers::Strong)
01996       IvarsInfo.push_back(GC_IVAR(fieldOffset,
01997                                   fieldSize / WordSizeInBits));
01998     else if (GCAttr == Qualifiers::GCNone || GCAttr == Qualifiers::Weak)
01999       SkipIvars.push_back(GC_IVAR(fieldOffset,
02000                                   fieldSize / ByteSizeInBits));
02001   }
02002   
02003   if (IvarsInfo.empty())
02004     return nullPtr;
02005 
02006   // Sort on byte position; captures might not be allocated in order,
02007   // and unions can do funny things.
02008   llvm::array_pod_sort(IvarsInfo.begin(), IvarsInfo.end());
02009   llvm::array_pod_sort(SkipIvars.begin(), SkipIvars.end());
02010   
02011   std::string BitMap;
02012   llvm::Constant *C = BuildIvarLayoutBitmap(BitMap);
02013   if (CGM.getLangOpts().ObjCGCBitmapPrint) {
02014     printf("\n block variable layout for block: ");
02015     const unsigned char *s = (const unsigned char*)BitMap.c_str();
02016     for (unsigned i = 0, e = BitMap.size(); i < e; i++)
02017       if (!(s[i] & 0xf0))
02018         printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
02019       else
02020         printf("0x%x%s",  s[i], s[i] != 0 ? ", " : "");
02021     printf("\n");
02022   }
02023   
02024   return C;
02025 }
02026 
02027 /// getBlockCaptureLifetime - This routine returns life time of the captured
02028 /// block variable for the purpose of block layout meta-data generation. FQT is
02029 /// the type of the variable captured in the block.
02030 Qualifiers::ObjCLifetime CGObjCCommonMac::getBlockCaptureLifetime(QualType FQT,
02031                                                                   bool ByrefLayout) {
02032   if (CGM.getLangOpts().ObjCAutoRefCount)
02033     return FQT.getObjCLifetime();
02034   
02035   // MRR.
02036   if (FQT->isObjCObjectPointerType() || FQT->isBlockPointerType())
02037     return ByrefLayout ? Qualifiers::OCL_ExplicitNone : Qualifiers::OCL_Strong;
02038   
02039   return Qualifiers::OCL_None;
02040 }
02041 
02042 void CGObjCCommonMac::UpdateRunSkipBlockVars(bool IsByref,
02043                                              Qualifiers::ObjCLifetime LifeTime,
02044                                              CharUnits FieldOffset,
02045                                              CharUnits FieldSize) {
02046   // __block variables are passed by their descriptor address.
02047   if (IsByref)
02048     RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_BYREF, FieldOffset,
02049                                         FieldSize));
02050   else if (LifeTime == Qualifiers::OCL_Strong)
02051     RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_STRONG, FieldOffset,
02052                                         FieldSize));
02053   else if (LifeTime == Qualifiers::OCL_Weak)
02054     RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_WEAK, FieldOffset,
02055                                         FieldSize));
02056   else if (LifeTime == Qualifiers::OCL_ExplicitNone)
02057     RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_UNRETAINED, FieldOffset,
02058                                         FieldSize));
02059   else
02060     RunSkipBlockVars.push_back(RUN_SKIP(BLOCK_LAYOUT_NON_OBJECT_BYTES,
02061                                         FieldOffset,
02062                                         FieldSize));
02063 }
02064 
02065 void CGObjCCommonMac::BuildRCRecordLayout(const llvm::StructLayout *RecLayout,
02066                                           const RecordDecl *RD,
02067                                           ArrayRef<const FieldDecl*> RecFields,
02068                                           CharUnits BytePos, bool &HasUnion,
02069                                           bool ByrefLayout) {
02070   bool IsUnion = (RD && RD->isUnion());
02071   CharUnits MaxUnionSize = CharUnits::Zero();
02072   const FieldDecl *MaxField = 0;
02073   const FieldDecl *LastFieldBitfieldOrUnnamed = 0;
02074   CharUnits MaxFieldOffset = CharUnits::Zero();
02075   CharUnits LastBitfieldOrUnnamedOffset = CharUnits::Zero();
02076   
02077   if (RecFields.empty())
02078     return;
02079   unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
02080   
02081   for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
02082     const FieldDecl *Field = RecFields[i];
02083     // Note that 'i' here is actually the field index inside RD of Field,
02084     // although this dependency is hidden.
02085     const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
02086     CharUnits FieldOffset =
02087       CGM.getContext().toCharUnitsFromBits(RL.getFieldOffset(i));
02088     
02089     // Skip over unnamed or bitfields
02090     if (!Field->getIdentifier() || Field->isBitField()) {
02091       LastFieldBitfieldOrUnnamed = Field;
02092       LastBitfieldOrUnnamedOffset = FieldOffset;
02093       continue;
02094     }
02095     
02096     LastFieldBitfieldOrUnnamed = 0;
02097     QualType FQT = Field->getType();
02098     if (FQT->isRecordType() || FQT->isUnionType()) {
02099       if (FQT->isUnionType())
02100         HasUnion = true;
02101       
02102       BuildRCBlockVarRecordLayout(FQT->getAs<RecordType>(),
02103                                   BytePos + FieldOffset, HasUnion);
02104       continue;
02105     }
02106     
02107     if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
02108       const ConstantArrayType *CArray =
02109         dyn_cast_or_null<ConstantArrayType>(Array);
02110       uint64_t ElCount = CArray->getSize().getZExtValue();
02111       assert(CArray && "only array with known element size is supported");
02112       FQT = CArray->getElementType();
02113       while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
02114         const ConstantArrayType *CArray =
02115           dyn_cast_or_null<ConstantArrayType>(Array);
02116         ElCount *= CArray->getSize().getZExtValue();
02117         FQT = CArray->getElementType();
02118       }
02119       if (FQT->isRecordType() && ElCount) {
02120         int OldIndex = RunSkipBlockVars.size() - 1;
02121         const RecordType *RT = FQT->getAs<RecordType>();
02122         BuildRCBlockVarRecordLayout(RT, BytePos + FieldOffset,
02123                                     HasUnion);
02124         
02125         // Replicate layout information for each array element. Note that
02126         // one element is already done.
02127         uint64_t ElIx = 1;
02128         for (int FirstIndex = RunSkipBlockVars.size() - 1 ;ElIx < ElCount; ElIx++) {
02129           CharUnits Size = CGM.getContext().getTypeSizeInChars(RT);
02130           for (int i = OldIndex+1; i <= FirstIndex; ++i)
02131             RunSkipBlockVars.push_back(
02132               RUN_SKIP(RunSkipBlockVars[i].opcode,
02133               RunSkipBlockVars[i].block_var_bytepos + Size*ElIx,
02134               RunSkipBlockVars[i].block_var_size));
02135         }
02136         continue;
02137       }
02138     }
02139     CharUnits FieldSize = CGM.getContext().getTypeSizeInChars(Field->getType());
02140     if (IsUnion) {
02141       CharUnits UnionIvarSize = FieldSize;
02142       if (UnionIvarSize > MaxUnionSize) {
02143         MaxUnionSize = UnionIvarSize;
02144         MaxField = Field;
02145         MaxFieldOffset = FieldOffset;
02146       }
02147     } else {
02148       UpdateRunSkipBlockVars(false,
02149                              getBlockCaptureLifetime(FQT, ByrefLayout),
02150                              BytePos + FieldOffset,
02151                              FieldSize);
02152     }
02153   }
02154   
02155   if (LastFieldBitfieldOrUnnamed) {
02156     if (LastFieldBitfieldOrUnnamed->isBitField()) {
02157       // Last field was a bitfield. Must update the info.
02158       uint64_t BitFieldSize
02159         = LastFieldBitfieldOrUnnamed->getBitWidthValue(CGM.getContext());
02160       unsigned UnsSize = (BitFieldSize / ByteSizeInBits) +
02161                         ((BitFieldSize % ByteSizeInBits) != 0);
02162       CharUnits Size = CharUnits::fromQuantity(UnsSize);
02163       Size += LastBitfieldOrUnnamedOffset;
02164       UpdateRunSkipBlockVars(false,
02165                              getBlockCaptureLifetime(LastFieldBitfieldOrUnnamed->getType(),
02166                                                      ByrefLayout),
02167                              BytePos + LastBitfieldOrUnnamedOffset,
02168                              Size);
02169     } else {
02170       assert(!LastFieldBitfieldOrUnnamed->getIdentifier() &&"Expected unnamed");
02171       // Last field was unnamed. Must update skip info.
02172       CharUnits FieldSize
02173         = CGM.getContext().getTypeSizeInChars(LastFieldBitfieldOrUnnamed->getType());
02174       UpdateRunSkipBlockVars(false,
02175                              getBlockCaptureLifetime(LastFieldBitfieldOrUnnamed->getType(),
02176                                                      ByrefLayout),
02177                              BytePos + LastBitfieldOrUnnamedOffset,
02178                              FieldSize);
02179     }
02180   }
02181   
02182   if (MaxField)
02183     UpdateRunSkipBlockVars(false,
02184                            getBlockCaptureLifetime(MaxField->getType(), ByrefLayout),
02185                            BytePos + MaxFieldOffset,
02186                            MaxUnionSize);
02187 }
02188 
02189 void CGObjCCommonMac::BuildRCBlockVarRecordLayout(const RecordType *RT,
02190                                                   CharUnits BytePos,
02191                                                   bool &HasUnion,
02192                                                   bool ByrefLayout) {
02193   const RecordDecl *RD = RT->getDecl();
02194   SmallVector<const FieldDecl*, 16> Fields(RD->fields());
02195   llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
02196   const llvm::StructLayout *RecLayout =
02197     CGM.getDataLayout().getStructLayout(cast<llvm::StructType>(Ty));
02198   
02199   BuildRCRecordLayout(RecLayout, RD, Fields, BytePos, HasUnion, ByrefLayout);
02200 }
02201 
02202 /// InlineLayoutInstruction - This routine produce an inline instruction for the
02203 /// block variable layout if it can. If not, it returns 0. Rules are as follow:
02204 /// If ((uintptr_t) layout) < (1 << 12), the layout is inline. In the 64bit world,
02205 /// an inline layout of value 0x0000000000000xyz is interpreted as follows:
02206 /// x captured object pointers of BLOCK_LAYOUT_STRONG. Followed by
02207 /// y captured object of BLOCK_LAYOUT_BYREF. Followed by
02208 /// z captured object of BLOCK_LAYOUT_WEAK. If any of the above is missing, zero
02209 /// replaces it. For example, 0x00000x00 means x BLOCK_LAYOUT_STRONG and no
02210 /// BLOCK_LAYOUT_BYREF and no BLOCK_LAYOUT_WEAK objects are captured.
02211 uint64_t CGObjCCommonMac::InlineLayoutInstruction(
02212                                     SmallVectorImpl<unsigned char> &Layout) {
02213   uint64_t Result = 0;
02214   if (Layout.size() <= 3) {
02215     unsigned size = Layout.size();
02216     unsigned strong_word_count = 0, byref_word_count=0, weak_word_count=0;
02217     unsigned char inst;
02218     enum BLOCK_LAYOUT_OPCODE opcode ;
02219     switch (size) {
02220       case 3:
02221         inst = Layout[0];
02222         opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
02223         if (opcode == BLOCK_LAYOUT_STRONG)
02224           strong_word_count = (inst & 0xF)+1;
02225         else
02226           return 0;
02227         inst = Layout[1];
02228         opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
02229         if (opcode == BLOCK_LAYOUT_BYREF)
02230           byref_word_count = (inst & 0xF)+1;
02231         else
02232           return 0;
02233         inst = Layout[2];
02234         opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
02235         if (opcode == BLOCK_LAYOUT_WEAK)
02236           weak_word_count = (inst & 0xF)+1;
02237         else
02238           return 0;
02239         break;
02240         
02241       case 2:
02242         inst = Layout[0];
02243         opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
02244         if (opcode == BLOCK_LAYOUT_STRONG) {
02245           strong_word_count = (inst & 0xF)+1;
02246           inst = Layout[1];
02247           opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
02248           if (opcode == BLOCK_LAYOUT_BYREF)
02249             byref_word_count = (inst & 0xF)+1;
02250           else if (opcode == BLOCK_LAYOUT_WEAK)
02251             weak_word_count = (inst & 0xF)+1;
02252           else
02253             return 0;
02254         }
02255         else if (opcode == BLOCK_LAYOUT_BYREF) {
02256           byref_word_count = (inst & 0xF)+1;
02257           inst = Layout[1];
02258           opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
02259           if (opcode == BLOCK_LAYOUT_WEAK)
02260             weak_word_count = (inst & 0xF)+1;
02261           else
02262             return 0;
02263         }
02264         else
02265           return 0;
02266         break;
02267         
02268       case 1:
02269         inst = Layout[0];
02270         opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
02271         if (opcode == BLOCK_LAYOUT_STRONG)
02272           strong_word_count = (inst & 0xF)+1;
02273         else if (opcode == BLOCK_LAYOUT_BYREF)
02274           byref_word_count = (inst & 0xF)+1;
02275         else if (opcode == BLOCK_LAYOUT_WEAK)
02276           weak_word_count = (inst & 0xF)+1;
02277         else
02278           return 0;
02279         break;
02280         
02281       default:
02282         return 0;
02283     }
02284     
02285     // Cannot inline when any of the word counts is 15. Because this is one less
02286     // than the actual work count (so 15 means 16 actual word counts),
02287     // and we can only display 0 thru 15 word counts.
02288     if (strong_word_count == 16 || byref_word_count == 16 || weak_word_count == 16)
02289       return 0;
02290     
02291     unsigned count =
02292       (strong_word_count != 0) + (byref_word_count != 0) + (weak_word_count != 0);
02293     
02294     if (size == count) {
02295       if (strong_word_count)
02296         Result = strong_word_count;
02297       Result <<= 4;
02298       if (byref_word_count)
02299         Result += byref_word_count;
02300       Result <<= 4;
02301       if (weak_word_count)
02302         Result += weak_word_count;
02303     }
02304   }
02305   return Result;
02306 }
02307 
02308 llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) {
02309   llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
02310   if (RunSkipBlockVars.empty())
02311     return nullPtr;
02312   unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
02313   unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
02314   unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits;
02315   
02316   // Sort on byte position; captures might not be allocated in order,
02317   // and unions can do funny things.
02318   llvm::array_pod_sort(RunSkipBlockVars.begin(), RunSkipBlockVars.end());
02319   SmallVector<unsigned char, 16> Layout;
02320   
02321   unsigned size = RunSkipBlockVars.size();
02322   for (unsigned i = 0; i < size; i++) {
02323     enum BLOCK_LAYOUT_OPCODE opcode = RunSkipBlockVars[i].opcode;
02324     CharUnits start_byte_pos = RunSkipBlockVars[i].block_var_bytepos;
02325     CharUnits end_byte_pos = start_byte_pos;
02326     unsigned j = i+1;
02327     while (j < size) {
02328       if (opcode == RunSkipBlockVars[j].opcode) {
02329         end_byte_pos = RunSkipBlockVars[j++].block_var_bytepos;
02330         i++;
02331       }
02332       else
02333         break;
02334     }
02335     CharUnits size_in_bytes =
02336     end_byte_pos - start_byte_pos + RunSkipBlockVars[j-1].block_var_size;
02337     if (j < size) {
02338       CharUnits gap =
02339       RunSkipBlockVars[j].block_var_bytepos -
02340       RunSkipBlockVars[j-1].block_var_bytepos - RunSkipBlockVars[j-1].block_var_size;
02341       size_in_bytes += gap;
02342     }
02343     CharUnits residue_in_bytes = CharUnits::Zero();
02344     if (opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES) {
02345       residue_in_bytes = size_in_bytes % WordSizeInBytes;
02346       size_in_bytes -= residue_in_bytes;
02347       opcode = BLOCK_LAYOUT_NON_OBJECT_WORDS;
02348     }
02349     
02350     unsigned size_in_words = size_in_bytes.getQuantity() / WordSizeInBytes;
02351     while (size_in_words >= 16) {
02352       // Note that value in imm. is one less that the actual
02353       // value. So, 0xf means 16 words follow!
02354       unsigned char inst = (opcode << 4) | 0xf;
02355       Layout.push_back(inst);
02356       size_in_words -= 16;
02357     }
02358     if (size_in_words > 0) {
02359       // Note that value in imm. is one less that the actual
02360       // value. So, we subtract 1 away!
02361       unsigned char inst = (opcode << 4) | (size_in_words-1);
02362       Layout.push_back(inst);
02363     }
02364     if (residue_in_bytes > CharUnits::Zero()) {
02365       unsigned char inst =
02366       (BLOCK_LAYOUT_NON_OBJECT_BYTES << 4) | (residue_in_bytes.getQuantity()-1);
02367       Layout.push_back(inst);
02368     }
02369   }
02370   
02371   int e = Layout.size()-1;
02372   while (e >= 0) {
02373     unsigned char inst = Layout[e--];
02374     enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
02375     if (opcode == BLOCK_LAYOUT_NON_OBJECT_BYTES || opcode == BLOCK_LAYOUT_NON_OBJECT_WORDS)
02376       Layout.pop_back();
02377     else
02378       break;
02379   }
02380   
02381   uint64_t Result = InlineLayoutInstruction(Layout);
02382   if (Result != 0) {
02383     // Block variable layout instruction has been inlined.
02384     if (CGM.getLangOpts().ObjCGCBitmapPrint) {
02385       if (ComputeByrefLayout)
02386         printf("\n Inline instruction for BYREF variable layout: ");
02387       else
02388         printf("\n Inline instruction for block variable layout: ");
02389       printf("0x0%" PRIx64 "\n", Result);
02390     }
02391     if (WordSizeInBytes == 8) {
02392       const llvm::APInt Instruction(64, Result);
02393       return llvm::Constant::getIntegerValue(CGM.Int64Ty, Instruction);
02394     }
02395     else {
02396       const llvm::APInt Instruction(32, Result);
02397       return llvm::Constant::getIntegerValue(CGM.Int32Ty, Instruction);
02398     }
02399   }
02400   
02401   unsigned char inst = (BLOCK_LAYOUT_OPERATOR << 4) | 0;
02402   Layout.push_back(inst);
02403   std::string BitMap;
02404   for (unsigned i = 0, e = Layout.size(); i != e; i++)
02405     BitMap += Layout[i];
02406   
02407   if (CGM.getLangOpts().ObjCGCBitmapPrint) {
02408     if (ComputeByrefLayout)
02409       printf("\n BYREF variable layout: ");
02410     else
02411       printf("\n block variable layout: ");
02412     for (unsigned i = 0, e = BitMap.size(); i != e; i++) {
02413       unsigned char inst = BitMap[i];
02414       enum BLOCK_LAYOUT_OPCODE opcode = (enum BLOCK_LAYOUT_OPCODE) (inst >> 4);
02415       unsigned delta = 1;
02416       switch (opcode) {
02417         case BLOCK_LAYOUT_OPERATOR:
02418           printf("BL_OPERATOR:");
02419           delta = 0;
02420           break;
02421         case BLOCK_LAYOUT_NON_OBJECT_BYTES:
02422           printf("BL_NON_OBJECT_BYTES:");
02423           break;
02424         case BLOCK_LAYOUT_NON_OBJECT_WORDS:
02425           printf("BL_NON_OBJECT_WORD:");
02426           break;
02427         case BLOCK_LAYOUT_STRONG:
02428           printf("BL_STRONG:");
02429           break;
02430         case BLOCK_LAYOUT_BYREF:
02431           printf("BL_BYREF:");
02432           break;
02433         case BLOCK_LAYOUT_WEAK:
02434           printf("BL_WEAK:");
02435           break;
02436         case BLOCK_LAYOUT_UNRETAINED:
02437           printf("BL_UNRETAINED:");
02438           break;
02439       }
02440       // Actual value of word count is one more that what is in the imm.
02441       // field of the instruction
02442       printf("%d", (inst & 0xf) + delta);
02443       if (i < e-1)
02444         printf(", ");
02445       else
02446         printf("\n");
02447     }
02448   }
02449   
02450   llvm::GlobalVariable * Entry =
02451   CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
02452                     llvm::ConstantDataArray::getString(VMContext, BitMap,false),
02453                     "__TEXT,__objc_classname,cstring_literals", 1, true);
02454   return getConstantGEP(VMContext, Entry, 0, 0);
02455 }
02456 
02457 llvm::Constant *CGObjCCommonMac::BuildRCBlockLayout(CodeGenModule &CGM,
02458                                                     const CGBlockInfo &blockInfo) {
02459   assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);
02460   
02461   RunSkipBlockVars.clear();
02462   bool hasUnion = false;
02463   
02464   unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
02465   unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
02466   unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits;
02467   
02468   const BlockDecl *blockDecl = blockInfo.getBlockDecl();
02469   
02470   // Calculate the basic layout of the block structure.
02471   const llvm::StructLayout *layout =
02472   CGM.getDataLayout().getStructLayout(blockInfo.StructureType);
02473   
02474   // Ignore the optional 'this' capture: C++ objects are not assumed
02475   // to be GC'ed.
02476   if (blockInfo.BlockHeaderForcedGapSize != CharUnits::Zero())
02477     UpdateRunSkipBlockVars(false, Qualifiers::OCL_None,
02478                            blockInfo.BlockHeaderForcedGapOffset,
02479                            blockInfo.BlockHeaderForcedGapSize);
02480   // Walk the captured variables.
02481   for (const auto &CI : blockDecl->captures()) {
02482     const VarDecl *variable = CI.getVariable();
02483     QualType type = variable->getType();
02484     
02485     const CGBlockInfo::Capture &capture = blockInfo.getCapture(variable);
02486     
02487     // Ignore constant captures.
02488     if (capture.isConstant()) continue;
02489     
02490     CharUnits fieldOffset =
02491        CharUnits::fromQuantity(layout->getElementOffset(capture.getIndex()));
02492     
02493     assert(!type->isArrayType() && "array variable should not be caught");
02494     if (!CI.isByRef())
02495       if (const RecordType *record = type->getAs<RecordType>()) {
02496         BuildRCBlockVarRecordLayout(record, fieldOffset, hasUnion);
02497         continue;
02498       }
02499     CharUnits fieldSize;
02500     if (CI.isByRef())
02501       fieldSize = CharUnits::fromQuantity(WordSizeInBytes);
02502     else
02503       fieldSize = CGM.getContext().getTypeSizeInChars(type);
02504     UpdateRunSkipBlockVars(CI.isByRef(), getBlockCaptureLifetime(type, false),
02505                            fieldOffset, fieldSize);
02506   }
02507   return getBitmapBlockLayout(false);
02508 }
02509 
02510 
02511 llvm::Constant *CGObjCCommonMac::BuildByrefLayout(CodeGen::CodeGenModule &CGM,
02512                                                   QualType T) {
02513   assert(CGM.getLangOpts().getGC() == LangOptions::NonGC);
02514   assert(!T->isArrayType() && "__block array variable should not be caught");
02515   CharUnits fieldOffset;
02516   RunSkipBlockVars.clear();
02517   bool hasUnion = false;
02518   if (const RecordType *record = T->getAs<RecordType>()) {
02519     BuildRCBlockVarRecordLayout(record, fieldOffset, hasUnion, true /*ByrefLayout */);
02520     llvm::Constant *Result = getBitmapBlockLayout(true);
02521     return Result;
02522   }
02523   llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
02524   return nullPtr;
02525 }
02526 
02527 llvm::Value *CGObjCMac::GenerateProtocolRef(CodeGenFunction &CGF,
02528                                             const ObjCProtocolDecl *PD) {
02529   // FIXME: I don't understand why gcc generates this, or where it is
02530   // resolved. Investigate. Its also wasteful to look this up over and over.
02531   LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
02532 
02533   return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
02534                                         ObjCTypes.getExternalProtocolPtrTy());
02535 }
02536 
02537 void CGObjCCommonMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
02538   // FIXME: We shouldn't need this, the protocol decl should contain enough
02539   // information to tell us whether this was a declaration or a definition.
02540   DefinedProtocols.insert(PD->getIdentifier());
02541 
02542   // If we have generated a forward reference to this protocol, emit
02543   // it now. Otherwise do nothing, the protocol objects are lazily
02544   // emitted.
02545   if (Protocols.count(PD->getIdentifier()))
02546     GetOrEmitProtocol(PD);
02547 }
02548 
02549 llvm::Constant *CGObjCCommonMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
02550   if (DefinedProtocols.count(PD->getIdentifier()))
02551     return GetOrEmitProtocol(PD);
02552   
02553   return GetOrEmitProtocolRef(PD);
02554 }
02555 
02556 static void assertPrivateName(const llvm::GlobalValue *GV) {
02557   StringRef NameRef = GV->getName();
02558   (void)NameRef;
02559   assert(NameRef[0] == '\01' && (NameRef[1] == 'L' || NameRef[1] == 'l'));
02560   assert(GV->getVisibility() == llvm::GlobalValue::DefaultVisibility);
02561   assert(GV->getLinkage() == llvm::GlobalValue::PrivateLinkage);
02562 }
02563 
02564 /*
02565 // Objective-C 1.0 extensions
02566 struct _objc_protocol {
02567 struct _objc_protocol_extension *isa;
02568 char *protocol_name;
02569 struct _objc_protocol_list *protocol_list;
02570 struct _objc__method_prototype_list *instance_methods;
02571 struct _objc__method_prototype_list *class_methods
02572 };
02573 
02574 See EmitProtocolExtension().
02575 */
02576 llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
02577   llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()];
02578 
02579   // Early exit if a defining object has already been generated.
02580   if (Entry && Entry->hasInitializer())
02581     return Entry;
02582 
02583   // Use the protocol definition, if there is one.
02584   if (const ObjCProtocolDecl *Def = PD->getDefinition())
02585     PD = Def;
02586 
02587   // FIXME: I don't understand why gcc generates this, or where it is
02588   // resolved. Investigate. Its also wasteful to look this up over and over.
02589   LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
02590 
02591   // Construct method lists.
02592   std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
02593   std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
02594   std::vector<llvm::Constant*> MethodTypesExt, OptMethodTypesExt;
02595   for (const auto *MD : PD->instance_methods()) {
02596     llvm::Constant *C = GetMethodDescriptionConstant(MD);
02597     if (!C)
02598       return GetOrEmitProtocolRef(PD);
02599     
02600     if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
02601       OptInstanceMethods.push_back(C);
02602       OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
02603     } else {
02604       InstanceMethods.push_back(C);
02605       MethodTypesExt.push_back(GetMethodVarType(MD, true));
02606     }
02607   }
02608 
02609   for (const auto *MD : PD->class_methods()) {
02610     llvm::Constant *C = GetMethodDescriptionConstant(MD);
02611     if (!C)
02612       return GetOrEmitProtocolRef(PD);
02613 
02614     if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
02615       OptClassMethods.push_back(C);
02616       OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
02617     } else {
02618       ClassMethods.push_back(C);
02619       MethodTypesExt.push_back(GetMethodVarType(MD, true));
02620     }
02621   }
02622 
02623   MethodTypesExt.insert(MethodTypesExt.end(),
02624                         OptMethodTypesExt.begin(), OptMethodTypesExt.end());
02625 
02626   llvm::Constant *Values[] = {
02627     EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods, 
02628                           MethodTypesExt),
02629     GetClassName(PD->getIdentifier()),
02630     EmitProtocolList("\01L_OBJC_PROTOCOL_REFS_" + PD->getName(),
02631                      PD->protocol_begin(),
02632                      PD->protocol_end()),
02633     EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_" + PD->getName(),
02634                        "__OBJC,__cat_inst_meth,regular,no_dead_strip",
02635                        InstanceMethods),
02636     EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_" + PD->getName(),
02637                        "__OBJC,__cat_cls_meth,regular,no_dead_strip",
02638                        ClassMethods)
02639   };
02640   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
02641                                                    Values);
02642 
02643   if (Entry) {
02644     // Already created, update the initializer.
02645     assert(Entry->getLinkage() == llvm::GlobalValue::PrivateLinkage);
02646     Entry->setInitializer(Init);
02647   } else {
02648     Entry =
02649       new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy, false,
02650                                llvm::GlobalValue::PrivateLinkage,
02651                                Init,
02652                                "\01L_OBJC_PROTOCOL_" + PD->getName());
02653     Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
02654     // FIXME: Is this necessary? Why only for protocol?
02655     Entry->setAlignment(4);
02656 
02657     Protocols[PD->getIdentifier()] = Entry;
02658   }
02659   assertPrivateName(Entry);
02660   CGM.addCompilerUsedGlobal(Entry);
02661 
02662   return Entry;
02663 }
02664 
02665 llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
02666   llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
02667 
02668   if (!Entry) {
02669     // We use the initializer as a marker of whether this is a forward
02670     // reference or not. At module finalization we add the empty
02671     // contents for protocols which were referenced but never defined.
02672     Entry =
02673       new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolTy, false,
02674                                llvm::GlobalValue::PrivateLinkage,
02675                                0,
02676                                "\01L_OBJC_PROTOCOL_" + PD->getName());
02677     Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
02678     // FIXME: Is this necessary? Why only for protocol?
02679     Entry->setAlignment(4);
02680   }
02681   assertPrivateName(Entry);
02682 
02683   return Entry;
02684 }
02685 
02686 /*
02687   struct _objc_protocol_extension {
02688   uint32_t size;
02689   struct objc_method_description_list *optional_instance_methods;
02690   struct objc_method_description_list *optional_class_methods;
02691   struct objc_property_list *instance_properties;
02692   const char ** extendedMethodTypes;
02693   };
02694 */
02695 llvm::Constant *
02696 CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
02697                                  ArrayRef<llvm::Constant*> OptInstanceMethods,
02698                                  ArrayRef<llvm::Constant*> OptClassMethods,
02699                                  ArrayRef<llvm::Constant*> MethodTypesExt) {
02700   uint64_t Size =
02701     CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolExtensionTy);
02702   llvm::Constant *Values[] = {
02703     llvm::ConstantInt::get(ObjCTypes.IntTy, Size),
02704     EmitMethodDescList("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_"
02705                        + PD->getName(),
02706                        "__OBJC,__cat_inst_meth,regular,no_dead_strip",
02707                        OptInstanceMethods),
02708     EmitMethodDescList("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_" + PD->getName(),
02709                        "__OBJC,__cat_cls_meth,regular,no_dead_strip",
02710                        OptClassMethods),
02711     EmitPropertyList("\01L_OBJC_$_PROP_PROTO_LIST_" + PD->getName(), 0, PD,
02712                      ObjCTypes),
02713     EmitProtocolMethodTypes("\01L_OBJC_PROTOCOL_METHOD_TYPES_" + PD->getName(),
02714                             MethodTypesExt, ObjCTypes)
02715   };
02716 
02717   // Return null if no extension bits are used.
02718   if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
02719       Values[3]->isNullValue() && Values[4]->isNullValue())
02720     return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
02721 
02722   llvm::Constant *Init =
02723     llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
02724 
02725   // No special section, but goes in llvm.used
02726   return CreateMetadataVar("\01l_OBJC_PROTOCOLEXT_" + PD->getName(),
02727                            Init,
02728                            0, 0, true);
02729 }
02730 
02731 /*
02732   struct objc_protocol_list {
02733     struct objc_protocol_list *next;
02734     long count;
02735     Protocol *list[];
02736   };
02737 */
02738 llvm::Constant *
02739 CGObjCMac::EmitProtocolList(Twine Name,
02740                             ObjCProtocolDecl::protocol_iterator begin,
02741                             ObjCProtocolDecl::protocol_iterator end) {
02742   SmallVector<llvm::Constant *, 16> ProtocolRefs;
02743 
02744   for (; begin != end; ++begin)
02745     ProtocolRefs.push_back(GetProtocolRef(*begin));
02746 
02747   // Just return null for empty protocol lists
02748   if (ProtocolRefs.empty())
02749     return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
02750 
02751   // This list is null terminated.
02752   ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
02753 
02754   llvm::Constant *Values[3];
02755   // This field is only used by the runtime.
02756   Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
02757   Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy,
02758                                      ProtocolRefs.size() - 1);
02759   Values[2] =
02760     llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
02761                                                   ProtocolRefs.size()),
02762                              ProtocolRefs);
02763 
02764   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
02765   llvm::GlobalVariable *GV =
02766     CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
02767                       4, false);
02768   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
02769 }
02770 
02771 void CGObjCCommonMac::
02772 PushProtocolProperties(llvm::SmallPtrSet<const IdentifierInfo*,16> &PropertySet,
02773                        SmallVectorImpl<llvm::Constant *> &Properties,
02774                        const Decl *Container,
02775                        const ObjCProtocolDecl *Proto,
02776                        const ObjCCommonTypesHelper &ObjCTypes) {
02777   for (const auto *P : Proto->protocols()) 
02778     PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes);
02779   for (const auto *PD : Proto->properties()) {
02780     if (!PropertySet.insert(PD->getIdentifier()))
02781       continue;
02782     llvm::Constant *Prop[] = {
02783       GetPropertyName(PD->getIdentifier()),
02784       GetPropertyTypeString(PD, Container)
02785     };
02786     Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy, Prop));
02787   }
02788 }
02789 
02790 /*
02791   struct _objc_property {
02792     const char * const name;
02793     const char * const attributes;
02794   };
02795 
02796   struct _objc_property_list {
02797     uint32_t entsize; // sizeof (struct _objc_property)
02798     uint32_t prop_count;
02799     struct _objc_property[prop_count];
02800   };
02801 */
02802 llvm::Constant *CGObjCCommonMac::EmitPropertyList(Twine Name,
02803                                        const Decl *Container,
02804                                        const ObjCContainerDecl *OCD,
02805                                        const ObjCCommonTypesHelper &ObjCTypes) {
02806   SmallVector<llvm::Constant *, 16> Properties;
02807   llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
02808   for (const auto *PD : OCD->properties()) {
02809     PropertySet.insert(PD->getIdentifier());
02810     llvm::Constant *Prop[] = {
02811       GetPropertyName(PD->getIdentifier()),
02812       GetPropertyTypeString(PD, Container)
02813     };
02814     Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
02815                                                    Prop));
02816   }
02817   if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD)) {
02818     for (const auto *P : OID->all_referenced_protocols())
02819       PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes);
02820   }
02821   else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD)) {
02822     for (const auto *P : CD->protocols())
02823       PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes);
02824   }
02825 
02826   // Return null for empty list.
02827   if (Properties.empty())
02828     return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
02829 
02830   unsigned PropertySize =
02831     CGM.getDataLayout().getTypeAllocSize(ObjCTypes.PropertyTy);
02832   llvm::Constant *Values[3];
02833   Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
02834   Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
02835   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
02836                                              Properties.size());
02837   Values[2] = llvm::ConstantArray::get(AT, Properties);
02838   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
02839 
02840   llvm::GlobalVariable *GV =
02841     CreateMetadataVar(Name, Init,
02842                       (ObjCABI == 2) ? "__DATA, __objc_const" :
02843                       "__OBJC,__property,regular,no_dead_strip",
02844                       (ObjCABI == 2) ? 8 : 4,
02845                       true);
02846   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
02847 }
02848 
02849 llvm::Constant *
02850 CGObjCCommonMac::EmitProtocolMethodTypes(Twine Name,
02851                                          ArrayRef<llvm::Constant*> MethodTypes,
02852                                          const ObjCCommonTypesHelper &ObjCTypes) {
02853   // Return null for empty list.
02854   if (MethodTypes.empty())
02855     return llvm::Constant::getNullValue(ObjCTypes.Int8PtrPtrTy);
02856 
02857   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
02858                                              MethodTypes.size());
02859   llvm::Constant *Init = llvm::ConstantArray::get(AT, MethodTypes);
02860 
02861   llvm::GlobalVariable *GV = 
02862     CreateMetadataVar(Name, Init,
02863                       (ObjCABI == 2) ? "__DATA, __objc_const" : 0,
02864                       (ObjCABI == 2) ? 8 : 4,
02865                       true);
02866   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.Int8PtrPtrTy);
02867 }
02868 
02869 /*
02870   struct objc_method_description_list {
02871   int count;
02872   struct objc_method_description list[];
02873   };
02874 */
02875 llvm::Constant *
02876 CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
02877   llvm::Constant *Desc[] = {
02878     llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
02879                                    ObjCTypes.SelectorPtrTy),
02880     GetMethodVarType(MD)
02881   };
02882   if (!Desc[1])
02883     return 0;
02884   
02885   return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
02886                                    Desc);
02887 }
02888 
02889 llvm::Constant *
02890 CGObjCMac::EmitMethodDescList(Twine Name, const char *Section,
02891                               ArrayRef<llvm::Constant*> Methods) {
02892   // Return null for empty list.
02893   if (Methods.empty())
02894     return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
02895 
02896   llvm::Constant *Values[2];
02897   Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
02898   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
02899                                              Methods.size());
02900   Values[1] = llvm::ConstantArray::get(AT, Methods);
02901   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
02902 
02903   llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
02904   return llvm::ConstantExpr::getBitCast(GV,
02905                                         ObjCTypes.MethodDescriptionListPtrTy);
02906 }
02907 
02908 /*
02909   struct _objc_category {
02910   char *category_name;
02911   char *class_name;
02912   struct _objc_method_list *instance_methods;
02913   struct _objc_method_list *class_methods;
02914   struct _objc_protocol_list *protocols;
02915   uint32_t size; // <rdar://4585769>
02916   struct _objc_property_list *instance_properties;
02917   };
02918 */
02919 void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
02920   unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.CategoryTy);
02921 
02922   // FIXME: This is poor design, the OCD should have a pointer to the category
02923   // decl. Additionally, note that Category can be null for the @implementation
02924   // w/o an @interface case. Sema should just create one for us as it does for
02925   // @implementation so everyone else can live life under a clear blue sky.
02926   const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
02927   const ObjCCategoryDecl *Category =
02928     Interface->FindCategoryDeclaration(OCD->getIdentifier());
02929 
02930   SmallString<256> ExtName;
02931   llvm::raw_svector_ostream(ExtName) << Interface->getName() << '_'
02932                                      << OCD->getName();
02933 
02934   SmallVector<llvm::Constant *, 16> InstanceMethods, ClassMethods;
02935   for (const auto *I : OCD->instance_methods())
02936     // Instance methods should always be defined.
02937     InstanceMethods.push_back(GetMethodConstant(I));
02938 
02939   for (const auto *I : OCD->class_methods())
02940     // Class methods should always be defined.
02941     ClassMethods.push_back(GetMethodConstant(I));
02942 
02943   llvm::Constant *Values[7];
02944   Values[0] = GetClassName(OCD->getIdentifier());
02945   Values[1] = GetClassName(Interface->getIdentifier());
02946   LazySymbols.insert(Interface->getIdentifier());
02947   Values[2] =
02948     EmitMethodList("\01L_OBJC_CATEGORY_INSTANCE_METHODS_" + ExtName.str(),
02949                    "__OBJC,__cat_inst_meth,regular,no_dead_strip",
02950                    InstanceMethods);
02951   Values[3] =
02952     EmitMethodList("\01L_OBJC_CATEGORY_CLASS_METHODS_" + ExtName.str(),
02953                    "__OBJC,__cat_cls_meth,regular,no_dead_strip",
02954                    ClassMethods);
02955   if (Category) {
02956     Values[4] =
02957       EmitProtocolList("\01L_OBJC_CATEGORY_PROTOCOLS_" + ExtName.str(),
02958                        Category->protocol_begin(),
02959                        Category->protocol_end());
02960   } else {
02961     Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
02962   }
02963   Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
02964 
02965   // If there is no category @interface then there can be no properties.
02966   if (Category) {
02967     Values[6] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(),
02968                                  OCD, Category, ObjCTypes);
02969   } else {
02970     Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
02971   }
02972 
02973   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
02974                                                    Values);
02975 
02976   llvm::GlobalVariable *GV =
02977     CreateMetadataVar("\01L_OBJC_CATEGORY_" + ExtName.str(), Init,
02978                       "__OBJC,__category,regular,no_dead_strip",
02979                       4, true);
02980   DefinedCategories.push_back(GV);
02981   DefinedCategoryNames.insert(ExtName.str());
02982   // method definition entries must be clear for next implementation.
02983   MethodDefinitions.clear();
02984 }
02985 
02986 enum FragileClassFlags {
02987   FragileABI_Class_Factory                 = 0x00001,
02988   FragileABI_Class_Meta                    = 0x00002,
02989   FragileABI_Class_HasCXXStructors         = 0x02000,
02990   FragileABI_Class_Hidden                  = 0x20000
02991 };
02992 
02993 enum NonFragileClassFlags {
02994   /// Is a meta-class.
02995   NonFragileABI_Class_Meta                 = 0x00001,
02996 
02997   /// Is a root class.
02998   NonFragileABI_Class_Root                 = 0x00002,
02999 
03000   /// Has a C++ constructor and destructor.
03001   NonFragileABI_Class_HasCXXStructors      = 0x00004,
03002 
03003   /// Has hidden visibility.
03004   NonFragileABI_Class_Hidden               = 0x00010,
03005 
03006   /// Has the exception attribute.
03007   NonFragileABI_Class_Exception            = 0x00020,
03008 
03009   /// (Obsolete) ARC-specific: this class has a .release_ivars method
03010   NonFragileABI_Class_HasIvarReleaser      = 0x00040,
03011 
03012   /// Class implementation was compiled under ARC.
03013   NonFragileABI_Class_CompiledByARC        = 0x00080,
03014 
03015   /// Class has non-trivial destructors, but zero-initialization is okay.
03016   NonFragileABI_Class_HasCXXDestructorOnly = 0x00100
03017 };
03018 
03019 /*
03020   struct _objc_class {
03021   Class isa;
03022   Class super_class;
03023   const char *name;
03024   long version;
03025   long info;
03026   long instance_size;
03027   struct _objc_ivar_list *ivars;
03028   struct _objc_method_list *methods;
03029   struct _objc_cache *cache;
03030   struct _objc_protocol_list *protocols;
03031   // Objective-C 1.0 extensions (<rdr://4585769>)
03032   const char *ivar_layout;
03033   struct _objc_class_ext *ext;
03034   };
03035 
03036   See EmitClassExtension();
03037 */
03038 void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
03039   DefinedSymbols.insert(ID->getIdentifier());
03040 
03041   std::string ClassName = ID->getNameAsString();
03042   // FIXME: Gross
03043   ObjCInterfaceDecl *Interface =
03044     const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
03045   llvm::Constant *Protocols =
03046     EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getName(),
03047                      Interface->all_referenced_protocol_begin(),
03048                      Interface->all_referenced_protocol_end());
03049   unsigned Flags = FragileABI_Class_Factory;
03050   if (ID->hasNonZeroConstructors() || ID->hasDestructors())
03051     Flags |= FragileABI_Class_HasCXXStructors;
03052   unsigned Size =
03053     CGM.getContext().getASTObjCImplementationLayout(ID).getSize().getQuantity();
03054 
03055   // FIXME: Set CXX-structors flag.
03056   if (ID->getClassInterface()->getVisibility() == HiddenVisibility)
03057     Flags |= FragileABI_Class_Hidden;
03058 
03059   SmallVector<llvm::Constant *, 16> InstanceMethods, ClassMethods;
03060   for (const auto *I : ID->instance_methods())
03061     // Instance methods should always be defined.
03062     InstanceMethods.push_back(GetMethodConstant(I));
03063 
03064   for (const auto *I : ID->class_methods())
03065     // Class methods should always be defined.
03066     ClassMethods.push_back(GetMethodConstant(I));
03067 
03068   for (const auto *PID : ID->property_impls()) {
03069     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
03070       ObjCPropertyDecl *PD = PID->getPropertyDecl();
03071 
03072       if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
03073         if (llvm::Constant *C = GetMethodConstant(MD))
03074           InstanceMethods.push_back(C);
03075       if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
03076         if (llvm::Constant *C = GetMethodConstant(MD))
03077           InstanceMethods.push_back(C);
03078     }
03079   }
03080 
03081   llvm::Constant *Values[12];
03082   Values[ 0] = EmitMetaClass(ID, Protocols, ClassMethods);
03083   if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
03084     // Record a reference to the super class.
03085     LazySymbols.insert(Super->getIdentifier());
03086 
03087     Values[ 1] =
03088       llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
03089                                      ObjCTypes.ClassPtrTy);
03090   } else {
03091     Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
03092   }
03093   Values[ 2] = GetClassName(ID->getIdentifier());
03094   // Version is always 0.
03095   Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
03096   Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
03097   Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
03098   Values[ 6] = EmitIvarList(ID, false);
03099   Values[ 7] =
03100     EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getName(),
03101                    "__OBJC,__inst_meth,regular,no_dead_strip",
03102                    InstanceMethods);
03103   // cache is always NULL.
03104   Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
03105   Values[ 9] = Protocols;
03106   Values[10] = BuildIvarLayout(ID, true);
03107   Values[11] = EmitClassExtension(ID);
03108   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
03109                                                    Values);
03110   std::string Name("\01L_OBJC_CLASS_");
03111   Name += ClassName;
03112   const char *Section = "__OBJC,__class,regular,no_dead_strip";
03113   // Check for a forward reference.
03114   llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
03115   if (GV) {
03116     assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
03117            "Forward metaclass reference has incorrect type.");
03118     GV->setInitializer(Init);
03119     GV->setSection(Section);
03120     GV->setAlignment(4);
03121     CGM.addCompilerUsedGlobal(GV);
03122   } else
03123     GV = CreateMetadataVar(Name, Init, Section, 4, true);
03124   assertPrivateName(GV);
03125   DefinedClasses.push_back(GV);
03126   ImplementedClasses.push_back(Interface);
03127   // method definition entries must be clear for next implementation.
03128   MethodDefinitions.clear();
03129 }
03130 
03131 llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
03132                                          llvm::Constant *Protocols,
03133                                          ArrayRef<llvm::Constant*> Methods) {
03134   unsigned Flags = FragileABI_Class_Meta;
03135   unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassTy);
03136 
03137   if (ID->getClassInterface()->getVisibility() == HiddenVisibility)
03138     Flags |= FragileABI_Class_Hidden;
03139 
03140   llvm::Constant *Values[12];
03141   // The isa for the metaclass is the root of the hierarchy.
03142   const ObjCInterfaceDecl *Root = ID->getClassInterface();
03143   while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
03144     Root = Super;
03145   Values[ 0] =
03146     llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
03147                                    ObjCTypes.ClassPtrTy);
03148   // The super class for the metaclass is emitted as the name of the
03149   // super class. The runtime fixes this up to point to the
03150   // *metaclass* for the super class.
03151   if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
03152     Values[ 1] =
03153       llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
03154                                      ObjCTypes.ClassPtrTy);
03155   } else {
03156     Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
03157   }
03158   Values[ 2] = GetClassName(ID->getIdentifier());
03159   // Version is always 0.
03160   Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
03161   Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
03162   Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
03163   Values[ 6] = EmitIvarList(ID, true);
03164   Values[ 7] =
03165     EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
03166                    "__OBJC,__cls_meth,regular,no_dead_strip",
03167                    Methods);
03168   // cache is always NULL.
03169   Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
03170   Values[ 9] = Protocols;
03171   // ivar_layout for metaclass is always NULL.
03172   Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
03173   // The class extension is always unused for metaclasses.
03174   Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
03175   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
03176                                                    Values);
03177 
03178   std::string Name("\01L_OBJC_METACLASS_");
03179   Name += ID->getName();
03180 
03181   // Check for a forward reference.
03182   llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
03183   if (GV) {
03184     assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
03185            "Forward metaclass reference has incorrect type.");
03186     GV->setInitializer(Init);
03187   } else {
03188     GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
03189                                   llvm::GlobalValue::PrivateLinkage,
03190                                   Init, Name);
03191   }
03192   assertPrivateName(GV);
03193   GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
03194   GV->setAlignment(4);
03195   CGM.addCompilerUsedGlobal(GV);
03196 
03197   return GV;
03198 }
03199 
03200 llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
03201   std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
03202 
03203   // FIXME: Should we look these up somewhere other than the module. Its a bit
03204   // silly since we only generate these while processing an implementation, so
03205   // exactly one pointer would work if know when we entered/exitted an
03206   // implementation block.
03207 
03208   // Check for an existing forward reference.
03209   // Previously, metaclass with internal linkage may have been defined.
03210   // pass 'true' as 2nd argument so it is returned.
03211   llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
03212   if (!GV)
03213     GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
03214                                   llvm::GlobalValue::PrivateLinkage, 0, Name);
03215 
03216   assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
03217          "Forward metaclass reference has incorrect type.");
03218   assertPrivateName(GV);
03219   return GV;
03220 }
03221 
03222 llvm::Value *CGObjCMac::EmitSuperClassRef(const ObjCInterfaceDecl *ID) {
03223   std::string Name = "\01L_OBJC_CLASS_" + ID->getNameAsString();
03224   llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
03225 
03226   if (!GV)
03227     GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
03228                                   llvm::GlobalValue::PrivateLinkage, 0, Name);
03229 
03230   assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
03231          "Forward class metadata reference has incorrect type.");
03232   assertPrivateName(GV);
03233   return GV;
03234 }
03235 
03236 /*
03237   struct objc_class_ext {
03238   uint32_t size;
03239   const char *weak_ivar_layout;
03240   struct _objc_property_list *properties;
03241   };
03242 */
03243 llvm::Constant *
03244 CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
03245   uint64_t Size =
03246     CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassExtensionTy);
03247 
03248   llvm::Constant *Values[3];
03249   Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
03250   Values[1] = BuildIvarLayout(ID, false);
03251   Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getName(),
03252                                ID, ID->getClassInterface(), ObjCTypes);
03253 
03254   // Return null if no extension bits are used.
03255   if (Values[1]->isNullValue() && Values[2]->isNullValue())
03256     return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
03257 
03258   llvm::Constant *Init =
03259     llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
03260   return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getName(),
03261                            Init, "__OBJC,__class_ext,regular,no_dead_strip",
03262                            4, true);
03263 }
03264 
03265 /*
03266   struct objc_ivar {
03267     char *ivar_name;
03268     char *ivar_type;
03269     int ivar_offset;
03270   };
03271 
03272   struct objc_ivar_list {
03273     int ivar_count;
03274     struct objc_ivar list[count];
03275   };
03276 */
03277 llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
03278                                         bool ForClass) {
03279   std::vector<llvm::Constant*> Ivars;
03280 
03281   // When emitting the root class GCC emits ivar entries for the
03282   // actual class structure. It is not clear if we need to follow this
03283   // behavior; for now lets try and get away with not doing it. If so,
03284   // the cleanest solution would be to make up an ObjCInterfaceDecl
03285   // for the class.
03286   if (ForClass)
03287     return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
03288 
03289   const ObjCInterfaceDecl *OID = ID->getClassInterface();
03290 
03291   for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin(); 
03292        IVD; IVD = IVD->getNextIvar()) {
03293     // Ignore unnamed bit-fields.
03294     if (!IVD->getDeclName())
03295       continue;
03296     llvm::Constant *Ivar[] = {
03297       GetMethodVarName(IVD->getIdentifier()),
03298       GetMethodVarType(IVD),
03299       llvm::ConstantInt::get(ObjCTypes.IntTy,
03300                              ComputeIvarBaseOffset(CGM, OID, IVD))
03301     };
03302     Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
03303   }
03304 
03305   // Return null for empty list.
03306   if (Ivars.empty())
03307     return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
03308 
03309   llvm::Constant *Values[2];
03310   Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
03311   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
03312                                              Ivars.size());
03313   Values[1] = llvm::ConstantArray::get(AT, Ivars);
03314   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
03315 
03316   llvm::GlobalVariable *GV;
03317   if (ForClass)
03318     GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getName(),
03319                            Init, "__OBJC,__class_vars,regular,no_dead_strip",
03320                            4, true);
03321   else
03322     GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_" + ID->getName(),
03323                            Init, "__OBJC,__instance_vars,regular,no_dead_strip",
03324                            4, true);
03325   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
03326 }
03327 
03328 /*
03329   struct objc_method {
03330   SEL method_name;
03331   char *method_types;
03332   void *method;
03333   };
03334 
03335   struct objc_method_list {
03336   struct objc_method_list *obsolete;
03337   int count;
03338   struct objc_method methods_list[count];
03339   };
03340 */
03341 
03342 /// GetMethodConstant - Return a struct objc_method constant for the
03343 /// given method if it has been defined. The result is null if the
03344 /// method has not been defined. The return value has type MethodPtrTy.
03345 llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
03346   llvm::Function *Fn = GetMethodDefinition(MD);
03347   if (!Fn)
03348     return 0;
03349 
03350   llvm::Constant *Method[] = {
03351     llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
03352                                    ObjCTypes.SelectorPtrTy),
03353     GetMethodVarType(MD),
03354     llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy)
03355   };
03356   return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
03357 }
03358 
03359 llvm::Constant *CGObjCMac::EmitMethodList(Twine Name,
03360                                           const char *Section,
03361                                           ArrayRef<llvm::Constant*> Methods) {
03362   // Return null for empty list.
03363   if (Methods.empty())
03364     return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
03365 
03366   llvm::Constant *Values[3];
03367   Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
03368   Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
03369   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
03370                                              Methods.size());
03371   Values[2] = llvm::ConstantArray::get(AT, Methods);
03372   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
03373 
03374   llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
03375   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListPtrTy);
03376 }
03377 
03378 llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
03379                                                 const ObjCContainerDecl *CD) {
03380   SmallString<256> Name;
03381   GetNameForMethod(OMD, CD, Name);
03382 
03383   CodeGenTypes &Types = CGM.getTypes();
03384   llvm::FunctionType *MethodTy =
03385     Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
03386   llvm::Function *Method =
03387     llvm::Function::Create(MethodTy,
03388                            llvm::GlobalValue::InternalLinkage,
03389                            Name.str(),
03390                            &CGM.getModule());
03391   MethodDefinitions.insert(std::make_pair(OMD, Method));
03392 
03393   return Method;
03394 }
03395 
03396 llvm::GlobalVariable *
03397 CGObjCCommonMac::CreateMetadataVar(Twine Name,
03398                                    llvm::Constant *Init,
03399                                    const char *Section,
03400                                    unsigned Align,
03401                                    bool AddToUsed) {
03402   llvm::Type *Ty = Init->getType();
03403   llvm::GlobalVariable *GV =
03404     new llvm::GlobalVariable(CGM.getModule(), Ty, false,
03405                              llvm::GlobalValue::PrivateLinkage, Init, Name);
03406   assertPrivateName(GV);
03407   if (Section)
03408     GV->setSection(Section);
03409   if (Align)
03410     GV->setAlignment(Align);
03411   if (AddToUsed)
03412     CGM.addCompilerUsedGlobal(GV);
03413   return GV;
03414 }
03415 
03416 llvm::Function *CGObjCMac::ModuleInitFunction() {
03417   // Abuse this interface function as a place to finalize.
03418   FinishModule();
03419   return NULL;
03420 }
03421 
03422 llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
03423   return ObjCTypes.getGetPropertyFn();
03424 }
03425 
03426 llvm::Constant *CGObjCMac::GetPropertySetFunction() {
03427   return ObjCTypes.getSetPropertyFn();
03428 }
03429 
03430 llvm::Constant *CGObjCMac::GetOptimizedPropertySetFunction(bool atomic, 
03431                                                            bool copy) {
03432   return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy);
03433 }
03434 
03435 llvm::Constant *CGObjCMac::GetGetStructFunction() {
03436   return ObjCTypes.getCopyStructFn();
03437 }
03438 llvm::Constant *CGObjCMac::GetSetStructFunction() {
03439   return ObjCTypes.getCopyStructFn();
03440 }
03441 
03442 llvm::Constant *CGObjCMac::GetCppAtomicObjectGetFunction() {
03443   return ObjCTypes.getCppAtomicObjectFunction();
03444 }
03445 llvm::Constant *CGObjCMac::GetCppAtomicObjectSetFunction() {
03446   return ObjCTypes.getCppAtomicObjectFunction();
03447 }
03448 
03449 llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
03450   return ObjCTypes.getEnumerationMutationFn();
03451 }
03452 
03453 void CGObjCMac::EmitTryStmt(CodeGenFunction &CGF, const ObjCAtTryStmt &S) {
03454   return EmitTryOrSynchronizedStmt(CGF, S);
03455 }
03456 
03457 void CGObjCMac::EmitSynchronizedStmt(CodeGenFunction &CGF,
03458                                      const ObjCAtSynchronizedStmt &S) {
03459   return EmitTryOrSynchronizedStmt(CGF, S);
03460 }
03461 
03462 namespace {
03463   struct PerformFragileFinally : EHScopeStack::Cleanup {
03464     const Stmt &S;
03465     llvm::Value *SyncArgSlot;
03466     llvm::Value *CallTryExitVar;
03467     llvm::Value *ExceptionData;
03468     ObjCTypesHelper &ObjCTypes;
03469     PerformFragileFinally(const Stmt *S,
03470                           llvm::Value *SyncArgSlot,
03471                           llvm::Value *CallTryExitVar,
03472                           llvm::Value *ExceptionData,
03473                           ObjCTypesHelper *ObjCTypes)
03474       : S(*S), SyncArgSlot(SyncArgSlot), CallTryExitVar(CallTryExitVar),
03475         ExceptionData(ExceptionData), ObjCTypes(*ObjCTypes) {}
03476 
03477     void Emit(CodeGenFunction &CGF, Flags flags) override {
03478       // Check whether we need to call objc_exception_try_exit.
03479       // In optimized code, this branch will always be folded.
03480       llvm::BasicBlock *FinallyCallExit =
03481         CGF.createBasicBlock("finally.call_exit");
03482       llvm::BasicBlock *FinallyNoCallExit =
03483         CGF.createBasicBlock("finally.no_call_exit");
03484       CGF.Builder.CreateCondBr(CGF.Builder.CreateLoad(CallTryExitVar),
03485                                FinallyCallExit, FinallyNoCallExit);
03486 
03487       CGF.EmitBlock(FinallyCallExit);
03488       CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryExitFn(),
03489                                   ExceptionData);
03490 
03491       CGF.EmitBlock(FinallyNoCallExit);
03492 
03493       if (isa<ObjCAtTryStmt>(S)) {
03494         if (const ObjCAtFinallyStmt* FinallyStmt =
03495               cast<ObjCAtTryStmt>(S).getFinallyStmt()) {
03496           // Don't try to do the @finally if this is an EH cleanup.
03497           if (flags.isForEHCleanup()) return;
03498 
03499           // Save the current cleanup destination in case there's
03500           // control flow inside the finally statement.
03501           llvm::Value *CurCleanupDest =
03502             CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot());
03503 
03504           CGF.EmitStmt(FinallyStmt->getFinallyBody());
03505 
03506           if (CGF.HaveInsertPoint()) {
03507             CGF.Builder.CreateStore(CurCleanupDest,
03508                                     CGF.getNormalCleanupDestSlot());
03509           } else {
03510             // Currently, the end of the cleanup must always exist.
03511             CGF.EnsureInsertPoint();
03512           }
03513         }
03514       } else {
03515         // Emit objc_sync_exit(expr); as finally's sole statement for
03516         // @synchronized.
03517         llvm::Value *SyncArg = CGF.Builder.CreateLoad(SyncArgSlot);
03518         CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncExitFn(), SyncArg);
03519       }
03520     }
03521   };
03522 
03523   class FragileHazards {
03524     CodeGenFunction &CGF;
03525     SmallVector<llvm::Value*, 20> Locals;
03526     llvm::DenseSet<llvm::BasicBlock*> BlocksBeforeTry;
03527 
03528     llvm::InlineAsm *ReadHazard;
03529     llvm::InlineAsm *WriteHazard;
03530 
03531     llvm::FunctionType *GetAsmFnType();
03532 
03533     void collectLocals();
03534     void emitReadHazard(CGBuilderTy &Builder);
03535 
03536   public:
03537     FragileHazards(CodeGenFunction &CGF);
03538 
03539     void emitWriteHazard();
03540     void emitHazardsInNewBlocks();
03541   };
03542 }
03543 
03544 /// Create the fragile-ABI read and write hazards based on the current
03545 /// state of the function, which is presumed to be immediately prior
03546 /// to a @try block.  These hazards are used to maintain correct
03547 /// semantics in the face of optimization and the fragile ABI's
03548 /// cavalier use of setjmp/longjmp.
03549 FragileHazards::FragileHazards(CodeGenFunction &CGF) : CGF(CGF) {
03550   collectLocals();
03551 
03552   if (Locals.empty()) return;
03553 
03554   // Collect all the blocks in the function.
03555   for (llvm::Function::iterator
03556          I = CGF.CurFn->begin(), E = CGF.CurFn->end(); I != E; ++I)
03557     BlocksBeforeTry.insert(&*I);
03558 
03559   llvm::FunctionType *AsmFnTy = GetAsmFnType();
03560 
03561   // Create a read hazard for the allocas.  This inhibits dead-store
03562   // optimizations and forces the values to memory.  This hazard is
03563   // inserted before any 'throwing' calls in the protected scope to
03564   // reflect the possibility that the variables might be read from the
03565   // catch block if the call throws.
03566   {
03567     std::string Constraint;
03568     for (unsigned I = 0, E = Locals.size(); I != E; ++I) {
03569       if (I) Constraint += ',';
03570       Constraint += "*m";
03571     }
03572 
03573     ReadHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);
03574   }
03575 
03576   // Create a write hazard for the allocas.  This inhibits folding
03577   // loads across the hazard.  This hazard is inserted at the
03578   // beginning of the catch path to reflect the possibility that the
03579   // variables might have been written within the protected scope.
03580   {
03581     std::string Constraint;
03582     for (unsigned I = 0, E = Locals.size(); I != E; ++I) {
03583       if (I) Constraint += ',';
03584       Constraint += "=*m";
03585     }
03586 
03587     WriteHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);
03588   }
03589 }
03590 
03591 /// Emit a write hazard at the current location.
03592 void FragileHazards::emitWriteHazard() {
03593   if (Locals.empty()) return;
03594 
03595   CGF.EmitNounwindRuntimeCall(WriteHazard, Locals);
03596 }
03597 
03598 void FragileHazards::emitReadHazard(CGBuilderTy &Builder) {
03599   assert(!Locals.empty());
03600   llvm::CallInst *call = Builder.CreateCall(ReadHazard, Locals);
03601   call->setDoesNotThrow();
03602   call->setCallingConv(CGF.getRuntimeCC());
03603 }
03604 
03605 /// Emit read hazards in all the protected blocks, i.e. all the blocks
03606 /// which have been inserted since the beginning of the try.
03607 void FragileHazards::emitHazardsInNewBlocks() {
03608   if (Locals.empty()) return;
03609 
03610   CGBuilderTy Builder(CGF.getLLVMContext());
03611 
03612   // Iterate through all blocks, skipping those prior to the try.
03613   for (llvm::Function::iterator
03614          FI = CGF.CurFn->begin(), FE = CGF.CurFn->end(); FI != FE; ++FI) {
03615     llvm::BasicBlock &BB = *FI;
03616     if (BlocksBeforeTry.count(&BB)) continue;
03617 
03618     // Walk through all the calls in the block.
03619     for (llvm::BasicBlock::iterator
03620            BI = BB.begin(), BE = BB.end(); BI != BE; ++BI) {
03621       llvm::Instruction &I = *BI;
03622 
03623       // Ignore instructions that aren't non-intrinsic calls.
03624       // These are the only calls that can possibly call longjmp.
03625       if (!isa<llvm::CallInst>(I) && !isa<llvm::InvokeInst>(I)) continue;
03626       if (isa<llvm::IntrinsicInst>(I))
03627         continue;
03628 
03629       // Ignore call sites marked nounwind.  This may be questionable,
03630       // since 'nounwind' doesn't necessarily mean 'does not call longjmp'.
03631       llvm::CallSite CS(&I);
03632       if (CS.doesNotThrow()) continue;
03633 
03634       // Insert a read hazard before the call.  This will ensure that
03635       // any writes to the locals are performed before making the
03636       // call.  If the call throws, then this is sufficient to
03637       // guarantee correctness as long as it doesn't also write to any
03638       // locals.
03639       Builder.SetInsertPoint(&BB, BI);
03640       emitReadHazard(Builder);
03641     }
03642   }
03643 }
03644 
03645 static void addIfPresent(llvm::DenseSet<llvm::Value*> &S, llvm::Value *V) {
03646   if (V) S.insert(V);
03647 }
03648 
03649 void FragileHazards::collectLocals() {
03650   // Compute a set of allocas to ignore.
03651   llvm::DenseSet<llvm::Value*> AllocasToIgnore;
03652   addIfPresent(AllocasToIgnore, CGF.ReturnValue);
03653   addIfPresent(AllocasToIgnore, CGF.NormalCleanupDest);
03654 
03655   // Collect all the allocas currently in the function.  This is
03656   // probably way too aggressive.
03657   llvm::BasicBlock &Entry = CGF.CurFn->getEntryBlock();
03658   for (llvm::BasicBlock::iterator
03659          I = Entry.begin(), E = Entry.end(); I != E; ++I)
03660     if (isa<llvm::AllocaInst>(*I) && !AllocasToIgnore.count(&*I))
03661       Locals.push_back(&*I);
03662 }
03663 
03664 llvm::FunctionType *FragileHazards::GetAsmFnType() {
03665   SmallVector<llvm::Type *, 16> tys(Locals.size());
03666   for (unsigned i = 0, e = Locals.size(); i != e; ++i)
03667     tys[i] = Locals[i]->getType();
03668   return llvm::FunctionType::get(CGF.VoidTy, tys, false);
03669 }
03670 
03671 /*
03672 
03673   Objective-C setjmp-longjmp (sjlj) Exception Handling
03674   --
03675 
03676   A catch buffer is a setjmp buffer plus:
03677     - a pointer to the exception that was caught
03678     - a pointer to the previous exception data buffer
03679     - two pointers of reserved storage
03680   Therefore catch buffers form a stack, with a pointer to the top
03681   of the stack kept in thread-local storage.
03682 
03683   objc_exception_try_enter pushes a catch buffer onto the EH stack.
03684   objc_exception_try_exit pops the given catch buffer, which is
03685     required to be the top of the EH stack.
03686   objc_exception_throw pops the top of the EH stack, writes the
03687     thrown exception into the appropriate field, and longjmps
03688     to the setjmp buffer.  It crashes the process (with a printf
03689     and an abort()) if there are no catch buffers on the stack.
03690   objc_exception_extract just reads the exception pointer out of the
03691     catch buffer.
03692 
03693   There's no reason an implementation couldn't use a light-weight
03694   setjmp here --- something like __builtin_setjmp, but API-compatible
03695   with the heavyweight setjmp.  This will be more important if we ever
03696   want to implement correct ObjC/C++ exception interactions for the
03697   fragile ABI.
03698 
03699   Note that for this use of setjmp/longjmp to be correct, we may need
03700   to mark some local variables volatile: if a non-volatile local
03701   variable is modified between the setjmp and the longjmp, it has
03702   indeterminate value.  For the purposes of LLVM IR, it may be
03703   sufficient to make loads and stores within the @try (to variables
03704   declared outside the @try) volatile.  This is necessary for
03705   optimized correctness, but is not currently being done; this is
03706   being tracked as rdar://problem/8160285
03707 
03708   The basic framework for a @try-catch-finally is as follows:
03709   {
03710   objc_exception_data d;
03711   id _rethrow = null;
03712   bool _call_try_exit = true;
03713 
03714   objc_exception_try_enter(&d);
03715   if (!setjmp(d.jmp_buf)) {
03716   ... try body ...
03717   } else {
03718   // exception path
03719   id _caught = objc_exception_extract(&d);
03720 
03721   // enter new try scope for handlers
03722   if (!setjmp(d.jmp_buf)) {
03723   ... match exception and execute catch blocks ...
03724 
03725   // fell off end, rethrow.
03726   _rethrow = _caught;
03727   ... jump-through-finally to finally_rethrow ...
03728   } else {
03729   // exception in catch block
03730   _rethrow = objc_exception_extract(&d);
03731   _call_try_exit = false;
03732   ... jump-through-finally to finally_rethrow ...
03733   }
03734   }
03735   ... jump-through-finally to finally_end ...
03736 
03737   finally:
03738   if (_call_try_exit)
03739   objc_exception_try_exit(&d);
03740 
03741   ... finally block ....
03742   ... dispatch to finally destination ...
03743 
03744   finally_rethrow:
03745   objc_exception_throw(_rethrow);
03746 
03747   finally_end:
03748   }
03749 
03750   This framework differs slightly from the one gcc uses, in that gcc
03751   uses _rethrow to determine if objc_exception_try_exit should be called
03752   and if the object should be rethrown. This breaks in the face of
03753   throwing nil and introduces unnecessary branches.
03754 
03755   We specialize this framework for a few particular circumstances:
03756 
03757   - If there are no catch blocks, then we avoid emitting the second
03758   exception handling context.
03759 
03760   - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
03761   e)) we avoid emitting the code to rethrow an uncaught exception.
03762 
03763   - FIXME: If there is no @finally block we can do a few more
03764   simplifications.
03765 
03766   Rethrows and Jumps-Through-Finally
03767   --
03768 
03769   '@throw;' is supported by pushing the currently-caught exception
03770   onto ObjCEHStack while the @catch blocks are emitted.
03771 
03772   Branches through the @finally block are handled with an ordinary
03773   normal cleanup.  We do not register an EH cleanup; fragile-ABI ObjC
03774   exceptions are not compatible with C++ exceptions, and this is
03775   hardly the only place where this will go wrong.
03776 
03777   @synchronized(expr) { stmt; } is emitted as if it were:
03778     id synch_value = expr;
03779     objc_sync_enter(synch_value);
03780     @try { stmt; } @finally { objc_sync_exit(synch_value); }
03781 */
03782 
03783 void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
03784                                           const Stmt &S) {
03785   bool isTry = isa<ObjCAtTryStmt>(S);
03786 
03787   // A destination for the fall-through edges of the catch handlers to
03788   // jump to.
03789   CodeGenFunction::JumpDest FinallyEnd =
03790     CGF.getJumpDestInCurrentScope("finally.end");
03791 
03792   // A destination for the rethrow edge of the catch handlers to jump
03793   // to.
03794   CodeGenFunction::JumpDest FinallyRethrow =
03795     CGF.getJumpDestInCurrentScope("finally.rethrow");
03796 
03797   // For @synchronized, call objc_sync_enter(sync.expr). The
03798   // evaluation of the expression must occur before we enter the
03799   // @synchronized.  We can't avoid a temp here because we need the
03800   // value to be preserved.  If the backend ever does liveness
03801   // correctly after setjmp, this will be unnecessary.
03802   llvm::Value *SyncArgSlot = 0;
03803   if (!isTry) {
03804     llvm::Value *SyncArg =
03805       CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
03806     SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
03807     CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncEnterFn(), SyncArg);
03808 
03809     SyncArgSlot = CGF.CreateTempAlloca(SyncArg->getType(), "sync.arg");
03810     CGF.Builder.CreateStore(SyncArg, SyncArgSlot);
03811   }
03812 
03813   // Allocate memory for the setjmp buffer.  This needs to be kept
03814   // live throughout the try and catch blocks.
03815   llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
03816                                                     "exceptiondata.ptr");
03817 
03818   // Create the fragile hazards.  Note that this will not capture any
03819   // of the allocas required for exception processing, but will
03820   // capture the current basic block (which extends all the way to the
03821   // setjmp call) as "before the @try".
03822   FragileHazards Hazards(CGF);
03823 
03824   // Create a flag indicating whether the cleanup needs to call
03825   // objc_exception_try_exit.  This is true except when
03826   //   - no catches match and we're branching through the cleanup
03827   //     just to rethrow the exception, or
03828   //   - a catch matched and we're falling out of the catch handler.
03829   // The setjmp-safety rule here is that we should always store to this
03830   // variable in a place that dominates the branch through the cleanup
03831   // without passing through any setjmps.
03832   llvm::Value *CallTryExitVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(),
03833                                                      "_call_try_exit");
03834 
03835   // A slot containing the exception to rethrow.  Only needed when we
03836   // have both a @catch and a @finally.
03837   llvm::Value *PropagatingExnVar = 0;
03838 
03839   // Push a normal cleanup to leave the try scope.
03840   CGF.EHStack.pushCleanup<PerformFragileFinally>(NormalAndEHCleanup, &S,
03841                                                  SyncArgSlot,
03842                                                  CallTryExitVar,
03843                                                  ExceptionData,
03844                                                  &ObjCTypes);
03845 
03846   // Enter a try block:
03847   //  - Call objc_exception_try_enter to push ExceptionData on top of
03848   //    the EH stack.
03849   CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
03850 
03851   //  - Call setjmp on the exception data buffer.
03852   llvm::Constant *Zero = llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
03853   llvm::Value *GEPIndexes[] = { Zero, Zero, Zero };
03854   llvm::Value *SetJmpBuffer =
03855     CGF.Builder.CreateGEP(ExceptionData, GEPIndexes, "setjmp_buffer");
03856   llvm::CallInst *SetJmpResult =
03857     CGF.EmitNounwindRuntimeCall(ObjCTypes.getSetJmpFn(), SetJmpBuffer, "setjmp_result");
03858   SetJmpResult->setCanReturnTwice();
03859 
03860   // If setjmp returned 0, enter the protected block; otherwise,
03861   // branch to the handler.
03862   llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
03863   llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
03864   llvm::Value *DidCatch =
03865     CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
03866   CGF.Builder.CreateCondBr(DidCatch, TryHandler, TryBlock);
03867 
03868   // Emit the protected block.
03869   CGF.EmitBlock(TryBlock);
03870   CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
03871   CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
03872                      : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
03873 
03874   CGBuilderTy::InsertPoint TryFallthroughIP = CGF.Builder.saveAndClearIP();
03875 
03876   // Emit the exception handler block.
03877   CGF.EmitBlock(TryHandler);
03878 
03879   // Don't optimize loads of the in-scope locals across this point.
03880   Hazards.emitWriteHazard();
03881 
03882   // For a @synchronized (or a @try with no catches), just branch
03883   // through the cleanup to the rethrow block.
03884   if (!isTry || !cast<ObjCAtTryStmt>(S).getNumCatchStmts()) {
03885     // Tell the cleanup not to re-pop the exit.
03886     CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
03887     CGF.EmitBranchThroughCleanup(FinallyRethrow);
03888 
03889   // Otherwise, we have to match against the caught exceptions.
03890   } else {
03891     // Retrieve the exception object.  We may emit multiple blocks but
03892     // nothing can cross this so the value is already in SSA form.
03893     llvm::CallInst *Caught =
03894       CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
03895                                   ExceptionData, "caught");
03896 
03897     // Push the exception to rethrow onto the EH value stack for the
03898     // benefit of any @throws in the handlers.
03899     CGF.ObjCEHValueStack.push_back(Caught);
03900 
03901     const ObjCAtTryStmt* AtTryStmt = cast<ObjCAtTryStmt>(&S);
03902 
03903     bool HasFinally = (AtTryStmt->getFinallyStmt() != 0);
03904 
03905     llvm::BasicBlock *CatchBlock = 0;
03906     llvm::BasicBlock *CatchHandler = 0;
03907     if (HasFinally) {
03908       // Save the currently-propagating exception before
03909       // objc_exception_try_enter clears the exception slot.
03910       PropagatingExnVar = CGF.CreateTempAlloca(Caught->getType(),
03911                                                "propagating_exception");
03912       CGF.Builder.CreateStore(Caught, PropagatingExnVar);
03913 
03914       // Enter a new exception try block (in case a @catch block
03915       // throws an exception).
03916       CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(),
03917                                   ExceptionData);
03918 
03919       llvm::CallInst *SetJmpResult =
03920         CGF.EmitNounwindRuntimeCall(ObjCTypes.getSetJmpFn(),
03921                                     SetJmpBuffer, "setjmp.result");
03922       SetJmpResult->setCanReturnTwice();
03923 
03924       llvm::Value *Threw =
03925         CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
03926 
03927       CatchBlock = CGF.createBasicBlock("catch");
03928       CatchHandler = CGF.createBasicBlock("catch_for_catch");
03929       CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
03930 
03931       CGF.EmitBlock(CatchBlock);
03932     }
03933 
03934     CGF.Builder.CreateStore(CGF.Builder.getInt1(HasFinally), CallTryExitVar);
03935 
03936     // Handle catch list. As a special case we check if everything is
03937     // matched and avoid generating code for falling off the end if
03938     // so.
03939     bool AllMatched = false;
03940     for (unsigned I = 0, N = AtTryStmt->getNumCatchStmts(); I != N; ++I) {
03941       const ObjCAtCatchStmt *CatchStmt = AtTryStmt->getCatchStmt(I);
03942 
03943       const VarDecl *CatchParam = CatchStmt->getCatchParamDecl();
03944       const ObjCObjectPointerType *OPT = 0;
03945 
03946       // catch(...) always matches.
03947       if (!CatchParam) {
03948         AllMatched = true;
03949       } else {
03950         OPT = CatchParam->getType()->getAs<ObjCObjectPointerType>();
03951 
03952         // catch(id e) always matches under this ABI, since only
03953         // ObjC exceptions end up here in the first place.
03954         // FIXME: For the time being we also match id<X>; this should
03955         // be rejected by Sema instead.
03956         if (OPT && (OPT->isObjCIdType() || OPT->isObjCQualifiedIdType()))
03957           AllMatched = true;
03958       }
03959 
03960       // If this is a catch-all, we don't need to test anything.
03961       if (AllMatched) {
03962         CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
03963 
03964         if (CatchParam) {
03965           CGF.EmitAutoVarDecl(*CatchParam);
03966           assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
03967 
03968           // These types work out because ConvertType(id) == i8*.
03969           CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
03970         }
03971 
03972         CGF.EmitStmt(CatchStmt->getCatchBody());
03973 
03974         // The scope of the catch variable ends right here.
03975         CatchVarCleanups.ForceCleanup();
03976 
03977         CGF.EmitBranchThroughCleanup(FinallyEnd);
03978         break;
03979       }
03980 
03981       assert(OPT && "Unexpected non-object pointer type in @catch");
03982       const ObjCObjectType *ObjTy = OPT->getObjectType();
03983 
03984       // FIXME: @catch (Class c) ?
03985       ObjCInterfaceDecl *IDecl = ObjTy->getInterface();
03986       assert(IDecl && "Catch parameter must have Objective-C type!");
03987 
03988       // Check if the @catch block matches the exception object.
03989       llvm::Value *Class = EmitClassRef(CGF, IDecl);
03990 
03991       llvm::Value *matchArgs[] = { Class, Caught };
03992       llvm::CallInst *Match =
03993         CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionMatchFn(),
03994                                     matchArgs, "match");
03995 
03996       llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("match");
03997       llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch.next");
03998 
03999       CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
04000                                MatchedBlock, NextCatchBlock);
04001 
04002       // Emit the @catch block.
04003       CGF.EmitBlock(MatchedBlock);
04004 
04005       // Collect any cleanups for the catch variable.  The scope lasts until
04006       // the end of the catch body.
04007       CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
04008 
04009       CGF.EmitAutoVarDecl(*CatchParam);
04010       assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
04011 
04012       // Initialize the catch variable.
04013       llvm::Value *Tmp =
04014         CGF.Builder.CreateBitCast(Caught,
04015                                   CGF.ConvertType(CatchParam->getType()));
04016       CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
04017 
04018       CGF.EmitStmt(CatchStmt->getCatchBody());
04019 
04020       // We're done with the catch variable.
04021       CatchVarCleanups.ForceCleanup();
04022 
04023       CGF.EmitBranchThroughCleanup(FinallyEnd);
04024 
04025       CGF.EmitBlock(NextCatchBlock);
04026     }
04027 
04028     CGF.ObjCEHValueStack.pop_back();
04029 
04030     // If nothing wanted anything to do with the caught exception,
04031     // kill the extract call.
04032     if (Caught->use_empty())
04033       Caught->eraseFromParent();
04034 
04035     if (!AllMatched)
04036       CGF.EmitBranchThroughCleanup(FinallyRethrow);
04037 
04038     if (HasFinally) {
04039       // Emit the exception handler for the @catch blocks.
04040       CGF.EmitBlock(CatchHandler);
04041 
04042       // In theory we might now need a write hazard, but actually it's
04043       // unnecessary because there's no local-accessing code between
04044       // the try's write hazard and here.
04045       //Hazards.emitWriteHazard();
04046 
04047       // Extract the new exception and save it to the
04048       // propagating-exception slot.
04049       assert(PropagatingExnVar);
04050       llvm::CallInst *NewCaught =
04051         CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
04052                                     ExceptionData, "caught");
04053       CGF.Builder.CreateStore(NewCaught, PropagatingExnVar);
04054 
04055       // Don't pop the catch handler; the throw already did.
04056       CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
04057       CGF.EmitBranchThroughCleanup(FinallyRethrow);
04058     }
04059   }
04060 
04061   // Insert read hazards as required in the new blocks.
04062   Hazards.emitHazardsInNewBlocks();
04063 
04064   // Pop the cleanup.
04065   CGF.Builder.restoreIP(TryFallthroughIP);
04066   if (CGF.HaveInsertPoint())
04067     CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
04068   CGF.PopCleanupBlock();
04069   CGF.EmitBlock(FinallyEnd.getBlock(), true);
04070 
04071   // Emit the rethrow block.
04072   CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
04073   CGF.EmitBlock(FinallyRethrow.getBlock(), true);
04074   if (CGF.HaveInsertPoint()) {
04075     // If we have a propagating-exception variable, check it.
04076     llvm::Value *PropagatingExn;
04077     if (PropagatingExnVar) {
04078       PropagatingExn = CGF.Builder.CreateLoad(PropagatingExnVar);
04079 
04080     // Otherwise, just look in the buffer for the exception to throw.
04081     } else {
04082       llvm::CallInst *Caught =
04083         CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
04084                                     ExceptionData);
04085       PropagatingExn = Caught;
04086     }
04087 
04088     CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionThrowFn(),
04089                                 PropagatingExn);
04090     CGF.Builder.CreateUnreachable();
04091   }
04092 
04093   CGF.Builder.restoreIP(SavedIP);
04094 }
04095 
04096 void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
04097                               const ObjCAtThrowStmt &S,
04098                               bool ClearInsertionPoint) {
04099   llvm::Value *ExceptionAsObject;
04100 
04101   if (const Expr *ThrowExpr = S.getThrowExpr()) {
04102     llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
04103     ExceptionAsObject =
04104       CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
04105   } else {
04106     assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
04107            "Unexpected rethrow outside @catch block.");
04108     ExceptionAsObject = CGF.ObjCEHValueStack.back();
04109   }
04110 
04111   CGF.EmitRuntimeCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject)
04112     ->setDoesNotReturn();
04113   CGF.Builder.CreateUnreachable();
04114 
04115   // Clear the insertion point to indicate we are in unreachable code.
04116   if (ClearInsertionPoint)
04117     CGF.Builder.ClearInsertionPoint();
04118 }
04119 
04120 /// EmitObjCWeakRead - Code gen for loading value of a __weak
04121 /// object: objc_read_weak (id *src)
04122 ///
04123 llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
04124                                           llvm::Value *AddrWeakObj) {
04125   llvm::Type* DestTy =
04126     cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
04127   AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj,
04128                                           ObjCTypes.PtrObjectPtrTy);
04129   llvm::Value *read_weak =
04130     CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(),
04131                                 AddrWeakObj, "weakread");
04132   read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
04133   return read_weak;
04134 }
04135 
04136 /// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
04137 /// objc_assign_weak (id src, id *dst)
04138 ///
04139 void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
04140                                    llvm::Value *src, llvm::Value *dst) {
04141   llvm::Type * SrcTy = src->getType();
04142   if (!isa<llvm::PointerType>(SrcTy)) {
04143     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
04144     assert(Size <= 8 && "does not support size > 8");
04145     src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
04146       : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
04147     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
04148   }
04149   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
04150   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
04151   llvm::Value *args[] = { src, dst };
04152   CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(),
04153                               args, "weakassign");
04154   return;
04155 }
04156 
04157 /// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
04158 /// objc_assign_global (id src, id *dst)
04159 ///
04160 void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
04161                                      llvm::Value *src, llvm::Value *dst,
04162                                      bool threadlocal) {
04163   llvm::Type * SrcTy = src->getType();
04164   if (!isa<llvm::PointerType>(SrcTy)) {
04165     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
04166     assert(Size <= 8 && "does not support size > 8");
04167     src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
04168       : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
04169     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
04170   }
04171   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
04172   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
04173   llvm::Value *args[] = { src, dst };
04174   if (!threadlocal)
04175     CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(),
04176                                 args, "globalassign");
04177   else
04178     CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(),
04179                                 args, "threadlocalassign");
04180   return;
04181 }
04182 
04183 /// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
04184 /// objc_assign_ivar (id src, id *dst, ptrdiff_t ivaroffset)
04185 ///
04186 void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
04187                                    llvm::Value *src, llvm::Value *dst,
04188                                    llvm::Value *ivarOffset) {
04189   assert(ivarOffset && "EmitObjCIvarAssign - ivarOffset is NULL");
04190   llvm::Type * SrcTy = src->getType();
04191   if (!isa<llvm::PointerType>(SrcTy)) {
04192     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
04193     assert(Size <= 8 && "does not support size > 8");
04194     src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
04195       : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
04196     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
04197   }
04198   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
04199   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
04200   llvm::Value *args[] = { src, dst, ivarOffset };
04201   CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args);
04202   return;
04203 }
04204 
04205 /// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
04206 /// objc_assign_strongCast (id src, id *dst)
04207 ///
04208 void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
04209                                          llvm::Value *src, llvm::Value *dst) {
04210   llvm::Type * SrcTy = src->getType();
04211   if (!isa<llvm::PointerType>(SrcTy)) {
04212     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
04213     assert(Size <= 8 && "does not support size > 8");
04214     src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
04215       : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
04216     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
04217   }
04218   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
04219   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
04220   llvm::Value *args[] = { src, dst };
04221   CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(),
04222                               args, "weakassign");
04223   return;
04224 }
04225 
04226 void CGObjCMac::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
04227                                          llvm::Value *DestPtr,
04228                                          llvm::Value *SrcPtr,
04229                                          llvm::Value *size) {
04230   SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
04231   DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
04232   llvm::Value *args[] = { DestPtr, SrcPtr, size };
04233   CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args);
04234 }
04235 
04236 /// EmitObjCValueForIvar - Code Gen for ivar reference.
04237 ///
04238 LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
04239                                        QualType ObjectTy,
04240                                        llvm::Value *BaseValue,
04241                                        const ObjCIvarDecl *Ivar,
04242                                        unsigned CVRQualifiers) {
04243   const ObjCInterfaceDecl *ID =
04244     ObjectTy->getAs<ObjCObjectType>()->getInterface();
04245   return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
04246                                   EmitIvarOffset(CGF, ID, Ivar));
04247 }
04248 
04249 llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
04250                                        const ObjCInterfaceDecl *Interface,
04251                                        const ObjCIvarDecl *Ivar) {
04252   uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
04253   return llvm::ConstantInt::get(
04254     CGM.getTypes().ConvertType(CGM.getContext().LongTy),
04255     Offset);
04256 }
04257 
04258 /* *** Private Interface *** */
04259 
04260 /// EmitImageInfo - Emit the image info marker used to encode some module
04261 /// level information.
04262 ///
04263 /// See: <rdr://4810609&4810587&4810587>
04264 /// struct IMAGE_INFO {
04265 ///   unsigned version;
04266 ///   unsigned flags;
04267 /// };
04268 enum ImageInfoFlags {
04269   eImageInfo_FixAndContinue      = (1 << 0), // This flag is no longer set by clang.
04270   eImageInfo_GarbageCollected    = (1 << 1),
04271   eImageInfo_GCOnly              = (1 << 2),
04272   eImageInfo_OptimizedByDyld     = (1 << 3), // This flag is set by the dyld shared cache.
04273 
04274   // A flag indicating that the module has no instances of a @synthesize of a
04275   // superclass variable. <rdar://problem/6803242>
04276   eImageInfo_CorrectedSynthesize = (1 << 4), // This flag is no longer set by clang.
04277   eImageInfo_ImageIsSimulated    = (1 << 5)
04278 };
04279 
04280 void CGObjCCommonMac::EmitImageInfo() {
04281   unsigned version = 0; // Version is unused?
04282   const char *Section = (ObjCABI == 1) ?
04283     "__OBJC, __image_info,regular" :
04284     "__DATA, __objc_imageinfo, regular, no_dead_strip";
04285 
04286   // Generate module-level named metadata to convey this information to the
04287   // linker and code-gen.
04288   llvm::Module &Mod = CGM.getModule();
04289 
04290   // Add the ObjC ABI version to the module flags.
04291   Mod.addModuleFlag(llvm::Module::Error, "Objective-C Version", ObjCABI);
04292   Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Version",
04293                     version);
04294   Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Section",
04295                     llvm::MDString::get(VMContext,Section));
04296 
04297   if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
04298     // Non-GC overrides those files which specify GC.
04299     Mod.addModuleFlag(llvm::Module::Override,
04300                       "Objective-C Garbage Collection", (uint32_t)0);
04301   } else {
04302     // Add the ObjC garbage collection value.
04303     Mod.addModuleFlag(llvm::Module::Error,
04304                       "Objective-C Garbage Collection",
04305                       eImageInfo_GarbageCollected);
04306 
04307     if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
04308       // Add the ObjC GC Only value.
04309       Mod.addModuleFlag(llvm::Module::Error, "Objective-C GC Only",
04310                         eImageInfo_GCOnly);
04311 
04312       // Require that GC be specified and set to eImageInfo_GarbageCollected.
04313       llvm::Value *Ops[2] = {
04314         llvm::MDString::get(VMContext, "Objective-C Garbage Collection"),
04315         llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
04316                                eImageInfo_GarbageCollected)
04317       };
04318       Mod.addModuleFlag(llvm::Module::Require, "Objective-C GC Only",
04319                         llvm::MDNode::get(VMContext, Ops));
04320     }
04321   }
04322 
04323   // Indicate whether we're compiling this to run on a simulator.
04324   const llvm::Triple &Triple = CGM.getTarget().getTriple();
04325   if (Triple.isiOS() &&
04326       (Triple.getArch() == llvm::Triple::x86 ||
04327        Triple.getArch() == llvm::Triple::x86_64))
04328     Mod.addModuleFlag(llvm::Module::Error, "Objective-C Is Simulated",
04329                       eImageInfo_ImageIsSimulated);
04330 }
04331 
04332 // struct objc_module {
04333 //   unsigned long version;
04334 //   unsigned long size;
04335 //   const char *name;
04336 //   Symtab symtab;
04337 // };
04338 
04339 // FIXME: Get from somewhere
04340 static const int ModuleVersion = 7;
04341 
04342 void CGObjCMac::EmitModuleInfo() {
04343   uint64_t Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ModuleTy);
04344 
04345   llvm::Constant *Values[] = {
04346     llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion),
04347     llvm::ConstantInt::get(ObjCTypes.LongTy, Size),
04348     // This used to be the filename, now it is unused. <rdr://4327263>
04349     GetClassName(&CGM.getContext().Idents.get("")),
04350     EmitModuleSymbols()
04351   };
04352   CreateMetadataVar("\01L_OBJC_MODULES",
04353                     llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
04354                     "__OBJC,__module_info,regular,no_dead_strip",
04355                     4, true);
04356 }
04357 
04358 llvm::Constant *CGObjCMac::EmitModuleSymbols() {
04359   unsigned NumClasses = DefinedClasses.size();
04360   unsigned NumCategories = DefinedCategories.size();
04361 
04362   // Return null if no symbols were defined.
04363   if (!NumClasses && !NumCategories)
04364     return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
04365 
04366   llvm::Constant *Values[5];
04367   Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
04368   Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
04369   Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
04370   Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
04371 
04372   // The runtime expects exactly the list of defined classes followed
04373   // by the list of defined categories, in a single array.
04374   SmallVector<llvm::Constant*, 8> Symbols(NumClasses + NumCategories);
04375   for (unsigned i=0; i<NumClasses; i++) {
04376     const ObjCInterfaceDecl *ID = ImplementedClasses[i];
04377     assert(ID);
04378     if (ObjCImplementationDecl *IMP = ID->getImplementation())
04379       // We are implementing a weak imported interface. Give it external linkage
04380       if (ID->isWeakImported() && !IMP->isWeakImported())
04381         DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
04382     
04383     Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
04384                                                 ObjCTypes.Int8PtrTy);
04385   }
04386   for (unsigned i=0; i<NumCategories; i++)
04387     Symbols[NumClasses + i] =
04388       llvm::ConstantExpr::getBitCast(DefinedCategories[i],
04389                                      ObjCTypes.Int8PtrTy);
04390 
04391   Values[4] =
04392     llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
04393                                                   Symbols.size()),
04394                              Symbols);
04395 
04396   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
04397 
04398   llvm::GlobalVariable *GV =
04399     CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
04400                       "__OBJC,__symbols,regular,no_dead_strip",
04401                       4, true);
04402   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
04403 }
04404 
04405 llvm::Value *CGObjCMac::EmitClassRefFromId(CodeGenFunction &CGF,
04406                                            IdentifierInfo *II) {
04407   LazySymbols.insert(II);
04408   
04409   llvm::GlobalVariable *&Entry = ClassReferences[II];
04410   
04411   if (!Entry) {
04412     llvm::Constant *Casted =
04413     llvm::ConstantExpr::getBitCast(GetClassName(II),
04414                                    ObjCTypes.ClassPtrTy);
04415     Entry =
04416     CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
04417                       "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
04418                       4, true);
04419   }
04420   
04421   return CGF.Builder.CreateLoad(Entry);
04422 }
04423 
04424 llvm::Value *CGObjCMac::EmitClassRef(CodeGenFunction &CGF,
04425                                      const ObjCInterfaceDecl *ID) {
04426   return EmitClassRefFromId(CGF, ID->getIdentifier());
04427 }
04428 
04429 llvm::Value *CGObjCMac::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
04430   IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
04431   return EmitClassRefFromId(CGF, II);
04432 }
04433 
04434 llvm::Value *CGObjCMac::EmitSelector(CodeGenFunction &CGF, Selector Sel,
04435                                      bool lvalue) {
04436   llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
04437 
04438   if (!Entry) {
04439     llvm::Constant *Casted =
04440       llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
04441                                      ObjCTypes.SelectorPtrTy);
04442     Entry =
04443       CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
04444                         "__OBJC,__message_refs,literal_pointers,no_dead_strip",
04445                         4, true);
04446     Entry->setExternallyInitialized(true);
04447   }
04448 
04449   if (lvalue)
04450     return Entry;
04451   return CGF.Builder.CreateLoad(Entry);
04452 }
04453 
04454 llvm::Constant *CGObjCCommonMac::GetClassName(IdentifierInfo *Ident) {
04455   llvm::GlobalVariable *&Entry = ClassNames[Ident];
04456 
04457   if (!Entry)
04458     Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
04459                               llvm::ConstantDataArray::getString(VMContext,
04460                                                          Ident->getNameStart()),
04461                               ((ObjCABI == 2) ?
04462                                "__TEXT,__objc_classname,cstring_literals" :
04463                                "__TEXT,__cstring,cstring_literals"),
04464                               1, true);
04465 
04466   return getConstantGEP(VMContext, Entry, 0, 0);
04467 }
04468 
04469 llvm::Function *CGObjCCommonMac::GetMethodDefinition(const ObjCMethodDecl *MD) {
04470   llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*>::iterator
04471       I = MethodDefinitions.find(MD);
04472   if (I != MethodDefinitions.end())
04473     return I->second;
04474 
04475   return NULL;
04476 }
04477 
04478 /// GetIvarLayoutName - Returns a unique constant for the given
04479 /// ivar layout bitmap.
04480 llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
04481                                        const ObjCCommonTypesHelper &ObjCTypes) {
04482   return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
04483 }
04484 
04485 void CGObjCCommonMac::BuildAggrIvarRecordLayout(const RecordType *RT,
04486                                                 unsigned int BytePos,
04487                                                 bool ForStrongLayout,
04488                                                 bool &HasUnion) {
04489   const RecordDecl *RD = RT->getDecl();
04490   // FIXME - Use iterator.
04491   SmallVector<const FieldDecl*, 16> Fields(RD->fields());
04492   llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
04493   const llvm::StructLayout *RecLayout =
04494     CGM.getDataLayout().getStructLayout(cast<llvm::StructType>(Ty));
04495 
04496   BuildAggrIvarLayout(0, RecLayout, RD, Fields, BytePos,
04497                       ForStrongLayout, HasUnion);
04498 }
04499 
04500 void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
04501                              const llvm::StructLayout *Layout,
04502                              const RecordDecl *RD,
04503                              ArrayRef<const FieldDecl*> RecFields,
04504                              unsigned int BytePos, bool ForStrongLayout,
04505                              bool &HasUnion) {
04506   bool IsUnion = (RD && RD->isUnion());
04507   uint64_t MaxUnionIvarSize = 0;
04508   uint64_t MaxSkippedUnionIvarSize = 0;
04509   const FieldDecl *MaxField = 0;
04510   const FieldDecl *MaxSkippedField = 0;
04511   const FieldDecl *LastFieldBitfieldOrUnnamed = 0;
04512   uint64_t MaxFieldOffset = 0;
04513   uint64_t MaxSkippedFieldOffset = 0;
04514   uint64_t LastBitfieldOrUnnamedOffset = 0;
04515   uint64_t FirstFieldDelta = 0;
04516 
04517   if (RecFields.empty())
04518     return;
04519   unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
04520   unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
04521   if (!RD && CGM.getLangOpts().ObjCAutoRefCount) {
04522     const FieldDecl *FirstField = RecFields[0];
04523     FirstFieldDelta = 
04524       ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(FirstField));
04525   }
04526   
04527   for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
04528     const FieldDecl *Field = RecFields[i];
04529     uint64_t FieldOffset;
04530     if (RD) {
04531       // Note that 'i' here is actually the field index inside RD of Field,
04532       // although this dependency is hidden.
04533       const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
04534       FieldOffset = (RL.getFieldOffset(i) / ByteSizeInBits) - FirstFieldDelta;
04535     } else
04536       FieldOffset = 
04537         ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field)) - FirstFieldDelta;
04538 
04539     // Skip over unnamed or bitfields
04540     if (!Field->getIdentifier() || Field->isBitField()) {
04541       LastFieldBitfieldOrUnnamed = Field;
04542       LastBitfieldOrUnnamedOffset = FieldOffset;
04543       continue;
04544     }
04545 
04546     LastFieldBitfieldOrUnnamed = 0;
04547     QualType FQT = Field->getType();
04548     if (FQT->isRecordType() || FQT->isUnionType()) {
04549       if (FQT->isUnionType())
04550         HasUnion = true;
04551 
04552       BuildAggrIvarRecordLayout(FQT->getAs<RecordType>(),
04553                                 BytePos + FieldOffset,
04554                                 ForStrongLayout, HasUnion);
04555       continue;
04556     }
04557 
04558     if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
04559       const ConstantArrayType *CArray =
04560         dyn_cast_or_null<ConstantArrayType>(Array);
04561       uint64_t ElCount = CArray->getSize().getZExtValue();
04562       assert(CArray && "only array with known element size is supported");
04563       FQT = CArray->getElementType();
04564       while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
04565         const ConstantArrayType *CArray =
04566           dyn_cast_or_null<ConstantArrayType>(Array);
04567         ElCount *= CArray->getSize().getZExtValue();
04568         FQT = CArray->getElementType();
04569       }
04570       if (FQT->isRecordType() && ElCount) {
04571         int OldIndex = IvarsInfo.size() - 1;
04572         int OldSkIndex = SkipIvars.size() -1;
04573 
04574         const RecordType *RT = FQT->getAs<RecordType>();
04575         BuildAggrIvarRecordLayout(RT, BytePos + FieldOffset,
04576                                   ForStrongLayout, HasUnion);
04577 
04578         // Replicate layout information for each array element. Note that
04579         // one element is already done.
04580         uint64_t ElIx = 1;
04581         for (int FirstIndex = IvarsInfo.size() - 1,
04582                FirstSkIndex = SkipIvars.size() - 1 ;ElIx < ElCount; ElIx++) {
04583           uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
04584           for (int i = OldIndex+1; i <= FirstIndex; ++i)
04585             IvarsInfo.push_back(GC_IVAR(IvarsInfo[i].ivar_bytepos + Size*ElIx,
04586                                         IvarsInfo[i].ivar_size));
04587           for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i)
04588             SkipIvars.push_back(GC_IVAR(SkipIvars[i].ivar_bytepos + Size*ElIx,
04589                                         SkipIvars[i].ivar_size));
04590         }
04591         continue;
04592       }
04593     }
04594     // At this point, we are done with Record/Union and array there of.
04595     // For other arrays we are down to its element type.
04596     Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), FQT);
04597 
04598     unsigned FieldSize = CGM.getContext().getTypeSize(Field->getType());
04599     if ((ForStrongLayout && GCAttr == Qualifiers::Strong)
04600         || (!ForStrongLayout && GCAttr == Qualifiers::Weak)) {
04601       if (IsUnion) {
04602         uint64_t UnionIvarSize = FieldSize / WordSizeInBits;
04603         if (UnionIvarSize > MaxUnionIvarSize) {
04604           MaxUnionIvarSize = UnionIvarSize;
04605           MaxField = Field;
04606           MaxFieldOffset = FieldOffset;
04607         }
04608       } else {
04609         IvarsInfo.push_back(GC_IVAR(BytePos + FieldOffset,
04610                                     FieldSize / WordSizeInBits));
04611       }
04612     } else if ((ForStrongLayout &&
04613                 (GCAttr == Qualifiers::GCNone || GCAttr == Qualifiers::Weak))
04614                || (!ForStrongLayout && GCAttr != Qualifiers::Weak)) {
04615       if (IsUnion) {
04616         // FIXME: Why the asymmetry? We divide by word size in bits on other
04617         // side.
04618         uint64_t UnionIvarSize = FieldSize / ByteSizeInBits;
04619         if (UnionIvarSize > MaxSkippedUnionIvarSize) {
04620           MaxSkippedUnionIvarSize = UnionIvarSize;
04621           MaxSkippedField = Field;
04622           MaxSkippedFieldOffset = FieldOffset;
04623         }
04624       } else {
04625         // FIXME: Why the asymmetry, we divide by byte size in bits here?
04626         SkipIvars.push_back(GC_IVAR(BytePos + FieldOffset,
04627                                     FieldSize / ByteSizeInBits));
04628       }
04629     }
04630   }
04631 
04632   if (LastFieldBitfieldOrUnnamed) {
04633     if (LastFieldBitfieldOrUnnamed->isBitField()) {
04634       // Last field was a bitfield. Must update skip info.
04635       uint64_t BitFieldSize
04636           = LastFieldBitfieldOrUnnamed->getBitWidthValue(CGM.getContext());
04637       GC_IVAR skivar;
04638       skivar.ivar_bytepos = BytePos + LastBitfieldOrUnnamedOffset;
04639       skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
04640         + ((BitFieldSize % ByteSizeInBits) != 0);
04641       SkipIvars.push_back(skivar);
04642     } else {
04643       assert(!LastFieldBitfieldOrUnnamed->getIdentifier() &&"Expected unnamed");
04644       // Last field was unnamed. Must update skip info.
04645       unsigned FieldSize
04646           = CGM.getContext().getTypeSize(LastFieldBitfieldOrUnnamed->getType());
04647       SkipIvars.push_back(GC_IVAR(BytePos + LastBitfieldOrUnnamedOffset,
04648                                   FieldSize / ByteSizeInBits));
04649     }
04650   }
04651 
04652   if (MaxField)
04653     IvarsInfo.push_back(GC_IVAR(BytePos + MaxFieldOffset,
04654                                 MaxUnionIvarSize));
04655   if (MaxSkippedField)
04656     SkipIvars.push_back(GC_IVAR(BytePos + MaxSkippedFieldOffset,
04657                                 MaxSkippedUnionIvarSize));
04658 }
04659 
04660 /// BuildIvarLayoutBitmap - This routine is the horsework for doing all
04661 /// the computations and returning the layout bitmap (for ivar or blocks) in
04662 /// the given argument BitMap string container. Routine reads
04663 /// two containers, IvarsInfo and SkipIvars which are assumed to be
04664 /// filled already by the caller.
04665 llvm::Constant *CGObjCCommonMac::BuildIvarLayoutBitmap(std::string &BitMap) {
04666   unsigned int WordsToScan, WordsToSkip;
04667   llvm::Type *PtrTy = CGM.Int8PtrTy;
04668   
04669   // Build the string of skip/scan nibbles
04670   SmallVector<SKIP_SCAN, 32> SkipScanIvars;
04671   unsigned int WordSize =
04672   CGM.getTypes().getDataLayout().getTypeAllocSize(PtrTy);
04673   if (IvarsInfo[0].ivar_bytepos == 0) {
04674     WordsToSkip = 0;
04675     WordsToScan = IvarsInfo[0].ivar_size;
04676   } else {
04677     WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
04678     WordsToScan = IvarsInfo[0].ivar_size;
04679   }
04680   for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++) {
04681     unsigned int TailPrevGCObjC =
04682     IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
04683     if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC) {
04684       // consecutive 'scanned' object pointers.
04685       WordsToScan += IvarsInfo[i].ivar_size;
04686     } else {
04687       // Skip over 'gc'able object pointer which lay over each other.
04688       if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
04689         continue;
04690       // Must skip over 1 or more words. We save current skip/scan values
04691       //  and start a new pair.
04692       SKIP_SCAN SkScan;
04693       SkScan.skip = WordsToSkip;
04694       SkScan.scan = WordsToScan;
04695       SkipScanIvars.push_back(SkScan);
04696       
04697       // Skip the hole.
04698       SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
04699       SkScan.scan = 0;
04700       SkipScanIvars.push_back(SkScan);
04701       WordsToSkip = 0;
04702       WordsToScan = IvarsInfo[i].ivar_size;
04703     }
04704   }
04705   if (WordsToScan > 0) {
04706     SKIP_SCAN SkScan;
04707     SkScan.skip = WordsToSkip;
04708     SkScan.scan = WordsToScan;
04709     SkipScanIvars.push_back(SkScan);
04710   }
04711   
04712   if (!SkipIvars.empty()) {
04713     unsigned int LastIndex = SkipIvars.size()-1;
04714     int LastByteSkipped =
04715     SkipIvars[LastIndex].ivar_bytepos + SkipIvars[LastIndex].ivar_size;
04716     LastIndex = IvarsInfo.size()-1;
04717     int LastByteScanned =
04718     IvarsInfo[LastIndex].ivar_bytepos +
04719     IvarsInfo[LastIndex].ivar_size * WordSize;
04720     // Compute number of bytes to skip at the tail end of the last ivar scanned.
04721     if (LastByteSkipped > LastByteScanned) {
04722       unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
04723       SKIP_SCAN SkScan;
04724       SkScan.skip = TotalWords - (LastByteScanned/WordSize);
04725       SkScan.scan = 0;
04726       SkipScanIvars.push_back(SkScan);
04727     }
04728   }
04729   // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
04730   // as 0xMN.
04731   int SkipScan = SkipScanIvars.size()-1;
04732   for (int i = 0; i <= SkipScan; i++) {
04733     if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
04734         && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
04735       // 0xM0 followed by 0x0N detected.
04736       SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
04737       for (int j = i+1; j < SkipScan; j++)
04738         SkipScanIvars[j] = SkipScanIvars[j+1];
04739       --SkipScan;
04740     }
04741   }
04742   
04743   // Generate the string.
04744   for (int i = 0; i <= SkipScan; i++) {
04745     unsigned char byte;
04746     unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
04747     unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
04748     unsigned int skip_big  = SkipScanIvars[i].skip / 0xf;
04749     unsigned int scan_big  = SkipScanIvars[i].scan / 0xf;
04750     
04751     // first skip big.
04752     for (unsigned int ix = 0; ix < skip_big; ix++)
04753       BitMap += (unsigned char)(0xf0);
04754     
04755     // next (skip small, scan)
04756     if (skip_small) {
04757       byte = skip_small << 4;
04758       if (scan_big > 0) {
04759         byte |= 0xf;
04760         --scan_big;
04761       } else if (scan_small) {
04762         byte |= scan_small;
04763         scan_small = 0;
04764       }
04765       BitMap += byte;
04766     }
04767     // next scan big
04768     for (unsigned int ix = 0; ix < scan_big; ix++)
04769       BitMap += (unsigned char)(0x0f);
04770     // last scan small
04771     if (scan_small) {
04772       byte = scan_small;
04773       BitMap += byte;
04774     }
04775   }
04776   // null terminate string.
04777   unsigned char zero = 0;
04778   BitMap += zero;
04779   
04780   llvm::GlobalVariable * Entry =
04781   CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
04782                     llvm::ConstantDataArray::getString(VMContext, BitMap,false),
04783                     ((ObjCABI == 2) ?
04784                      "__TEXT,__objc_classname,cstring_literals" :
04785                      "__TEXT,__cstring,cstring_literals"),
04786                     1, true);
04787   return getConstantGEP(VMContext, Entry, 0, 0);
04788 }
04789 
04790 /// BuildIvarLayout - Builds ivar layout bitmap for the class
04791 /// implementation for the __strong or __weak case.
04792 /// The layout map displays which words in ivar list must be skipped
04793 /// and which must be scanned by GC (see below). String is built of bytes.
04794 /// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
04795 /// of words to skip and right nibble is count of words to scan. So, each
04796 /// nibble represents up to 15 workds to skip or scan. Skipping the rest is
04797 /// represented by a 0x00 byte which also ends the string.
04798 /// 1. when ForStrongLayout is true, following ivars are scanned:
04799 /// - id, Class
04800 /// - object *
04801 /// - __strong anything
04802 ///
04803 /// 2. When ForStrongLayout is false, following ivars are scanned:
04804 /// - __weak anything
04805 ///
04806 llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
04807   const ObjCImplementationDecl *OMD,
04808   bool ForStrongLayout) {
04809   bool hasUnion = false;
04810 
04811   llvm::Type *PtrTy = CGM.Int8PtrTy;
04812   if (CGM.getLangOpts().getGC() == LangOptions::NonGC &&
04813       !CGM.getLangOpts().ObjCAutoRefCount)
04814     return llvm::Constant::getNullValue(PtrTy);
04815 
04816   const ObjCInterfaceDecl *OI = OMD->getClassInterface();
04817   SmallVector<const FieldDecl*, 32> RecFields;
04818   if (CGM.getLangOpts().ObjCAutoRefCount) {
04819     for (const ObjCIvarDecl *IVD = OI->all_declared_ivar_begin(); 
04820          IVD; IVD = IVD->getNextIvar())
04821       RecFields.push_back(cast<FieldDecl>(IVD));
04822   }
04823   else {
04824     SmallVector<const ObjCIvarDecl*, 32> Ivars;
04825     CGM.getContext().DeepCollectObjCIvars(OI, true, Ivars);
04826 
04827     // FIXME: This is not ideal; we shouldn't have to do this copy.
04828     RecFields.append(Ivars.begin(), Ivars.end());
04829   }
04830 
04831   if (RecFields.empty())
04832     return llvm::Constant::getNullValue(PtrTy);
04833 
04834   SkipIvars.clear();
04835   IvarsInfo.clear();
04836 
04837   BuildAggrIvarLayout(OMD, 0, 0, RecFields, 0, ForStrongLayout, hasUnion);
04838   if (IvarsInfo.empty())
04839     return llvm::Constant::getNullValue(PtrTy);
04840   // Sort on byte position in case we encounterred a union nested in
04841   // the ivar list.
04842   if (hasUnion && !IvarsInfo.empty())
04843     std::sort(IvarsInfo.begin(), IvarsInfo.end());
04844   if (hasUnion && !SkipIvars.empty())
04845     std::sort(SkipIvars.begin(), SkipIvars.end());
04846   
04847   std::string BitMap;
04848   llvm::Constant *C = BuildIvarLayoutBitmap(BitMap);
04849   
04850    if (CGM.getLangOpts().ObjCGCBitmapPrint) {
04851     printf("\n%s ivar layout for class '%s': ",
04852            ForStrongLayout ? "strong" : "weak",
04853            OMD->getClassInterface()->getName().data());
04854     const unsigned char *s = (const unsigned char*)BitMap.c_str();
04855     for (unsigned i = 0, e = BitMap.size(); i < e; i++)
04856       if (!(s[i] & 0xf0))
04857         printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
04858       else
04859         printf("0x%x%s",  s[i], s[i] != 0 ? ", " : "");
04860     printf("\n");
04861   }
04862   return C;
04863 }
04864 
04865 llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
04866   llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
04867 
04868   // FIXME: Avoid std::string in "Sel.getAsString()"
04869   if (!Entry)
04870     Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
04871                llvm::ConstantDataArray::getString(VMContext, Sel.getAsString()),
04872                               ((ObjCABI == 2) ?
04873                                "__TEXT,__objc_methname,cstring_literals" :
04874                                "__TEXT,__cstring,cstring_literals"),
04875                               1, true);
04876 
04877   return getConstantGEP(VMContext, Entry, 0, 0);
04878 }
04879 
04880 // FIXME: Merge into a single cstring creation function.
04881 llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
04882   return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
04883 }
04884 
04885 llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
04886   std::string TypeStr;
04887   CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
04888 
04889   llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
04890 
04891   if (!Entry)
04892     Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
04893                          llvm::ConstantDataArray::getString(VMContext, TypeStr),
04894                               ((ObjCABI == 2) ?
04895                                "__TEXT,__objc_methtype,cstring_literals" :
04896                                "__TEXT,__cstring,cstring_literals"),
04897                               1, true);
04898 
04899   return getConstantGEP(VMContext, Entry, 0, 0);
04900 }
04901 
04902 llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D,
04903                                                   bool Extended) {
04904   std::string TypeStr;
04905   if (CGM.getContext().getObjCEncodingForMethodDecl(D, TypeStr, Extended))
04906     return 0;
04907 
04908   llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
04909 
04910   if (!Entry)
04911     Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
04912                          llvm::ConstantDataArray::getString(VMContext, TypeStr),
04913                               ((ObjCABI == 2) ?
04914                                "__TEXT,__objc_methtype,cstring_literals" :
04915                                "__TEXT,__cstring,cstring_literals"),
04916                               1, true);
04917 
04918   return getConstantGEP(VMContext, Entry, 0, 0);
04919 }
04920 
04921 // FIXME: Merge into a single cstring creation function.
04922 llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
04923   llvm::GlobalVariable *&Entry = PropertyNames[Ident];
04924 
04925   if (!Entry)
04926     Entry = CreateMetadataVar("\01L_OBJC_PROP_NAME_ATTR_",
04927                         llvm::ConstantDataArray::getString(VMContext,
04928                                                        Ident->getNameStart()),
04929                               "__TEXT,__cstring,cstring_literals",
04930                               1, true);
04931 
04932   return getConstantGEP(VMContext, Entry, 0, 0);
04933 }
04934 
04935 // FIXME: Merge into a single cstring creation function.
04936 // FIXME: This Decl should be more precise.
04937 llvm::Constant *
04938 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
04939                                        const Decl *Container) {
04940   std::string TypeStr;
04941   CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
04942   return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
04943 }
04944 
04945 void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
04946                                        const ObjCContainerDecl *CD,
04947                                        SmallVectorImpl<char> &Name) {
04948   llvm::raw_svector_ostream OS(Name);
04949   assert (CD && "Missing container decl in GetNameForMethod");
04950   OS << '\01' << (D->isInstanceMethod() ? '-' : '+')
04951      << '[' << CD->getName();
04952   if (const ObjCCategoryImplDecl *CID =
04953       dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext()))
04954     OS << '(' << *CID << ')';
04955   OS << ' ' << D->getSelector().getAsString() << ']';
04956 }
04957 
04958 void CGObjCMac::FinishModule() {
04959   EmitModuleInfo();
04960 
04961   // Emit the dummy bodies for any protocols which were referenced but
04962   // never defined.
04963   for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
04964          I = Protocols.begin(), e = Protocols.end(); I != e; ++I) {
04965     if (I->second->hasInitializer())
04966       continue;
04967 
04968     llvm::Constant *Values[5];
04969     Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
04970     Values[1] = GetClassName(I->first);
04971     Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
04972     Values[3] = Values[4] =
04973       llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
04974     assertPrivateName(I->second);
04975     I->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
04976                                                         Values));
04977     CGM.addCompilerUsedGlobal(I->second);
04978   }
04979 
04980   // Add assembler directives to add lazy undefined symbol references
04981   // for classes which are referenced but not defined. This is
04982   // important for correct linker interaction.
04983   //
04984   // FIXME: It would be nice if we had an LLVM construct for this.
04985   if (!LazySymbols.empty() || !DefinedSymbols.empty()) {
04986     SmallString<256> Asm;
04987     Asm += CGM.getModule().getModuleInlineAsm();
04988     if (!Asm.empty() && Asm.back() != '\n')
04989       Asm += '\n';
04990 
04991     llvm::raw_svector_ostream OS(Asm);
04992     for (llvm::SetVector<IdentifierInfo*>::iterator I = DefinedSymbols.begin(),
04993            e = DefinedSymbols.end(); I != e; ++I)
04994       OS << "\t.objc_class_name_" << (*I)->getName() << "=0\n"
04995          << "\t.globl .objc_class_name_" << (*I)->getName() << "\n";
04996     for (llvm::SetVector<IdentifierInfo*>::iterator I = LazySymbols.begin(),
04997          e = LazySymbols.end(); I != e; ++I) {
04998       OS << "\t.lazy_reference .objc_class_name_" << (*I)->getName() << "\n";
04999     }
05000 
05001     for (size_t i = 0, e = DefinedCategoryNames.size(); i < e; ++i) {
05002       OS << "\t.objc_category_name_" << DefinedCategoryNames[i] << "=0\n"
05003          << "\t.globl .objc_category_name_" << DefinedCategoryNames[i] << "\n";
05004     }
05005     
05006     CGM.getModule().setModuleInlineAsm(OS.str());
05007   }
05008 }
05009 
05010 CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
05011   : CGObjCCommonMac(cgm),
05012     ObjCTypes(cgm) {
05013   ObjCEmptyCacheVar = ObjCEmptyVtableVar = NULL;
05014   ObjCABI = 2;
05015 }
05016 
05017 /* *** */
05018 
05019 ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
05020   : VMContext(cgm.getLLVMContext()), CGM(cgm), ExternalProtocolPtrTy(0) 
05021 {
05022   CodeGen::CodeGenTypes &Types = CGM.getTypes();
05023   ASTContext &Ctx = CGM.getContext();
05024 
05025   ShortTy = Types.ConvertType(Ctx.ShortTy);
05026   IntTy = Types.ConvertType(Ctx.IntTy);
05027   LongTy = Types.ConvertType(Ctx.LongTy);
05028   LongLongTy = Types.ConvertType(Ctx.LongLongTy);
05029   Int8PtrTy = CGM.Int8PtrTy;
05030   Int8PtrPtrTy = CGM.Int8PtrPtrTy;
05031 
05032   // arm64 targets use "int" ivar offset variables. All others,
05033   // including OS X x86_64 and Windows x86_64, use "long" ivar offsets.
05034   if (CGM.getTarget().getTriple().getArch() == llvm::Triple::arm64)
05035     IvarOffsetVarTy = IntTy;
05036   else
05037     IvarOffsetVarTy = LongTy;
05038 
05039   ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
05040   PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
05041   SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
05042 
05043   // I'm not sure I like this. The implicit coordination is a bit
05044   // gross. We should solve this in a reasonable fashion because this
05045   // is a pretty common task (match some runtime data structure with
05046   // an LLVM data structure).
05047 
05048   // FIXME: This is leaked.
05049   // FIXME: Merge with rewriter code?
05050 
05051   // struct _objc_super {
05052   //   id self;
05053   //   Class cls;
05054   // }
05055   RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct,
05056                                       Ctx.getTranslationUnitDecl(),
05057                                       SourceLocation(), SourceLocation(),
05058                                       &Ctx.Idents.get("_objc_super"));
05059   RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(), 0,
05060                                 Ctx.getObjCIdType(), 0, 0, false, ICIS_NoInit));
05061   RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(), 0,
05062                                 Ctx.getObjCClassType(), 0, 0, false,
05063                                 ICIS_NoInit));
05064   RD->completeDefinition();
05065 
05066   SuperCTy = Ctx.getTagDeclType(RD);
05067   SuperPtrCTy = Ctx.getPointerType(SuperCTy);
05068 
05069   SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
05070   SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
05071 
05072   // struct _prop_t {
05073   //   char *name;
05074   //   char *attributes;
05075   // }
05076   PropertyTy = llvm::StructType::create("struct._prop_t",
05077                                         Int8PtrTy, Int8PtrTy, NULL);
05078 
05079   // struct _prop_list_t {
05080   //   uint32_t entsize;      // sizeof(struct _prop_t)
05081   //   uint32_t count_of_properties;
05082   //   struct _prop_t prop_list[count_of_properties];
05083   // }
05084   PropertyListTy =
05085     llvm::StructType::create("struct._prop_list_t", IntTy, IntTy,
05086                              llvm::ArrayType::get(PropertyTy, 0), NULL);
05087   // struct _prop_list_t *
05088   PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
05089 
05090   // struct _objc_method {
05091   //   SEL _cmd;
05092   //   char *method_type;
05093   //   char *_imp;
05094   // }
05095   MethodTy = llvm::StructType::create("struct._objc_method",
05096                                       SelectorPtrTy, Int8PtrTy, Int8PtrTy,
05097                                       NULL);
05098 
05099   // struct _objc_cache *
05100   CacheTy = llvm::StructType::create(VMContext, "struct._objc_cache");
05101   CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
05102     
05103 }
05104 
05105 ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
05106   : ObjCCommonTypesHelper(cgm) {
05107   // struct _objc_method_description {
05108   //   SEL name;
05109   //   char *types;
05110   // }
05111   MethodDescriptionTy =
05112     llvm::StructType::create("struct._objc_method_description",
05113                              SelectorPtrTy, Int8PtrTy, NULL);
05114 
05115   // struct _objc_method_description_list {
05116   //   int count;
05117   //   struct _objc_method_description[1];
05118   // }
05119   MethodDescriptionListTy =
05120     llvm::StructType::create("struct._objc_method_description_list",
05121                              IntTy,
05122                              llvm::ArrayType::get(MethodDescriptionTy, 0),NULL);
05123 
05124   // struct _objc_method_description_list *
05125   MethodDescriptionListPtrTy =
05126     llvm::PointerType::getUnqual(MethodDescriptionListTy);
05127 
05128   // Protocol description structures
05129 
05130   // struct _objc_protocol_extension {
05131   //   uint32_t size;  // sizeof(struct _objc_protocol_extension)
05132   //   struct _objc_method_description_list *optional_instance_methods;
05133   //   struct _objc_method_description_list *optional_class_methods;
05134   //   struct _objc_property_list *instance_properties;
05135   //   const char ** extendedMethodTypes;
05136   // }
05137   ProtocolExtensionTy =
05138     llvm::StructType::create("struct._objc_protocol_extension",
05139                              IntTy, MethodDescriptionListPtrTy,
05140                              MethodDescriptionListPtrTy, PropertyListPtrTy,
05141                              Int8PtrPtrTy, NULL);
05142 
05143   // struct _objc_protocol_extension *
05144   ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
05145 
05146   // Handle recursive construction of Protocol and ProtocolList types
05147 
05148   ProtocolTy =
05149     llvm::StructType::create(VMContext, "struct._objc_protocol");
05150 
05151   ProtocolListTy =
05152     llvm::StructType::create(VMContext, "struct._objc_protocol_list");
05153   ProtocolListTy->setBody(llvm::PointerType::getUnqual(ProtocolListTy),
05154                           LongTy,
05155                           llvm::ArrayType::get(ProtocolTy, 0),
05156                           NULL);
05157 
05158   // struct _objc_protocol {
05159   //   struct _objc_protocol_extension *isa;
05160   //   char *protocol_name;
05161   //   struct _objc_protocol **_objc_protocol_list;
05162   //   struct _objc_method_description_list *instance_methods;
05163   //   struct _objc_method_description_list *class_methods;
05164   // }
05165   ProtocolTy->setBody(ProtocolExtensionPtrTy, Int8PtrTy,
05166                       llvm::PointerType::getUnqual(ProtocolListTy),
05167                       MethodDescriptionListPtrTy,
05168                       MethodDescriptionListPtrTy,
05169                       NULL);
05170 
05171   // struct _objc_protocol_list *
05172   ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
05173 
05174   ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
05175 
05176   // Class description structures
05177 
05178   // struct _objc_ivar {
05179   //   char *ivar_name;
05180   //   char *ivar_type;
05181   //   int  ivar_offset;
05182   // }
05183   IvarTy = llvm::StructType::create("struct._objc_ivar",
05184                                     Int8PtrTy, Int8PtrTy, IntTy, NULL);
05185 
05186   // struct _objc_ivar_list *
05187   IvarListTy =
05188     llvm::StructType::create(VMContext, "struct._objc_ivar_list");
05189   IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
05190 
05191   // struct _objc_method_list *
05192   MethodListTy =
05193     llvm::StructType::create(VMContext, "struct._objc_method_list");
05194   MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
05195 
05196   // struct _objc_class_extension *
05197   ClassExtensionTy =
05198     llvm::StructType::create("struct._objc_class_extension",
05199                              IntTy, Int8PtrTy, PropertyListPtrTy, NULL);
05200   ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
05201 
05202   ClassTy = llvm::StructType::create(VMContext, "struct._objc_class");
05203 
05204   // struct _objc_class {
05205   //   Class isa;
05206   //   Class super_class;
05207   //   char *name;
05208   //   long version;
05209   //   long info;
05210   //   long instance_size;
05211   //   struct _objc_ivar_list *ivars;
05212   //   struct _objc_method_list *methods;
05213   //   struct _objc_cache *cache;
05214   //   struct _objc_protocol_list *protocols;
05215   //   char *ivar_layout;
05216   //   struct _objc_class_ext *ext;
05217   // };
05218   ClassTy->setBody(llvm::PointerType::getUnqual(ClassTy),
05219                    llvm::PointerType::getUnqual(ClassTy),
05220                    Int8PtrTy,
05221                    LongTy,
05222                    LongTy,
05223                    LongTy,
05224                    IvarListPtrTy,
05225                    MethodListPtrTy,
05226                    CachePtrTy,
05227                    ProtocolListPtrTy,
05228                    Int8PtrTy,
05229                    ClassExtensionPtrTy,
05230                    NULL);
05231 
05232   ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
05233 
05234   // struct _objc_category {
05235   //   char *category_name;
05236   //   char *class_name;
05237   //   struct _objc_method_list *instance_method;
05238   //   struct _objc_method_list *class_method;
05239   //   uint32_t size;  // sizeof(struct _objc_category)
05240   //   struct _objc_property_list *instance_properties;// category's @property
05241   // }
05242   CategoryTy =
05243     llvm::StructType::create("struct._objc_category",
05244                              Int8PtrTy, Int8PtrTy, MethodListPtrTy,
05245                              MethodListPtrTy, ProtocolListPtrTy,
05246                              IntTy, PropertyListPtrTy, NULL);
05247 
05248   // Global metadata structures
05249 
05250   // struct _objc_symtab {
05251   //   long sel_ref_cnt;
05252   //   SEL *refs;
05253   //   short cls_def_cnt;
05254   //   short cat_def_cnt;
05255   //   char *defs[cls_def_cnt + cat_def_cnt];
05256   // }
05257   SymtabTy =
05258     llvm::StructType::create("struct._objc_symtab",
05259                              LongTy, SelectorPtrTy, ShortTy, ShortTy,
05260                              llvm::ArrayType::get(Int8PtrTy, 0), NULL);
05261   SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
05262 
05263   // struct _objc_module {
05264   //   long version;
05265   //   long size;   // sizeof(struct _objc_module)
05266   //   char *name;
05267   //   struct _objc_symtab* symtab;
05268   //  }
05269   ModuleTy =
05270     llvm::StructType::create("struct._objc_module",
05271                              LongTy, LongTy, Int8PtrTy, SymtabPtrTy, NULL);
05272 
05273 
05274   // FIXME: This is the size of the setjmp buffer and should be target
05275   // specific. 18 is what's used on 32-bit X86.
05276   uint64_t SetJmpBufferSize = 18;
05277 
05278   // Exceptions
05279   llvm::Type *StackPtrTy = llvm::ArrayType::get(CGM.Int8PtrTy, 4);
05280 
05281   ExceptionDataTy =
05282     llvm::StructType::create("struct._objc_exception_data",
05283                              llvm::ArrayType::get(CGM.Int32Ty,SetJmpBufferSize),
05284                              StackPtrTy, NULL);
05285 
05286 }
05287 
05288 ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
05289   : ObjCCommonTypesHelper(cgm) {
05290   // struct _method_list_t {
05291   //   uint32_t entsize;  // sizeof(struct _objc_method)
05292   //   uint32_t method_count;
05293   //   struct _objc_method method_list[method_count];
05294   // }
05295   MethodListnfABITy =
05296     llvm::StructType::create("struct.__method_list_t", IntTy, IntTy,
05297                              llvm::ArrayType::get(MethodTy, 0), NULL);
05298   // struct method_list_t *
05299   MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
05300 
05301   // struct _protocol_t {
05302   //   id isa;  // NULL
05303   //   const char * const protocol_name;
05304   //   const struct _protocol_list_t * protocol_list; // super protocols
05305   //   const struct method_list_t * const instance_methods;
05306   //   const struct method_list_t * const class_methods;
05307   //   const struct method_list_t *optionalInstanceMethods;
05308   //   const struct method_list_t *optionalClassMethods;
05309   //   const struct _prop_list_t * properties;
05310   //   const uint32_t size;  // sizeof(struct _protocol_t)
05311   //   const uint32_t flags;  // = 0
05312   //   const char ** extendedMethodTypes;
05313   // }
05314 
05315   // Holder for struct _protocol_list_t *
05316   ProtocolListnfABITy =
05317     llvm::StructType::create(VMContext, "struct._objc_protocol_list");
05318 
05319   ProtocolnfABITy =
05320     llvm::StructType::create("struct._protocol_t", ObjectPtrTy, Int8PtrTy,
05321                              llvm::PointerType::getUnqual(ProtocolListnfABITy),
05322                              MethodListnfABIPtrTy, MethodListnfABIPtrTy,
05323                              MethodListnfABIPtrTy, MethodListnfABIPtrTy,
05324                              PropertyListPtrTy, IntTy, IntTy, Int8PtrPtrTy,
05325                              NULL);
05326 
05327   // struct _protocol_t*
05328   ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
05329 
05330   // struct _protocol_list_t {
05331   //   long protocol_count;   // Note, this is 32/64 bit
05332   //   struct _protocol_t *[protocol_count];
05333   // }
05334   ProtocolListnfABITy->setBody(LongTy,
05335                                llvm::ArrayType::get(ProtocolnfABIPtrTy, 0),
05336                                NULL);
05337 
05338   // struct _objc_protocol_list*
05339   ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
05340 
05341   // struct _ivar_t {
05342   //   unsigned [long] int *offset;  // pointer to ivar offset location
05343   //   char *name;
05344   //   char *type;
05345   //   uint32_t alignment;
05346   //   uint32_t size;
05347   // }
05348   IvarnfABITy = llvm::StructType::create(
05349       "struct._ivar_t", llvm::PointerType::getUnqual(IvarOffsetVarTy),
05350       Int8PtrTy, Int8PtrTy, IntTy, IntTy, NULL);
05351 
05352   // struct _ivar_list_t {
05353   //   uint32 entsize;  // sizeof(struct _ivar_t)
05354   //   uint32 count;
05355   //   struct _iver_t list[count];
05356   // }
05357   IvarListnfABITy =
05358     llvm::StructType::create("struct._ivar_list_t", IntTy, IntTy,
05359                              llvm::ArrayType::get(IvarnfABITy, 0), NULL);
05360 
05361   IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
05362 
05363   // struct _class_ro_t {
05364   //   uint32_t const flags;
05365   //   uint32_t const instanceStart;
05366   //   uint32_t const instanceSize;
05367   //   uint32_t const reserved;  // only when building for 64bit targets
05368   //   const uint8_t * const ivarLayout;
05369   //   const char *const name;
05370   //   const struct _method_list_t * const baseMethods;
05371   //   const struct _objc_protocol_list *const baseProtocols;
05372   //   const struct _ivar_list_t *const ivars;
05373   //   const uint8_t * const weakIvarLayout;
05374   //   const struct _prop_list_t * const properties;
05375   // }
05376 
05377   // FIXME. Add 'reserved' field in 64bit abi mode!
05378   ClassRonfABITy = llvm::StructType::create("struct._class_ro_t",
05379                                             IntTy, IntTy, IntTy, Int8PtrTy,
05380                                             Int8PtrTy, MethodListnfABIPtrTy,
05381                                             ProtocolListnfABIPtrTy,
05382                                             IvarListnfABIPtrTy,
05383                                             Int8PtrTy, PropertyListPtrTy, NULL);
05384 
05385   // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
05386   llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
05387   ImpnfABITy = llvm::FunctionType::get(ObjectPtrTy, params, false)
05388                  ->getPointerTo();
05389 
05390   // struct _class_t {
05391   //   struct _class_t *isa;
05392   //   struct _class_t * const superclass;
05393   //   void *cache;
05394   //   IMP *vtable;
05395   //   struct class_ro_t *ro;
05396   // }
05397 
05398   ClassnfABITy = llvm::StructType::create(VMContext, "struct._class_t");
05399   ClassnfABITy->setBody(llvm::PointerType::getUnqual(ClassnfABITy),
05400                         llvm::PointerType::getUnqual(ClassnfABITy),
05401                         CachePtrTy,
05402                         llvm::PointerType::getUnqual(ImpnfABITy),
05403                         llvm::PointerType::getUnqual(ClassRonfABITy),
05404                         NULL);
05405 
05406   // LLVM for struct _class_t *
05407   ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
05408 
05409   // struct _category_t {
05410   //   const char * const name;
05411   //   struct _class_t *const cls;
05412   //   const struct _method_list_t * const instance_methods;
05413   //   const struct _method_list_t * const class_methods;
05414   //   const struct _protocol_list_t * const protocols;
05415   //   const struct _prop_list_t * const properties;
05416   // }
05417   CategorynfABITy = llvm::StructType::create("struct._category_t",
05418                                              Int8PtrTy, ClassnfABIPtrTy,
05419                                              MethodListnfABIPtrTy,
05420                                              MethodListnfABIPtrTy,
05421                                              ProtocolListnfABIPtrTy,
05422                                              PropertyListPtrTy,
05423                                              NULL);
05424 
05425   // New types for nonfragile abi messaging.
05426   CodeGen::CodeGenTypes &Types = CGM.getTypes();
05427   ASTContext &Ctx = CGM.getContext();
05428 
05429   // MessageRefTy - LLVM for:
05430   // struct _message_ref_t {
05431   //   IMP messenger;
05432   //   SEL name;
05433   // };
05434 
05435   // First the clang type for struct _message_ref_t
05436   RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct,
05437                                       Ctx.getTranslationUnitDecl(),
05438                                       SourceLocation(), SourceLocation(),
05439                                       &Ctx.Idents.get("_message_ref_t"));
05440   RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(), 0,
05441                                 Ctx.VoidPtrTy, 0, 0, false, ICIS_NoInit));
05442   RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(), 0,
05443                                 Ctx.getObjCSelType(), 0, 0, false,
05444                                 ICIS_NoInit));
05445   RD->completeDefinition();
05446 
05447   MessageRefCTy = Ctx.getTagDeclType(RD);
05448   MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
05449   MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
05450 
05451   // MessageRefPtrTy - LLVM for struct _message_ref_t*
05452   MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
05453 
05454   // SuperMessageRefTy - LLVM for:
05455   // struct _super_message_ref_t {
05456   //   SUPER_IMP messenger;
05457   //   SEL name;
05458   // };
05459   SuperMessageRefTy =
05460     llvm::StructType::create("struct._super_message_ref_t",
05461                              ImpnfABITy, SelectorPtrTy, NULL);
05462 
05463   // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
05464   SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
05465     
05466 
05467   // struct objc_typeinfo {
05468   //   const void** vtable; // objc_ehtype_vtable + 2
05469   //   const char*  name;    // c++ typeinfo string
05470   //   Class        cls;
05471   // };
05472   EHTypeTy =
05473     llvm::StructType::create("struct._objc_typeinfo",
05474                              llvm::PointerType::getUnqual(Int8PtrTy),
05475                              Int8PtrTy, ClassnfABIPtrTy, NULL);
05476   EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
05477 }
05478 
05479 llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
05480   FinishNonFragileABIModule();
05481 
05482   return NULL;
05483 }
05484 
05485 void CGObjCNonFragileABIMac::
05486 AddModuleClassList(ArrayRef<llvm::GlobalValue*> Container,
05487                    const char *SymbolName,
05488                    const char *SectionName) {
05489   unsigned NumClasses = Container.size();
05490 
05491   if (!NumClasses)
05492     return;
05493 
05494   SmallVector<llvm::Constant*, 8> Symbols(NumClasses);
05495   for (unsigned i=0; i<NumClasses; i++)
05496     Symbols[i] = llvm::ConstantExpr::getBitCast(Container[i],
05497                                                 ObjCTypes.Int8PtrTy);
05498   llvm::Constant *Init =
05499     llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
05500                                                   Symbols.size()),
05501                              Symbols);
05502 
05503   llvm::GlobalVariable *GV =
05504     new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
05505                              llvm::GlobalValue::PrivateLinkage,
05506                              Init,
05507                              SymbolName);
05508   assertPrivateName(GV);
05509   GV->setAlignment(CGM.getDataLayout().getABITypeAlignment(Init->getType()));
05510   GV->setSection(SectionName);
05511   CGM.addCompilerUsedGlobal(GV);
05512 }
05513 
05514 void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
05515   // nonfragile abi has no module definition.
05516 
05517   // Build list of all implemented class addresses in array
05518   // L_OBJC_LABEL_CLASS_$.
05519 
05520   for (unsigned i=0, NumClasses=ImplementedClasses.size(); i<NumClasses; i++) {
05521     const ObjCInterfaceDecl *ID = ImplementedClasses[i];
05522     assert(ID);
05523     if (ObjCImplementationDecl *IMP = ID->getImplementation())
05524       // We are implementing a weak imported interface. Give it external linkage
05525       if (ID->isWeakImported() && !IMP->isWeakImported())
05526         DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
05527   }
05528   
05529   AddModuleClassList(DefinedClasses,
05530                      "\01L_OBJC_LABEL_CLASS_$",
05531                      "__DATA, __objc_classlist, regular, no_dead_strip");
05532 
05533   AddModuleClassList(DefinedNonLazyClasses,
05534                      "\01L_OBJC_LABEL_NONLAZY_CLASS_$",
05535                      "__DATA, __objc_nlclslist, regular, no_dead_strip");
05536 
05537   // Build list of all implemented category addresses in array
05538   // L_OBJC_LABEL_CATEGORY_$.
05539   AddModuleClassList(DefinedCategories,
05540                      "\01L_OBJC_LABEL_CATEGORY_$",
05541                      "__DATA, __objc_catlist, regular, no_dead_strip");
05542   AddModuleClassList(DefinedNonLazyCategories,
05543                      "\01L_OBJC_LABEL_NONLAZY_CATEGORY_$",
05544                      "__DATA, __objc_nlcatlist, regular, no_dead_strip");
05545 
05546   EmitImageInfo();
05547 }
05548 
05549 /// isVTableDispatchedSelector - Returns true if SEL is not in the list of
05550 /// VTableDispatchMethods; false otherwise. What this means is that
05551 /// except for the 19 selectors in the list, we generate 32bit-style
05552 /// message dispatch call for all the rest.
05553 bool CGObjCNonFragileABIMac::isVTableDispatchedSelector(Selector Sel) {
05554   // At various points we've experimented with using vtable-based
05555   // dispatch for all methods.
05556   switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
05557   case CodeGenOptions::Legacy:
05558     return false;
05559   case CodeGenOptions::NonLegacy:
05560     return true;
05561   case CodeGenOptions::Mixed:
05562     break;
05563   }
05564 
05565   // If so, see whether this selector is in the white-list of things which must
05566   // use the new dispatch convention. We lazily build a dense set for this.
05567   if (VTableDispatchMethods.empty()) {
05568     VTableDispatchMethods.insert(GetNullarySelector("alloc"));
05569     VTableDispatchMethods.insert(GetNullarySelector("class"));
05570     VTableDispatchMethods.insert(GetNullarySelector("self"));
05571     VTableDispatchMethods.insert(GetNullarySelector("isFlipped"));
05572     VTableDispatchMethods.insert(GetNullarySelector("length"));
05573     VTableDispatchMethods.insert(GetNullarySelector("count"));
05574 
05575     // These are vtable-based if GC is disabled.
05576     // Optimistically use vtable dispatch for hybrid compiles.
05577     if (CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
05578       VTableDispatchMethods.insert(GetNullarySelector("retain"));
05579       VTableDispatchMethods.insert(GetNullarySelector("release"));
05580       VTableDispatchMethods.insert(GetNullarySelector("autorelease"));
05581     }
05582 
05583     VTableDispatchMethods.insert(GetUnarySelector("allocWithZone"));
05584     VTableDispatchMethods.insert(GetUnarySelector("isKindOfClass"));
05585     VTableDispatchMethods.insert(GetUnarySelector("respondsToSelector"));
05586     VTableDispatchMethods.insert(GetUnarySelector("objectForKey"));
05587     VTableDispatchMethods.insert(GetUnarySelector("objectAtIndex"));
05588     VTableDispatchMethods.insert(GetUnarySelector("isEqualToString"));
05589     VTableDispatchMethods.insert(GetUnarySelector("isEqual"));
05590 
05591     // These are vtable-based if GC is enabled.
05592     // Optimistically use vtable dispatch for hybrid compiles.
05593     if (CGM.getLangOpts().getGC() != LangOptions::NonGC) {
05594       VTableDispatchMethods.insert(GetNullarySelector("hash"));
05595       VTableDispatchMethods.insert(GetUnarySelector("addObject"));
05596     
05597       // "countByEnumeratingWithState:objects:count"
05598       IdentifierInfo *KeyIdents[] = {
05599         &CGM.getContext().Idents.get("countByEnumeratingWithState"),
05600         &CGM.getContext().Idents.get("objects"),
05601         &CGM.getContext().Idents.get("count")
05602       };
05603       VTableDispatchMethods.insert(
05604         CGM.getContext().Selectors.getSelector(3, KeyIdents));
05605     }
05606   }
05607 
05608   return VTableDispatchMethods.count(Sel);
05609 }
05610 
05611 /// BuildClassRoTInitializer - generate meta-data for:
05612 /// struct _class_ro_t {
05613 ///   uint32_t const flags;
05614 ///   uint32_t const instanceStart;
05615 ///   uint32_t const instanceSize;
05616 ///   uint32_t const reserved;  // only when building for 64bit targets
05617 ///   const uint8_t * const ivarLayout;
05618 ///   const char *const name;
05619 ///   const struct _method_list_t * const baseMethods;
05620 ///   const struct _protocol_list_t *const baseProtocols;
05621 ///   const struct _ivar_list_t *const ivars;
05622 ///   const uint8_t * const weakIvarLayout;
05623 ///   const struct _prop_list_t * const properties;
05624 /// }
05625 ///
05626 llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
05627   unsigned flags,
05628   unsigned InstanceStart,
05629   unsigned InstanceSize,
05630   const ObjCImplementationDecl *ID) {
05631   std::string ClassName = ID->getNameAsString();
05632   llvm::Constant *Values[10]; // 11 for 64bit targets!
05633 
05634   if (CGM.getLangOpts().ObjCAutoRefCount)
05635     flags |= NonFragileABI_Class_CompiledByARC;
05636 
05637   Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
05638   Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
05639   Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
05640   // FIXME. For 64bit targets add 0 here.
05641   Values[ 3] = (flags & NonFragileABI_Class_Meta)
05642     ? GetIvarLayoutName(0, ObjCTypes)
05643     : BuildIvarLayout(ID, true);
05644   Values[ 4] = GetClassName(ID->getIdentifier());
05645   // const struct _method_list_t * const baseMethods;
05646   std::vector<llvm::Constant*> Methods;
05647   std::string MethodListName("\01l_OBJC_$_");
05648   if (flags & NonFragileABI_Class_Meta) {
05649     MethodListName += "CLASS_METHODS_" + ID->getNameAsString();
05650     for (const auto *I : ID->class_methods())
05651       // Class methods should always be defined.
05652       Methods.push_back(GetMethodConstant(I));
05653   } else {
05654     MethodListName += "INSTANCE_METHODS_" + ID->getNameAsString();
05655     for (const auto *I : ID->instance_methods())
05656       // Instance methods should always be defined.
05657       Methods.push_back(GetMethodConstant(I));
05658 
05659     for (const auto *PID : ID->property_impls()) {
05660       if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
05661         ObjCPropertyDecl *PD = PID->getPropertyDecl();
05662 
05663         if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
05664           if (llvm::Constant *C = GetMethodConstant(MD))
05665             Methods.push_back(C);
05666         if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
05667           if (llvm::Constant *C = GetMethodConstant(MD))
05668             Methods.push_back(C);
05669       }
05670     }
05671   }
05672   Values[ 5] = EmitMethodList(MethodListName,
05673                               "__DATA, __objc_const", Methods);
05674 
05675   const ObjCInterfaceDecl *OID = ID->getClassInterface();
05676   assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
05677   Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
05678                                 + OID->getName(),
05679                                 OID->all_referenced_protocol_begin(),
05680                                 OID->all_referenced_protocol_end());
05681 
05682   if (flags & NonFragileABI_Class_Meta) {
05683     Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
05684     Values[ 8] = GetIvarLayoutName(0, ObjCTypes);
05685     Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
05686   } else {
05687     Values[ 7] = EmitIvarList(ID);
05688     Values[ 8] = BuildIvarLayout(ID, false);
05689     Values[ 9] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getName(),
05690                                   ID, ID->getClassInterface(), ObjCTypes);
05691   }
05692   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
05693                                                    Values);
05694   llvm::GlobalVariable *CLASS_RO_GV =
05695     new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassRonfABITy, false,
05696                              llvm::GlobalValue::PrivateLinkage,
05697                              Init,
05698                              (flags & NonFragileABI_Class_Meta) ?
05699                              std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
05700                              std::string("\01l_OBJC_CLASS_RO_$_")+ClassName);
05701   assertPrivateName(CLASS_RO_GV);
05702   CLASS_RO_GV->setAlignment(
05703     CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ClassRonfABITy));
05704   CLASS_RO_GV->setSection("__DATA, __objc_const");
05705   return CLASS_RO_GV;
05706 
05707 }
05708 
05709 /// BuildClassMetaData - This routine defines that to-level meta-data
05710 /// for the given ClassName for:
05711 /// struct _class_t {
05712 ///   struct _class_t *isa;
05713 ///   struct _class_t * const superclass;
05714 ///   void *cache;
05715 ///   IMP *vtable;
05716 ///   struct class_ro_t *ro;
05717 /// }
05718 ///
05719 llvm::GlobalVariable *CGObjCNonFragileABIMac::BuildClassMetaData(
05720     std::string &ClassName, llvm::Constant *IsAGV, llvm::Constant *SuperClassGV,
05721     llvm::Constant *ClassRoGV, bool HiddenVisibility, bool Weak) {
05722   llvm::Constant *Values[] = {
05723     IsAGV,
05724     SuperClassGV,
05725     ObjCEmptyCacheVar,  // &ObjCEmptyCacheVar
05726     ObjCEmptyVtableVar, // &ObjCEmptyVtableVar
05727     ClassRoGV           // &CLASS_RO_GV
05728   };
05729   if (!Values[1])
05730     Values[1] = llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
05731   if (!Values[3])
05732     Values[3] = llvm::Constant::getNullValue(
05733                   llvm::PointerType::getUnqual(ObjCTypes.ImpnfABITy));
05734   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
05735                                                    Values);
05736   llvm::GlobalVariable *GV = GetClassGlobal(ClassName, Weak);
05737   GV->setInitializer(Init);
05738   GV->setSection("__DATA, __objc_data");
05739   GV->setAlignment(
05740     CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ClassnfABITy));
05741   if (HiddenVisibility)
05742     GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
05743   return GV;
05744 }
05745 
05746 bool
05747 CGObjCNonFragileABIMac::ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
05748   return OD->getClassMethod(GetNullarySelector("load")) != 0;
05749 }
05750 
05751 void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
05752                                               uint32_t &InstanceStart,
05753                                               uint32_t &InstanceSize) {
05754   const ASTRecordLayout &RL =
05755     CGM.getContext().getASTObjCImplementationLayout(OID);
05756 
05757   // InstanceSize is really instance end.
05758   InstanceSize = RL.getDataSize().getQuantity();
05759 
05760   // If there are no fields, the start is the same as the end.
05761   if (!RL.getFieldCount())
05762     InstanceStart = InstanceSize;
05763   else
05764     InstanceStart = RL.getFieldOffset(0) / CGM.getContext().getCharWidth();
05765 }
05766 
05767 void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
05768   std::string ClassName = ID->getNameAsString();
05769   if (!ObjCEmptyCacheVar) {
05770     ObjCEmptyCacheVar = new llvm::GlobalVariable(
05771       CGM.getModule(),
05772       ObjCTypes.CacheTy,
05773       false,
05774       llvm::GlobalValue::ExternalLinkage,
05775       0,
05776       "_objc_empty_cache");
05777     
05778     // Make this entry NULL for any iOS device target, any iOS simulator target,
05779     // OS X with deployment target 10.9 or later.
05780     const llvm::Triple &Triple = CGM.getTarget().getTriple();
05781     if (Triple.isiOS() || (Triple.isMacOSX() && !Triple.isMacOSXVersionLT(10, 9)))
05782       // This entry will be null.
05783       ObjCEmptyVtableVar = 0;
05784     else
05785       ObjCEmptyVtableVar = new llvm::GlobalVariable(
05786                                                     CGM.getModule(),
05787                                                     ObjCTypes.ImpnfABITy,
05788                                                     false,
05789                                                     llvm::GlobalValue::ExternalLinkage,
05790                                                     0,
05791                                                     "_objc_empty_vtable");
05792   }
05793   assert(ID->getClassInterface() &&
05794          "CGObjCNonFragileABIMac::GenerateClass - class is 0");
05795   // FIXME: Is this correct (that meta class size is never computed)?
05796   uint32_t InstanceStart =
05797     CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassnfABITy);
05798   uint32_t InstanceSize = InstanceStart;
05799   uint32_t flags = NonFragileABI_Class_Meta;
05800   std::string ObjCMetaClassName(getMetaclassSymbolPrefix());
05801   std::string ObjCClassName(getClassSymbolPrefix());
05802 
05803   llvm::GlobalVariable *SuperClassGV, *IsAGV;
05804 
05805   // Build the flags for the metaclass.
05806   bool classIsHidden =
05807     ID->getClassInterface()->getVisibility() == HiddenVisibility;
05808   if (classIsHidden)
05809     flags |= NonFragileABI_Class_Hidden;
05810 
05811   // FIXME: why is this flag set on the metaclass?
05812   // ObjC metaclasses have no fields and don't really get constructed.
05813   if (ID->hasNonZeroConstructors() || ID->hasDestructors()) {
05814     flags |= NonFragileABI_Class_HasCXXStructors;
05815     if (!ID->hasNonZeroConstructors())
05816       flags |= NonFragileABI_Class_HasCXXDestructorOnly;  
05817   }
05818 
05819   if (!ID->getClassInterface()->getSuperClass()) {
05820     // class is root
05821     flags |= NonFragileABI_Class_Root;
05822     SuperClassGV = GetClassGlobal(ObjCClassName + ClassName,
05823                                   ID->getClassInterface()->isWeakImported());
05824     IsAGV = GetClassGlobal(ObjCMetaClassName + ClassName,
05825                            ID->getClassInterface()->isWeakImported());
05826 
05827     // We are implementing a weak imported interface. Give it external
05828     // linkage.
05829     if (!ID->isWeakImported() && ID->getClassInterface()->isWeakImported())
05830       IsAGV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
05831   } else {
05832     // Has a root. Current class is not a root.
05833     const ObjCInterfaceDecl *Root = ID->getClassInterface();
05834     while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
05835       Root = Super;
05836     IsAGV = GetClassGlobal(ObjCMetaClassName + Root->getNameAsString(),
05837                            Root->isWeakImported());
05838     // work on super class metadata symbol.
05839     std::string SuperClassName =
05840       ObjCMetaClassName + 
05841         ID->getClassInterface()->getSuperClass()->getNameAsString();
05842     SuperClassGV = GetClassGlobal(
05843         SuperClassName,
05844         ID->getClassInterface()->getSuperClass()->isWeakImported());
05845   }
05846   llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
05847                                                                InstanceStart,
05848                                                                InstanceSize,ID);
05849   std::string TClassName = ObjCMetaClassName + ClassName;
05850   llvm::GlobalVariable *MetaTClass = BuildClassMetaData(
05851       TClassName, IsAGV, SuperClassGV, CLASS_RO_GV, classIsHidden,
05852       ID->isWeakImported());
05853   DefinedMetaClasses.push_back(MetaTClass);
05854 
05855   // Metadata for the class
05856   flags = 0;
05857   if (classIsHidden)
05858     flags |= NonFragileABI_Class_Hidden;
05859 
05860   if (ID->hasNonZeroConstructors() || ID->hasDestructors()) {
05861     flags |= NonFragileABI_Class_HasCXXStructors;
05862 
05863     // Set a flag to enable a runtime optimization when a class has
05864     // fields that require destruction but which don't require
05865     // anything except zero-initialization during construction.  This
05866     // is most notably true of __strong and __weak types, but you can
05867     // also imagine there being C++ types with non-trivial default
05868     // constructors that merely set all fields to null.
05869     if (!ID->hasNonZeroConstructors())
05870       flags |= NonFragileABI_Class_HasCXXDestructorOnly;
05871   }
05872 
05873   if (hasObjCExceptionAttribute(CGM.getContext(), ID->getClassInterface()))
05874     flags |= NonFragileABI_Class_Exception;
05875 
05876   if (!ID->getClassInterface()->getSuperClass()) {
05877     flags |= NonFragileABI_Class_Root;
05878     SuperClassGV = 0;
05879   } else {
05880     // Has a root. Current class is not a root.
05881     std::string RootClassName =
05882       ID->getClassInterface()->getSuperClass()->getNameAsString();
05883     SuperClassGV = GetClassGlobal(
05884         ObjCClassName + RootClassName,
05885         ID->getClassInterface()->getSuperClass()->isWeakImported());
05886   }
05887   GetClassSizeInfo(ID, InstanceStart, InstanceSize);
05888   CLASS_RO_GV = BuildClassRoTInitializer(flags,
05889                                          InstanceStart,
05890                                          InstanceSize,
05891                                          ID);
05892 
05893   TClassName = ObjCClassName + ClassName;
05894   llvm::GlobalVariable *ClassMD =
05895     BuildClassMetaData(TClassName, MetaTClass, SuperClassGV, CLASS_RO_GV,
05896                        classIsHidden,
05897                        ID->getClassInterface()->isWeakImported());
05898   DefinedClasses.push_back(ClassMD);
05899   ImplementedClasses.push_back(ID->getClassInterface());
05900 
05901   // Determine if this class is also "non-lazy".
05902   if (ImplementationIsNonLazy(ID))
05903     DefinedNonLazyClasses.push_back(ClassMD);
05904 
05905   // Force the definition of the EHType if necessary.
05906   if (flags & NonFragileABI_Class_Exception)
05907     GetInterfaceEHType(ID->getClassInterface(), true);
05908   // Make sure method definition entries are all clear for next implementation.
05909   MethodDefinitions.clear();
05910 }
05911 
05912 /// GenerateProtocolRef - This routine is called to generate code for
05913 /// a protocol reference expression; as in:
05914 /// @code
05915 ///   @protocol(Proto1);
05916 /// @endcode
05917 /// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
05918 /// which will hold address of the protocol meta-data.
05919 ///
05920 llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CodeGenFunction &CGF,
05921                                                          const ObjCProtocolDecl *PD) {
05922 
05923   // This routine is called for @protocol only. So, we must build definition
05924   // of protocol's meta-data (not a reference to it!)
05925   //
05926   llvm::Constant *Init =
05927     llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
05928                                    ObjCTypes.getExternalProtocolPtrTy());
05929 
05930   std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
05931   ProtocolName += PD->getName();
05932 
05933   llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
05934   if (PTGV)
05935     return CGF.Builder.CreateLoad(PTGV);
05936   PTGV = new llvm::GlobalVariable(
05937     CGM.getModule(),
05938     Init->getType(), false,
05939     llvm::GlobalValue::WeakAnyLinkage,
05940     Init,
05941     ProtocolName);
05942   PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
05943   PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
05944   CGM.addCompilerUsedGlobal(PTGV);
05945   return CGF.Builder.CreateLoad(PTGV);
05946 }
05947 
05948 /// GenerateCategory - Build metadata for a category implementation.
05949 /// struct _category_t {
05950 ///   const char * const name;
05951 ///   struct _class_t *const cls;
05952 ///   const struct _method_list_t * const instance_methods;
05953 ///   const struct _method_list_t * const class_methods;
05954 ///   const struct _protocol_list_t * const protocols;
05955 ///   const struct _prop_list_t * const properties;
05956 /// }
05957 ///
05958 void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
05959   const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
05960   const char *Prefix = "\01l_OBJC_$_CATEGORY_";
05961   std::string ExtCatName(Prefix + Interface->getNameAsString()+
05962                          "_$_" + OCD->getNameAsString());
05963   std::string ExtClassName(getClassSymbolPrefix() +
05964                            Interface->getNameAsString());
05965 
05966   llvm::Constant *Values[6];
05967   Values[0] = GetClassName(OCD->getIdentifier());
05968   // meta-class entry symbol
05969   llvm::GlobalVariable *ClassGV =
05970       GetClassGlobal(ExtClassName, Interface->isWeakImported());
05971 
05972   Values[1] = ClassGV;
05973   std::vector<llvm::Constant*> Methods;
05974   std::string MethodListName(Prefix);
05975   MethodListName += "INSTANCE_METHODS_" + Interface->getNameAsString() +
05976     "_$_" + OCD->getNameAsString();
05977 
05978   for (const auto *I : OCD->instance_methods())
05979     // Instance methods should always be defined.
05980     Methods.push_back(GetMethodConstant(I));
05981 
05982   Values[2] = EmitMethodList(MethodListName,
05983                              "__DATA, __objc_const",
05984                              Methods);
05985 
05986   MethodListName = Prefix;
05987   MethodListName += "CLASS_METHODS_" + Interface->getNameAsString() + "_$_" +
05988     OCD->getNameAsString();
05989   Methods.clear();
05990   for (const auto *I : OCD->class_methods())
05991     // Class methods should always be defined.
05992     Methods.push_back(GetMethodConstant(I));
05993 
05994   Values[3] = EmitMethodList(MethodListName,
05995                              "__DATA, __objc_const",
05996                              Methods);
05997   const ObjCCategoryDecl *Category =
05998     Interface->FindCategoryDeclaration(OCD->getIdentifier());
05999   if (Category) {
06000     SmallString<256> ExtName;
06001     llvm::raw_svector_ostream(ExtName) << Interface->getName() << "_$_"
06002                                        << OCD->getName();
06003     Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
06004                                  + Interface->getName() + "_$_"
06005                                  + Category->getName(),
06006                                  Category->protocol_begin(),
06007                                  Category->protocol_end());
06008     Values[5] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(),
06009                                  OCD, Category, ObjCTypes);
06010   } else {
06011     Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
06012     Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
06013   }
06014 
06015   llvm::Constant *Init =
06016     llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
06017                               Values);
06018   llvm::GlobalVariable *GCATV
06019     = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.CategorynfABITy,
06020                                false,
06021                                llvm::GlobalValue::PrivateLinkage,
06022                                Init,
06023                                ExtCatName);
06024   assertPrivateName(GCATV);
06025   GCATV->setAlignment(
06026     CGM.getDataLayout().getABITypeAlignment(ObjCTypes.CategorynfABITy));
06027   GCATV->setSection("__DATA, __objc_const");
06028   CGM.addCompilerUsedGlobal(GCATV);
06029   DefinedCategories.push_back(GCATV);
06030 
06031   // Determine if this category is also "non-lazy".
06032   if (ImplementationIsNonLazy(OCD))
06033     DefinedNonLazyCategories.push_back(GCATV);
06034   // method definition entries must be clear for next implementation.
06035   MethodDefinitions.clear();
06036 }
06037 
06038 /// GetMethodConstant - Return a struct objc_method constant for the
06039 /// given method if it has been defined. The result is null if the
06040 /// method has not been defined. The return value has type MethodPtrTy.
06041 llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
06042   const ObjCMethodDecl *MD) {
06043   llvm::Function *Fn = GetMethodDefinition(MD);
06044   if (!Fn)
06045     return 0;
06046 
06047   llvm::Constant *Method[] = {
06048     llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
06049                                    ObjCTypes.SelectorPtrTy),
06050     GetMethodVarType(MD),
06051     llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy)
06052   };
06053   return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
06054 }
06055 
06056 /// EmitMethodList - Build meta-data for method declarations
06057 /// struct _method_list_t {
06058 ///   uint32_t entsize;  // sizeof(struct _objc_method)
06059 ///   uint32_t method_count;
06060 ///   struct _objc_method method_list[method_count];
06061 /// }
06062 ///
06063 llvm::Constant *
06064 CGObjCNonFragileABIMac::EmitMethodList(Twine Name,
06065                                        const char *Section,
06066                                        ArrayRef<llvm::Constant*> Methods) {
06067   // Return null for empty list.
06068   if (Methods.empty())
06069     return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
06070 
06071   llvm::Constant *Values[3];
06072   // sizeof(struct _objc_method)
06073   unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.MethodTy);
06074   Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
06075   // method_count
06076   Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
06077   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
06078                                              Methods.size());
06079   Values[2] = llvm::ConstantArray::get(AT, Methods);
06080   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
06081 
06082   llvm::GlobalVariable *GV =
06083     new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
06084                              llvm::GlobalValue::PrivateLinkage, Init, Name);
06085   assertPrivateName(GV);
06086   GV->setAlignment(CGM.getDataLayout().getABITypeAlignment(Init->getType()));
06087   GV->setSection(Section);
06088   CGM.addCompilerUsedGlobal(GV);
06089   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListnfABIPtrTy);
06090 }
06091 
06092 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
06093 /// the given ivar.
06094 llvm::GlobalVariable *
06095 CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
06096                                                const ObjCIvarDecl *Ivar) {
06097   const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();
06098   std::string Name = "OBJC_IVAR_$_" + Container->getNameAsString() +
06099     '.' + Ivar->getNameAsString();
06100   llvm::GlobalVariable *IvarOffsetGV =
06101     CGM.getModule().getGlobalVariable(Name);
06102   if (!IvarOffsetGV)
06103     IvarOffsetGV = new llvm::GlobalVariable(
06104         CGM.getModule(), ObjCTypes.IvarOffsetVarTy, false,
06105         llvm::GlobalValue::ExternalLinkage, 0, Name);
06106   return IvarOffsetGV;
06107 }
06108 
06109 llvm::Constant *
06110 CGObjCNonFragileABIMac::EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
06111                                           const ObjCIvarDecl *Ivar,
06112                                           unsigned long int Offset) {
06113   llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
06114   IvarOffsetGV->setInitializer(
06115       llvm::ConstantInt::get(ObjCTypes.IvarOffsetVarTy, Offset));
06116   IvarOffsetGV->setAlignment(
06117       CGM.getDataLayout().getABITypeAlignment(ObjCTypes.IvarOffsetVarTy));
06118 
06119   // FIXME: This matches gcc, but shouldn't the visibility be set on the use as
06120   // well (i.e., in ObjCIvarOffsetVariable).
06121   if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
06122       Ivar->getAccessControl() == ObjCIvarDecl::Package ||
06123       ID->getVisibility() == HiddenVisibility)
06124     IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
06125   else
06126     IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
06127   IvarOffsetGV->setSection("__DATA, __objc_ivar");
06128   return IvarOffsetGV;
06129 }
06130 
06131 /// EmitIvarList - Emit the ivar list for the given
06132 /// implementation. The return value has type
06133 /// IvarListnfABIPtrTy.
06134 ///  struct _ivar_t {
06135 ///   unsigned [long] int *offset;  // pointer to ivar offset location
06136 ///   char *name;
06137 ///   char *type;
06138 ///   uint32_t alignment;
06139 ///   uint32_t size;
06140 /// }
06141 /// struct _ivar_list_t {
06142 ///   uint32 entsize;  // sizeof(struct _ivar_t)
06143 ///   uint32 count;
06144 ///   struct _iver_t list[count];
06145 /// }
06146 ///
06147 
06148 llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
06149   const ObjCImplementationDecl *ID) {
06150 
06151   std::vector<llvm::Constant*> Ivars;
06152 
06153   const ObjCInterfaceDecl *OID = ID->getClassInterface();
06154   assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
06155 
06156   // FIXME. Consolidate this with similar code in GenerateClass.
06157 
06158   for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin(); 
06159        IVD; IVD = IVD->getNextIvar()) {
06160     // Ignore unnamed bit-fields.
06161     if (!IVD->getDeclName())
06162       continue;
06163     llvm::Constant *Ivar[5];
06164     Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
06165                                 ComputeIvarBaseOffset(CGM, ID, IVD));
06166     Ivar[1] = GetMethodVarName(IVD->getIdentifier());
06167     Ivar[2] = GetMethodVarType(IVD);
06168     llvm::Type *FieldTy =
06169       CGM.getTypes().ConvertTypeForMem(IVD->getType());
06170     unsigned Size = CGM.getDataLayout().getTypeAllocSize(FieldTy);
06171     unsigned Align = CGM.getContext().getPreferredTypeAlign(
06172       IVD->getType().getTypePtr()) >> 3;
06173     Align = llvm::Log2_32(Align);
06174     Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
06175     // NOTE. Size of a bitfield does not match gcc's, because of the
06176     // way bitfields are treated special in each. But I am told that
06177     // 'size' for bitfield ivars is ignored by the runtime so it does
06178     // not matter.  If it matters, there is enough info to get the
06179     // bitfield right!
06180     Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
06181     Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
06182   }
06183   // Return null for empty list.
06184   if (Ivars.empty())
06185     return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
06186 
06187   llvm::Constant *Values[3];
06188   unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.IvarnfABITy);
06189   Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
06190   Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
06191   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
06192                                              Ivars.size());
06193   Values[2] = llvm::ConstantArray::get(AT, Ivars);
06194   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
06195   const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
06196   llvm::GlobalVariable *GV =
06197     new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
06198                              llvm::GlobalValue::PrivateLinkage,
06199                              Init,
06200                              Prefix + OID->getName());
06201   assertPrivateName(GV);
06202   GV->setAlignment(
06203     CGM.getDataLayout().getABITypeAlignment(Init->getType()));
06204   GV->setSection("__DATA, __objc_const");
06205 
06206   CGM.addCompilerUsedGlobal(GV);
06207   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListnfABIPtrTy);
06208 }
06209 
06210 llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
06211   const ObjCProtocolDecl *PD) {
06212   llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
06213 
06214   if (!Entry) {
06215     // We use the initializer as a marker of whether this is a forward
06216     // reference or not. At module finalization we add the empty
06217     // contents for protocols which were referenced but never defined.
06218     Entry =
06219         new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy,
06220                                  false, llvm::GlobalValue::WeakAnyLinkage, 0,
06221                                  "\01l_OBJC_PROTOCOL_$_" + PD->getName());
06222     Entry->setSection("__DATA,__datacoal_nt,coalesced");
06223   }
06224 
06225   return Entry;
06226 }
06227 
06228 /// GetOrEmitProtocol - Generate the protocol meta-data:
06229 /// @code
06230 /// struct _protocol_t {
06231 ///   id isa;  // NULL
06232 ///   const char * const protocol_name;
06233 ///   const struct _protocol_list_t * protocol_list; // super protocols
06234 ///   const struct method_list_t * const instance_methods;
06235 ///   const struct method_list_t * const class_methods;
06236 ///   const struct method_list_t *optionalInstanceMethods;
06237 ///   const struct method_list_t *optionalClassMethods;
06238 ///   const struct _prop_list_t * properties;
06239 ///   const uint32_t size;  // sizeof(struct _protocol_t)
06240 ///   const uint32_t flags;  // = 0
06241 ///   const char ** extendedMethodTypes;
06242 /// }
06243 /// @endcode
06244 ///
06245 
06246 llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
06247   const ObjCProtocolDecl *PD) {
06248   llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()];
06249 
06250   // Early exit if a defining object has already been generated.
06251   if (Entry && Entry->hasInitializer())
06252     return Entry;
06253 
06254   // Use the protocol definition, if there is one.
06255   if (const ObjCProtocolDecl *Def = PD->getDefinition())
06256     PD = Def;
06257   
06258   // Construct method lists.
06259   std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
06260   std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
06261   std::vector<llvm::Constant*> MethodTypesExt, OptMethodTypesExt;
06262   for (const auto *MD : PD->instance_methods()) {
06263     llvm::Constant *C = GetMethodDescriptionConstant(MD);
06264     if (!C)
06265       return GetOrEmitProtocolRef(PD);
06266     
06267     if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
06268       OptInstanceMethods.push_back(C);
06269       OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
06270     } else {
06271       InstanceMethods.push_back(C);
06272       MethodTypesExt.push_back(GetMethodVarType(MD, true));
06273     }
06274   }
06275 
06276   for (const auto *MD : PD->class_methods()) {
06277     llvm::Constant *C = GetMethodDescriptionConstant(MD);
06278     if (!C)
06279       return GetOrEmitProtocolRef(PD);
06280 
06281     if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
06282       OptClassMethods.push_back(C);
06283       OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
06284     } else {
06285       ClassMethods.push_back(C);
06286       MethodTypesExt.push_back(GetMethodVarType(MD, true));
06287     }
06288   }
06289 
06290   MethodTypesExt.insert(MethodTypesExt.end(),
06291                         OptMethodTypesExt.begin(), OptMethodTypesExt.end());
06292 
06293   llvm::Constant *Values[11];
06294   // isa is NULL
06295   Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
06296   Values[1] = GetClassName(PD->getIdentifier());
06297   Values[2] = EmitProtocolList("\01l_OBJC_$_PROTOCOL_REFS_" + PD->getName(),
06298                                PD->protocol_begin(),
06299                                PD->protocol_end());
06300 
06301   Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
06302                              + PD->getName(),
06303                              "__DATA, __objc_const",
06304                              InstanceMethods);
06305   Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
06306                              + PD->getName(),
06307                              "__DATA, __objc_const",
06308                              ClassMethods);
06309   Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
06310                              + PD->getName(),
06311                              "__DATA, __objc_const",
06312                              OptInstanceMethods);
06313   Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
06314                              + PD->getName(),
06315                              "__DATA, __objc_const",
06316                              OptClassMethods);
06317   Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getName(),
06318                                0, PD, ObjCTypes);
06319   uint32_t Size =
06320     CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolnfABITy);
06321   Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
06322   Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
06323   Values[10] = EmitProtocolMethodTypes("\01l_OBJC_$_PROTOCOL_METHOD_TYPES_"
06324                                        + PD->getName(),
06325                                        MethodTypesExt, ObjCTypes);
06326   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
06327                                                    Values);
06328 
06329   if (Entry) {
06330     // Already created, update the initializer.
06331     assert(Entry->getLinkage() == llvm::GlobalValue::WeakAnyLinkage);
06332     Entry->setInitializer(Init);
06333   } else {
06334     Entry =
06335       new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy,
06336                                false, llvm::GlobalValue::WeakAnyLinkage, Init,
06337                                "\01l_OBJC_PROTOCOL_$_" + PD->getName());
06338     Entry->setAlignment(
06339       CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ProtocolnfABITy));
06340     Entry->setSection("__DATA,__datacoal_nt,coalesced");
06341 
06342     Protocols[PD->getIdentifier()] = Entry;
06343   }
06344   Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
06345   CGM.addCompilerUsedGlobal(Entry);
06346 
06347   // Use this protocol meta-data to build protocol list table in section
06348   // __DATA, __objc_protolist
06349   llvm::GlobalVariable *PTGV =
06350     new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABIPtrTy,
06351                              false, llvm::GlobalValue::WeakAnyLinkage, Entry,
06352                              "\01l_OBJC_LABEL_PROTOCOL_$_" + PD->getName());
06353   PTGV->setAlignment(
06354     CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
06355   PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
06356   PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
06357   CGM.addCompilerUsedGlobal(PTGV);
06358   return Entry;
06359 }
06360 
06361 /// EmitProtocolList - Generate protocol list meta-data:
06362 /// @code
06363 /// struct _protocol_list_t {
06364 ///   long protocol_count;   // Note, this is 32/64 bit
06365 ///   struct _protocol_t[protocol_count];
06366 /// }
06367 /// @endcode
06368 ///
06369 llvm::Constant *
06370 CGObjCNonFragileABIMac::EmitProtocolList(Twine Name,
06371                                       ObjCProtocolDecl::protocol_iterator begin,
06372                                       ObjCProtocolDecl::protocol_iterator end) {
06373   SmallVector<llvm::Constant *, 16> ProtocolRefs;
06374 
06375   // Just return null for empty protocol lists
06376   if (begin == end)
06377     return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
06378 
06379   // FIXME: We shouldn't need to do this lookup here, should we?
06380   SmallString<256> TmpName;
06381   Name.toVector(TmpName);
06382   llvm::GlobalVariable *GV =
06383     CGM.getModule().getGlobalVariable(TmpName.str(), true);
06384   if (GV)
06385     return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListnfABIPtrTy);
06386 
06387   for (; begin != end; ++begin)
06388     ProtocolRefs.push_back(GetProtocolRef(*begin));  // Implemented???
06389 
06390   // This list is null terminated.
06391   ProtocolRefs.push_back(llvm::Constant::getNullValue(
06392                            ObjCTypes.ProtocolnfABIPtrTy));
06393 
06394   llvm::Constant *Values[2];
06395   Values[0] =
06396     llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
06397   Values[1] =
06398     llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
06399                                                   ProtocolRefs.size()),
06400                              ProtocolRefs);
06401 
06402   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
06403   GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
06404                                 llvm::GlobalValue::PrivateLinkage,
06405                                 Init, Name);
06406   assertPrivateName(GV);
06407   GV->setSection("__DATA, __objc_const");
06408   GV->setAlignment(
06409     CGM.getDataLayout().getABITypeAlignment(Init->getType()));
06410   CGM.addCompilerUsedGlobal(GV);
06411   return llvm::ConstantExpr::getBitCast(GV,
06412                                         ObjCTypes.ProtocolListnfABIPtrTy);
06413 }
06414 
06415 /// GetMethodDescriptionConstant - This routine build following meta-data:
06416 /// struct _objc_method {
06417 ///   SEL _cmd;
06418 ///   char *method_type;
06419 ///   char *_imp;
06420 /// }
06421 
06422 llvm::Constant *
06423 CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
06424   llvm::Constant *Desc[3];
06425   Desc[0] =
06426     llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
06427                                    ObjCTypes.SelectorPtrTy);
06428   Desc[1] = GetMethodVarType(MD);
06429   if (!Desc[1])
06430     return 0;
06431   
06432   // Protocol methods have no implementation. So, this entry is always NULL.
06433   Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
06434   return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
06435 }
06436 
06437 /// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
06438 /// This code gen. amounts to generating code for:
06439 /// @code
06440 /// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
06441 /// @encode
06442 ///
06443 LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
06444                                                CodeGen::CodeGenFunction &CGF,
06445                                                QualType ObjectTy,
06446                                                llvm::Value *BaseValue,
06447                                                const ObjCIvarDecl *Ivar,
06448                                                unsigned CVRQualifiers) {
06449   ObjCInterfaceDecl *ID = ObjectTy->getAs<ObjCObjectType>()->getInterface();
06450   llvm::Value *Offset = EmitIvarOffset(CGF, ID, Ivar);
06451   return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
06452                                   Offset);
06453 }
06454 
06455 llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
06456   CodeGen::CodeGenFunction &CGF,
06457   const ObjCInterfaceDecl *Interface,
06458   const ObjCIvarDecl *Ivar) {
06459   llvm::Value *IvarOffsetValue = ObjCIvarOffsetVariable(Interface, Ivar);
06460   IvarOffsetValue = CGF.Builder.CreateLoad(IvarOffsetValue, "ivar");
06461   if (IsIvarOffsetKnownIdempotent(CGF, Ivar))
06462     cast<llvm::LoadInst>(IvarOffsetValue)
06463         ->setMetadata(CGM.getModule().getMDKindID("invariant.load"),
06464                       llvm::MDNode::get(VMContext, ArrayRef<llvm::Value *>()));
06465 
06466   // This could be 32bit int or 64bit integer depending on the architecture.
06467   // Cast it to 64bit integer value, if it is a 32bit integer ivar offset value
06468   //  as this is what caller always expectes.
06469   if (ObjCTypes.IvarOffsetVarTy == ObjCTypes.IntTy)
06470     IvarOffsetValue = CGF.Builder.CreateIntCast(
06471         IvarOffsetValue, ObjCTypes.LongTy, true, "ivar.conv");
06472   return IvarOffsetValue;
06473 }
06474 
06475 static void appendSelectorForMessageRefTable(std::string &buffer,
06476                                              Selector selector) {
06477   if (selector.isUnarySelector()) {
06478     buffer += selector.getNameForSlot(0);
06479     return;
06480   }
06481 
06482   for (unsigned i = 0, e = selector.getNumArgs(); i != e; ++i) {
06483     buffer += selector.getNameForSlot(i);
06484     buffer += '_';
06485   }
06486 }
06487 
06488 /// Emit a "v-table" message send.  We emit a weak hidden-visibility
06489 /// struct, initially containing the selector pointer and a pointer to
06490 /// a "fixup" variant of the appropriate objc_msgSend.  To call, we
06491 /// load and call the function pointer, passing the address of the
06492 /// struct as the second parameter.  The runtime determines whether
06493 /// the selector is currently emitted using vtable dispatch; if so, it
06494 /// substitutes a stub function which simply tail-calls through the
06495 /// appropriate vtable slot, and if not, it substitues a stub function
06496 /// which tail-calls objc_msgSend.  Both stubs adjust the selector
06497 /// argument to correctly point to the selector.
06498 RValue
06499 CGObjCNonFragileABIMac::EmitVTableMessageSend(CodeGenFunction &CGF,
06500                                               ReturnValueSlot returnSlot,
06501                                               QualType resultType,
06502                                               Selector selector,
06503                                               llvm::Value *arg0,
06504                                               QualType arg0Type,
06505                                               bool isSuper,
06506                                               const CallArgList &formalArgs,
06507                                               const ObjCMethodDecl *method) {
06508   // Compute the actual arguments.
06509   CallArgList args;
06510 
06511   // First argument: the receiver / super-call structure.
06512   if (!isSuper)
06513     arg0 = CGF.Builder.CreateBitCast(arg0, ObjCTypes.ObjectPtrTy);
06514   args.add(RValue::get(arg0), arg0Type);
06515 
06516   // Second argument: a pointer to the message ref structure.  Leave
06517   // the actual argument value blank for now.
06518   args.add(RValue::get(0), ObjCTypes.MessageRefCPtrTy);
06519 
06520   args.insert(args.end(), formalArgs.begin(), formalArgs.end());
06521 
06522   MessageSendInfo MSI = getMessageSendInfo(method, resultType, args);
06523 
06524   NullReturnState nullReturn;
06525 
06526   // Find the function to call and the mangled name for the message
06527   // ref structure.  Using a different mangled name wouldn't actually
06528   // be a problem; it would just be a waste.
06529   //
06530   // The runtime currently never uses vtable dispatch for anything
06531   // except normal, non-super message-sends.
06532   // FIXME: don't use this for that.
06533   llvm::Constant *fn = 0;
06534   std::string messageRefName("\01l_");
06535   if (CGM.ReturnSlotInterferesWithArgs(MSI.CallInfo)) {
06536     if (isSuper) {
06537       fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
06538       messageRefName += "objc_msgSendSuper2_stret_fixup";
06539     } else {
06540       nullReturn.init(CGF, arg0);
06541       fn = ObjCTypes.getMessageSendStretFixupFn();
06542       messageRefName += "objc_msgSend_stret_fixup";
06543     }
06544   } else if (!isSuper && CGM.ReturnTypeUsesFPRet(resultType)) {
06545     fn = ObjCTypes.getMessageSendFpretFixupFn();
06546     messageRefName += "objc_msgSend_fpret_fixup";
06547   } else {
06548     if (isSuper) {
06549       fn = ObjCTypes.getMessageSendSuper2FixupFn();
06550       messageRefName += "objc_msgSendSuper2_fixup";
06551     } else {
06552       fn = ObjCTypes.getMessageSendFixupFn();
06553       messageRefName += "objc_msgSend_fixup";
06554     }
06555   }
06556   assert(fn && "CGObjCNonFragileABIMac::EmitMessageSend");
06557   messageRefName += '_';
06558 
06559   // Append the selector name, except use underscores anywhere we
06560   // would have used colons.
06561   appendSelectorForMessageRefTable(messageRefName, selector);
06562 
06563   llvm::GlobalVariable *messageRef
06564     = CGM.getModule().getGlobalVariable(messageRefName);
06565   if (!messageRef) {
06566     // Build the message ref structure.
06567     llvm::Constant *values[] = { fn, GetMethodVarName(selector) };
06568     llvm::Constant *init = llvm::ConstantStruct::getAnon(values);
06569     messageRef = new llvm::GlobalVariable(CGM.getModule(),
06570                                           init->getType(),
06571                                           /*constant*/ false,
06572                                           llvm::GlobalValue::WeakAnyLinkage,
06573                                           init,
06574                                           messageRefName);
06575     messageRef->setVisibility(llvm::GlobalValue::HiddenVisibility);
06576     messageRef->setAlignment(16);
06577     messageRef->setSection("__DATA, __objc_msgrefs, coalesced");
06578   }
06579   
06580   bool requiresnullCheck = false;
06581   if (CGM.getLangOpts().ObjCAutoRefCount && method)
06582     for (const auto *ParamDecl : method->params()) {
06583       if (ParamDecl->hasAttr<NSConsumedAttr>()) {
06584         if (!nullReturn.NullBB)
06585           nullReturn.init(CGF, arg0);
06586         requiresnullCheck = true;
06587         break;
06588       }
06589     }
06590   
06591   llvm::Value *mref =
06592     CGF.Builder.CreateBitCast(messageRef, ObjCTypes.MessageRefPtrTy);
06593 
06594   // Update the message ref argument.
06595   args[1].RV = RValue::get(mref);
06596 
06597   // Load the function to call from the message ref table.
06598   llvm::Value *callee = CGF.Builder.CreateStructGEP(mref, 0);
06599   callee = CGF.Builder.CreateLoad(callee, "msgSend_fn");
06600 
06601   callee = CGF.Builder.CreateBitCast(callee, MSI.MessengerType);
06602 
06603   RValue result = CGF.EmitCall(MSI.CallInfo, callee, returnSlot, args);
06604   return nullReturn.complete(CGF, result, resultType, formalArgs, 
06605                              requiresnullCheck ? method : 0);
06606 }
06607 
06608 /// Generate code for a message send expression in the nonfragile abi.
06609 CodeGen::RValue
06610 CGObjCNonFragileABIMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
06611                                             ReturnValueSlot Return,
06612                                             QualType ResultType,
06613                                             Selector Sel,
06614                                             llvm::Value *Receiver,
06615                                             const CallArgList &CallArgs,
06616                                             const ObjCInterfaceDecl *Class,
06617                                             const ObjCMethodDecl *Method) {
06618   return isVTableDispatchedSelector(Sel)
06619     ? EmitVTableMessageSend(CGF, Return, ResultType, Sel,
06620                             Receiver, CGF.getContext().getObjCIdType(),
06621                             false, CallArgs, Method)
06622     : EmitMessageSend(CGF, Return, ResultType,
06623                       EmitSelector(CGF, Sel),
06624                       Receiver, CGF.getContext().getObjCIdType(),
06625                       false, CallArgs, Method, ObjCTypes);
06626 }
06627 
06628 llvm::GlobalVariable *
06629 CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name, bool Weak) {
06630   llvm::GlobalValue::LinkageTypes L =
06631       Weak ? llvm::GlobalValue::ExternalWeakLinkage
06632            : llvm::GlobalValue::ExternalLinkage;
06633 
06634   llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
06635 
06636   if (!GV)
06637     GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABITy,
06638                                   false, L, 0, Name);
06639 
06640   assert(GV->getLinkage() == L);
06641   return GV;
06642 }
06643 
06644 llvm::Value *CGObjCNonFragileABIMac::EmitClassRefFromId(CodeGenFunction &CGF,
06645                                                         IdentifierInfo *II,
06646                                                         bool Weak) {
06647   llvm::GlobalVariable *&Entry = ClassReferences[II];
06648   
06649   if (!Entry) {
06650     std::string ClassName(getClassSymbolPrefix() + II->getName().str());
06651     llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName, Weak);
06652     Entry =
06653     new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
06654                              false, llvm::GlobalValue::PrivateLinkage,
06655                              ClassGV,
06656                              "\01L_OBJC_CLASSLIST_REFERENCES_$_");
06657     Entry->setAlignment(
06658                         CGM.getDataLayout().getABITypeAlignment(
06659                                                                 ObjCTypes.ClassnfABIPtrTy));
06660     Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
06661     CGM.addCompilerUsedGlobal(Entry);
06662   }
06663   assertPrivateName(Entry);
06664   return CGF.Builder.CreateLoad(Entry);
06665 }
06666 
06667 llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CodeGenFunction &CGF,
06668                                                   const ObjCInterfaceDecl *ID) {
06669   return EmitClassRefFromId(CGF, ID->getIdentifier(), ID->isWeakImported());
06670 }
06671 
06672 llvm::Value *CGObjCNonFragileABIMac::EmitNSAutoreleasePoolClassRef(
06673                                                     CodeGenFunction &CGF) {
06674   IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
06675   return EmitClassRefFromId(CGF, II, false);
06676 }
06677 
06678 llvm::Value *
06679 CGObjCNonFragileABIMac::EmitSuperClassRef(CodeGenFunction &CGF,
06680                                           const ObjCInterfaceDecl *ID) {
06681   llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
06682 
06683   if (!Entry) {
06684     std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
06685     llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName,
06686                                                    ID->isWeakImported());
06687     Entry =
06688       new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
06689                                false, llvm::GlobalValue::PrivateLinkage,
06690                                ClassGV,
06691                                "\01L_OBJC_CLASSLIST_SUP_REFS_$_");
06692     Entry->setAlignment(
06693       CGM.getDataLayout().getABITypeAlignment(
06694         ObjCTypes.ClassnfABIPtrTy));
06695     Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
06696     CGM.addCompilerUsedGlobal(Entry);
06697   }
06698   assertPrivateName(Entry);
06699   return CGF.Builder.CreateLoad(Entry);
06700 }
06701 
06702 /// EmitMetaClassRef - Return a Value * of the address of _class_t
06703 /// meta-data
06704 ///
06705 llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CodeGenFunction &CGF,
06706                                                       const ObjCInterfaceDecl *ID) {
06707   llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
06708   if (!Entry) {
06709 
06710     std::string MetaClassName(getMetaclassSymbolPrefix() +
06711                               ID->getNameAsString());
06712     llvm::GlobalVariable *MetaClassGV = GetClassGlobal(MetaClassName);
06713     Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
06714                                      false, llvm::GlobalValue::PrivateLinkage,
06715                                      MetaClassGV,
06716                                      "\01L_OBJC_CLASSLIST_SUP_REFS_$_");
06717     Entry->setAlignment(
06718         CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ClassnfABIPtrTy));
06719 
06720     Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
06721     CGM.addCompilerUsedGlobal(Entry);
06722   }
06723 
06724   assertPrivateName(Entry);
06725   return CGF.Builder.CreateLoad(Entry);
06726 }
06727 
06728 /// GetClass - Return a reference to the class for the given interface
06729 /// decl.
06730 llvm::Value *CGObjCNonFragileABIMac::GetClass(CodeGenFunction &CGF,
06731                                               const ObjCInterfaceDecl *ID) {
06732   if (ID->isWeakImported()) {
06733     std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
06734     llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName, true);
06735     (void)ClassGV;
06736     assert(ClassGV->getLinkage() == llvm::GlobalValue::ExternalWeakLinkage);
06737   }
06738   
06739   return EmitClassRef(CGF, ID);
06740 }
06741 
06742 /// Generates a message send where the super is the receiver.  This is
06743 /// a message send to self with special delivery semantics indicating
06744 /// which class's method should be called.
06745 CodeGen::RValue
06746 CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
06747                                                  ReturnValueSlot Return,
06748                                                  QualType ResultType,
06749                                                  Selector Sel,
06750                                                  const ObjCInterfaceDecl *Class,
06751                                                  bool isCategoryImpl,
06752                                                  llvm::Value *Receiver,
06753                                                  bool IsClassMessage,
06754                                                  const CodeGen::CallArgList &CallArgs,
06755                                                  const ObjCMethodDecl *Method) {
06756   // ...
06757   // Create and init a super structure; this is a (receiver, class)
06758   // pair we will pass to objc_msgSendSuper.
06759   llvm::Value *ObjCSuper =
06760     CGF.CreateTempAlloca(ObjCTypes.SuperTy, "objc_super");
06761 
06762   llvm::Value *ReceiverAsObject =
06763     CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
06764   CGF.Builder.CreateStore(ReceiverAsObject,
06765                           CGF.Builder.CreateStructGEP(ObjCSuper, 0));
06766 
06767   // If this is a class message the metaclass is passed as the target.
06768   llvm::Value *Target;
06769   if (IsClassMessage)
06770       Target = EmitMetaClassRef(CGF, Class);
06771   else
06772     Target = EmitSuperClassRef(CGF, Class);
06773 
06774   // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
06775   // ObjCTypes types.
06776   llvm::Type *ClassTy =
06777     CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
06778   Target = CGF.Builder.CreateBitCast(Target, ClassTy);
06779   CGF.Builder.CreateStore(Target,
06780                           CGF.Builder.CreateStructGEP(ObjCSuper, 1));
06781 
06782   return (isVTableDispatchedSelector(Sel))
06783     ? EmitVTableMessageSend(CGF, Return, ResultType, Sel,
06784                             ObjCSuper, ObjCTypes.SuperPtrCTy,
06785                             true, CallArgs, Method)
06786     : EmitMessageSend(CGF, Return, ResultType,
06787                       EmitSelector(CGF, Sel),
06788                       ObjCSuper, ObjCTypes.SuperPtrCTy,
06789                       true, CallArgs, Method, ObjCTypes);
06790 }
06791 
06792 llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CodeGenFunction &CGF,
06793                                                   Selector Sel, bool lval) {
06794   llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
06795 
06796   if (!Entry) {
06797     llvm::Constant *Casted =
06798       llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
06799                                      ObjCTypes.SelectorPtrTy);
06800     Entry =
06801       new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.SelectorPtrTy, false,
06802                                llvm::GlobalValue::PrivateLinkage,
06803                                Casted, "\01L_OBJC_SELECTOR_REFERENCES_");
06804     Entry->setExternallyInitialized(true);
06805     Entry->setSection("__DATA, __objc_selrefs, literal_pointers, no_dead_strip");
06806     CGM.addCompilerUsedGlobal(Entry);
06807   }
06808   assertPrivateName(Entry);
06809 
06810   if (lval)
06811     return Entry;
06812   llvm::LoadInst* LI = CGF.Builder.CreateLoad(Entry);
06813   
06814   LI->setMetadata(CGM.getModule().getMDKindID("invariant.load"), 
06815                   llvm::MDNode::get(VMContext,
06816                                     ArrayRef<llvm::Value*>()));
06817   return LI;
06818 }
06819 /// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
06820 /// objc_assign_ivar (id src, id *dst, ptrdiff_t)
06821 ///
06822 void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
06823                                                 llvm::Value *src,
06824                                                 llvm::Value *dst,
06825                                                 llvm::Value *ivarOffset) {
06826   llvm::Type * SrcTy = src->getType();
06827   if (!isa<llvm::PointerType>(SrcTy)) {
06828     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
06829     assert(Size <= 8 && "does not support size > 8");
06830     src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
06831            : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
06832     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
06833   }
06834   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
06835   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
06836   llvm::Value *args[] = { src, dst, ivarOffset };
06837   CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args);
06838 }
06839 
06840 /// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
06841 /// objc_assign_strongCast (id src, id *dst)
06842 ///
06843 void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
06844   CodeGen::CodeGenFunction &CGF,
06845   llvm::Value *src, llvm::Value *dst) {
06846   llvm::Type * SrcTy = src->getType();
06847   if (!isa<llvm::PointerType>(SrcTy)) {
06848     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
06849     assert(Size <= 8 && "does not support size > 8");
06850     src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
06851            : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
06852     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
06853   }
06854   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
06855   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
06856   llvm::Value *args[] = { src, dst };
06857   CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(),
06858                               args, "weakassign");
06859 }
06860 
06861 void CGObjCNonFragileABIMac::EmitGCMemmoveCollectable(
06862   CodeGen::CodeGenFunction &CGF,
06863   llvm::Value *DestPtr,
06864   llvm::Value *SrcPtr,
06865   llvm::Value *Size) {
06866   SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
06867   DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
06868   llvm::Value *args[] = { DestPtr, SrcPtr, Size };
06869   CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args);
06870 }
06871 
06872 /// EmitObjCWeakRead - Code gen for loading value of a __weak
06873 /// object: objc_read_weak (id *src)
06874 ///
06875 llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
06876   CodeGen::CodeGenFunction &CGF,
06877   llvm::Value *AddrWeakObj) {
06878   llvm::Type* DestTy =
06879     cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
06880   AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
06881   llvm::Value *read_weak =
06882     CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(),
06883                                 AddrWeakObj, "weakread");
06884   read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
06885   return read_weak;
06886 }
06887 
06888 /// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
06889 /// objc_assign_weak (id src, id *dst)
06890 ///
06891 void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
06892                                                 llvm::Value *src, llvm::Value *dst) {
06893   llvm::Type * SrcTy = src->getType();
06894   if (!isa<llvm::PointerType>(SrcTy)) {
06895     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
06896     assert(Size <= 8 && "does not support size > 8");
06897     src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
06898            : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
06899     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
06900   }
06901   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
06902   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
06903   llvm::Value *args[] = { src, dst };
06904   CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(),
06905                               args, "weakassign");
06906 }
06907 
06908 /// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
06909 /// objc_assign_global (id src, id *dst)
06910 ///
06911 void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
06912                                           llvm::Value *src, llvm::Value *dst,
06913                                           bool threadlocal) {
06914   llvm::Type * SrcTy = src->getType();
06915   if (!isa<llvm::PointerType>(SrcTy)) {
06916     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
06917     assert(Size <= 8 && "does not support size > 8");
06918     src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
06919            : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
06920     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
06921   }
06922   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
06923   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
06924   llvm::Value *args[] = { src, dst };
06925   if (!threadlocal)
06926     CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(),
06927                                 args, "globalassign");
06928   else
06929     CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(),
06930                                 args, "threadlocalassign");
06931 }
06932 
06933 void
06934 CGObjCNonFragileABIMac::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
06935                                              const ObjCAtSynchronizedStmt &S) {
06936   EmitAtSynchronizedStmt(CGF, S,
06937       cast<llvm::Function>(ObjCTypes.getSyncEnterFn()),
06938       cast<llvm::Function>(ObjCTypes.getSyncExitFn()));
06939 }
06940 
06941 llvm::Constant *
06942 CGObjCNonFragileABIMac::GetEHType(QualType T) {
06943   // There's a particular fixed type info for 'id'.
06944   if (T->isObjCIdType() ||
06945       T->isObjCQualifiedIdType()) {
06946     llvm::Constant *IDEHType =
06947       CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
06948     if (!IDEHType)
06949       IDEHType =
06950         new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy,
06951                                  false,
06952                                  llvm::GlobalValue::ExternalLinkage,
06953                                  0, "OBJC_EHTYPE_id");
06954     return IDEHType;
06955   }
06956 
06957   // All other types should be Objective-C interface pointer types.
06958   const ObjCObjectPointerType *PT =
06959     T->getAs<ObjCObjectPointerType>();
06960   assert(PT && "Invalid @catch type.");
06961   const ObjCInterfaceType *IT = PT->getInterfaceType();
06962   assert(IT && "Invalid @catch type.");
06963   return GetInterfaceEHType(IT->getDecl(), false);
06964 }                                                  
06965 
06966 void CGObjCNonFragileABIMac::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
06967                                          const ObjCAtTryStmt &S) {
06968   EmitTryCatchStmt(CGF, S,
06969       cast<llvm::Function>(ObjCTypes.getObjCBeginCatchFn()),
06970       cast<llvm::Function>(ObjCTypes.getObjCEndCatchFn()),
06971       cast<llvm::Function>(ObjCTypes.getExceptionRethrowFn()));
06972 }
06973 
06974 /// EmitThrowStmt - Generate code for a throw statement.
06975 void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
06976                                            const ObjCAtThrowStmt &S,
06977                                            bool ClearInsertionPoint) {
06978   if (const Expr *ThrowExpr = S.getThrowExpr()) {
06979     llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
06980     Exception = CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
06981     CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionThrowFn(), Exception)
06982       .setDoesNotReturn();
06983   } else {
06984     CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionRethrowFn())
06985       .setDoesNotReturn();
06986   }
06987 
06988   CGF.Builder.CreateUnreachable();
06989   if (ClearInsertionPoint)
06990     CGF.Builder.ClearInsertionPoint();
06991 }
06992 
06993 llvm::Constant *
06994 CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
06995                                            bool ForDefinition) {
06996   llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
06997 
06998   // If we don't need a definition, return the entry if found or check
06999   // if we use an external reference.
07000   if (!ForDefinition) {
07001     if (Entry)
07002       return Entry;
07003 
07004     // If this type (or a super class) has the __objc_exception__
07005     // attribute, emit an external reference.
07006     if (hasObjCExceptionAttribute(CGM.getContext(), ID))
07007       return Entry =
07008         new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false,
07009                                  llvm::GlobalValue::ExternalLinkage,
07010                                  0,
07011                                  ("OBJC_EHTYPE_$_" +
07012                                   ID->getIdentifier()->getName()));
07013   }
07014 
07015   // Otherwise we need to either make a new entry or fill in the
07016   // initializer.
07017   assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
07018   std::string ClassName(getClassSymbolPrefix() + ID->getNameAsString());
07019   std::string VTableName = "objc_ehtype_vtable";
07020   llvm::GlobalVariable *VTableGV =
07021     CGM.getModule().getGlobalVariable(VTableName);
07022   if (!VTableGV)
07023     VTableGV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.Int8PtrTy,
07024                                         false,
07025                                         llvm::GlobalValue::ExternalLinkage,
07026                                         0, VTableName);
07027 
07028   llvm::Value *VTableIdx = llvm::ConstantInt::get(CGM.Int32Ty, 2);
07029 
07030   llvm::Constant *Values[] = {
07031     llvm::ConstantExpr::getGetElementPtr(VTableGV, VTableIdx),
07032     GetClassName(ID->getIdentifier()),
07033     GetClassGlobal(ClassName)
07034   };
07035   llvm::Constant *Init =
07036     llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
07037 
07038   llvm::GlobalValue::LinkageTypes L = ForDefinition
07039                                           ? llvm::GlobalValue::ExternalLinkage
07040                                           : llvm::GlobalValue::WeakAnyLinkage;
07041   if (Entry) {
07042     Entry->setInitializer(Init);
07043   } else {
07044     Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false,
07045                                      L,
07046                                      Init,
07047                                      ("OBJC_EHTYPE_$_" +
07048                                       ID->getIdentifier()->getName()));
07049   }
07050   assert(Entry->getLinkage() == L);
07051 
07052   if (ID->getVisibility() == HiddenVisibility)
07053     Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
07054   Entry->setAlignment(CGM.getDataLayout().getABITypeAlignment(
07055       ObjCTypes.EHTypeTy));
07056 
07057   if (ForDefinition)
07058     Entry->setSection("__DATA,__objc_const");
07059   else
07060     Entry->setSection("__DATA,__datacoal_nt,coalesced");
07061 
07062   return Entry;
07063 }
07064 
07065 /* *** */
07066 
07067 CodeGen::CGObjCRuntime *
07068 CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
07069   switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
07070   case ObjCRuntime::FragileMacOSX:
07071   return new CGObjCMac(CGM);
07072 
07073   case ObjCRuntime::MacOSX:
07074   case ObjCRuntime::iOS:
07075     return new CGObjCNonFragileABIMac(CGM);
07076 
07077   case ObjCRuntime::GNUstep:
07078   case ObjCRuntime::GCC:
07079   case ObjCRuntime::ObjFW:
07080     llvm_unreachable("these runtimes are not Mac runtimes");
07081   }
07082   llvm_unreachable("bad runtime");
07083 }