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::StringMap<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   /// runtime name (which may change via use of objc_runtime_name attribute on
00936   /// class or protocol definition. The return value has type char *.
00937   llvm::Constant *GetClassName(StringRef RuntimeName);
00938 
00939   llvm::Function *GetMethodDefinition(const ObjCMethodDecl *MD);
00940 
00941   /// BuildIvarLayout - Builds ivar layout bitmap for the class
00942   /// implementation for the __strong or __weak case.
00943   ///
00944   llvm::Constant *BuildIvarLayout(const ObjCImplementationDecl *OI,
00945                                   bool ForStrongLayout);
00946   
00947   llvm::Constant *BuildIvarLayoutBitmap(std::string &BitMap);
00948 
00949   void BuildAggrIvarRecordLayout(const RecordType *RT,
00950                                  unsigned int BytePos, bool ForStrongLayout,
00951                                  bool &HasUnion);
00952   void BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
00953                            const llvm::StructLayout *Layout,
00954                            const RecordDecl *RD,
00955                            ArrayRef<const FieldDecl*> RecFields,
00956                            unsigned int BytePos, bool ForStrongLayout,
00957                            bool &HasUnion);
00958   
00959   Qualifiers::ObjCLifetime getBlockCaptureLifetime(QualType QT, bool ByrefLayout);
00960   
00961   void UpdateRunSkipBlockVars(bool IsByref,
00962                               Qualifiers::ObjCLifetime LifeTime,
00963                               CharUnits FieldOffset,
00964                               CharUnits FieldSize);
00965   
00966   void BuildRCBlockVarRecordLayout(const RecordType *RT,
00967                                    CharUnits BytePos, bool &HasUnion,
00968                                    bool ByrefLayout=false);
00969   
00970   void BuildRCRecordLayout(const llvm::StructLayout *RecLayout,
00971                            const RecordDecl *RD,
00972                            ArrayRef<const FieldDecl*> RecFields,
00973                            CharUnits BytePos, bool &HasUnion,
00974                            bool ByrefLayout);
00975   
00976   uint64_t InlineLayoutInstruction(SmallVectorImpl<unsigned char> &Layout);
00977   
00978   llvm::Constant *getBitmapBlockLayout(bool ComputeByrefLayout);
00979   
00980 
00981   /// GetIvarLayoutName - Returns a unique constant for the given
00982   /// ivar layout bitmap.
00983   llvm::Constant *GetIvarLayoutName(IdentifierInfo *Ident,
00984                                     const ObjCCommonTypesHelper &ObjCTypes);
00985 
00986   /// EmitPropertyList - Emit the given property list. The return
00987   /// value has type PropertyListPtrTy.
00988   llvm::Constant *EmitPropertyList(Twine Name,
00989                                    const Decl *Container,
00990                                    const ObjCContainerDecl *OCD,
00991                                    const ObjCCommonTypesHelper &ObjCTypes);
00992 
00993   /// EmitProtocolMethodTypes - Generate the array of extended method type 
00994   /// strings. The return value has type Int8PtrPtrTy.
00995   llvm::Constant *EmitProtocolMethodTypes(Twine Name, 
00996                                           ArrayRef<llvm::Constant*> MethodTypes,
00997                                        const ObjCCommonTypesHelper &ObjCTypes);
00998 
00999   /// PushProtocolProperties - Push protocol's property on the input stack.
01000   void PushProtocolProperties(
01001     llvm::SmallPtrSet<const IdentifierInfo*, 16> &PropertySet,
01002     SmallVectorImpl<llvm::Constant*> &Properties,
01003     const Decl *Container,
01004     const ObjCProtocolDecl *Proto,
01005     const ObjCCommonTypesHelper &ObjCTypes);
01006 
01007   /// GetProtocolRef - Return a reference to the internal protocol
01008   /// description, creating an empty one if it has not been
01009   /// defined. The return value has type ProtocolPtrTy.
01010   llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
01011 
01012   /// CreateMetadataVar - Create a global variable with internal
01013   /// linkage for use by the Objective-C runtime.
01014   ///
01015   /// This is a convenience wrapper which not only creates the
01016   /// variable, but also sets the section and alignment and adds the
01017   /// global to the "llvm.used" list.
01018   ///
01019   /// \param Name - The variable name.
01020   /// \param Init - The variable initializer; this is also used to
01021   /// define the type of the variable.
01022   /// \param Section - The section the variable should go into, or empty.
01023   /// \param Align - The alignment for the variable, or 0.
01024   /// \param AddToUsed - Whether the variable should be added to
01025   /// "llvm.used".
01026   llvm::GlobalVariable *CreateMetadataVar(Twine Name, llvm::Constant *Init,
01027                                           StringRef Section, unsigned Align,
01028                                           bool AddToUsed);
01029 
01030   CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
01031                                   ReturnValueSlot Return,
01032                                   QualType ResultType,
01033                                   llvm::Value *Sel,
01034                                   llvm::Value *Arg0,
01035                                   QualType Arg0Ty,
01036                                   bool IsSuper,
01037                                   const CallArgList &CallArgs,
01038                                   const ObjCMethodDecl *OMD,
01039                                   const ObjCCommonTypesHelper &ObjCTypes);
01040 
01041   /// EmitImageInfo - Emit the image info marker used to encode some module
01042   /// level information.
01043   void EmitImageInfo();
01044 
01045 public:
01046   CGObjCCommonMac(CodeGen::CodeGenModule &cgm) :
01047     CGObjCRuntime(cgm), VMContext(cgm.getLLVMContext()) { }
01048 
01049   llvm::Constant *GenerateConstantString(const StringLiteral *SL) override;
01050 
01051   llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
01052                                  const ObjCContainerDecl *CD=nullptr) override;
01053 
01054   void GenerateProtocol(const ObjCProtocolDecl *PD) override;
01055 
01056   /// GetOrEmitProtocol - Get the protocol object for the given
01057   /// declaration, emitting it if necessary. The return value has type
01058   /// ProtocolPtrTy.
01059   virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD)=0;
01060 
01061   /// GetOrEmitProtocolRef - Get a forward reference to the protocol
01062   /// object for the given declaration, emitting it if needed. These
01063   /// forward references will be filled in with empty bodies if no
01064   /// definition is seen. The return value has type ProtocolPtrTy.
01065   virtual llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD)=0;
01066   llvm::Constant *BuildGCBlockLayout(CodeGen::CodeGenModule &CGM,
01067                                      const CGBlockInfo &blockInfo) override;
01068   llvm::Constant *BuildRCBlockLayout(CodeGen::CodeGenModule &CGM,
01069                                      const CGBlockInfo &blockInfo) override;
01070 
01071   llvm::Constant *BuildByrefLayout(CodeGen::CodeGenModule &CGM,
01072                                    QualType T) override;
01073 };
01074 
01075 class CGObjCMac : public CGObjCCommonMac {
01076 private:
01077   ObjCTypesHelper ObjCTypes;
01078 
01079   /// EmitModuleInfo - Another marker encoding module level
01080   /// information.
01081   void EmitModuleInfo();
01082 
01083   /// EmitModuleSymols - Emit module symbols, the list of defined
01084   /// classes and categories. The result has type SymtabPtrTy.
01085   llvm::Constant *EmitModuleSymbols();
01086 
01087   /// FinishModule - Write out global data structures at the end of
01088   /// processing a translation unit.
01089   void FinishModule();
01090 
01091   /// EmitClassExtension - Generate the class extension structure used
01092   /// to store the weak ivar layout and properties. The return value
01093   /// has type ClassExtensionPtrTy.
01094   llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
01095 
01096   /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
01097   /// for the given class.
01098   llvm::Value *EmitClassRef(CodeGenFunction &CGF,
01099                             const ObjCInterfaceDecl *ID);
01100   
01101   llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF,
01102                                   IdentifierInfo *II);
01103 
01104   llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
01105 
01106   /// EmitSuperClassRef - Emits reference to class's main metadata class.
01107   llvm::Value *EmitSuperClassRef(const ObjCInterfaceDecl *ID);
01108 
01109   /// EmitIvarList - Emit the ivar list for the given
01110   /// implementation. If ForClass is true the list of class ivars
01111   /// (i.e. metaclass ivars) is emitted, otherwise the list of
01112   /// interface ivars will be emitted. The return value has type
01113   /// IvarListPtrTy.
01114   llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
01115                                bool ForClass);
01116 
01117   /// EmitMetaClass - Emit a forward reference to the class structure
01118   /// for the metaclass of the given interface. The return value has
01119   /// type ClassPtrTy.
01120   llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
01121 
01122   /// EmitMetaClass - Emit a class structure for the metaclass of the
01123   /// given implementation. The return value has type ClassPtrTy.
01124   llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
01125                                 llvm::Constant *Protocols,
01126                                 ArrayRef<llvm::Constant*> Methods);
01127 
01128   llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
01129 
01130   llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
01131 
01132   /// EmitMethodList - Emit the method list for the given
01133   /// implementation. The return value has type MethodListPtrTy.
01134   llvm::Constant *EmitMethodList(Twine Name,
01135                                  const char *Section,
01136                                  ArrayRef<llvm::Constant*> Methods);
01137 
01138   /// EmitMethodDescList - Emit a method description list for a list of
01139   /// method declarations.
01140   ///  - TypeName: The name for the type containing the methods.
01141   ///  - IsProtocol: True iff these methods are for a protocol.
01142   ///  - ClassMethds: True iff these are class methods.
01143   ///  - Required: When true, only "required" methods are
01144   ///    listed. Similarly, when false only "optional" methods are
01145   ///    listed. For classes this should always be true.
01146   ///  - begin, end: The method list to output.
01147   ///
01148   /// The return value has type MethodDescriptionListPtrTy.
01149   llvm::Constant *EmitMethodDescList(Twine Name,
01150                                      const char *Section,
01151                                      ArrayRef<llvm::Constant*> Methods);
01152 
01153   /// GetOrEmitProtocol - Get the protocol object for the given
01154   /// declaration, emitting it if necessary. The return value has type
01155   /// ProtocolPtrTy.
01156   llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override;
01157 
01158   /// GetOrEmitProtocolRef - Get a forward reference to the protocol
01159   /// object for the given declaration, emitting it if needed. These
01160   /// forward references will be filled in with empty bodies if no
01161   /// definition is seen. The return value has type ProtocolPtrTy.
01162   llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) override;
01163 
01164   /// EmitProtocolExtension - Generate the protocol extension
01165   /// structure used to store optional instance and class methods, and
01166   /// protocol properties. The return value has type
01167   /// ProtocolExtensionPtrTy.
01168   llvm::Constant *
01169   EmitProtocolExtension(const ObjCProtocolDecl *PD,
01170                         ArrayRef<llvm::Constant*> OptInstanceMethods,
01171                         ArrayRef<llvm::Constant*> OptClassMethods,
01172                         ArrayRef<llvm::Constant*> MethodTypesExt);
01173 
01174   /// EmitProtocolList - Generate the list of referenced
01175   /// protocols. The return value has type ProtocolListPtrTy.
01176   llvm::Constant *EmitProtocolList(Twine Name,
01177                                    ObjCProtocolDecl::protocol_iterator begin,
01178                                    ObjCProtocolDecl::protocol_iterator end);
01179 
01180   /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
01181   /// for the given selector.
01182   llvm::Value *EmitSelector(CodeGenFunction &CGF, Selector Sel, 
01183                             bool lval=false);
01184 
01185 public:
01186   CGObjCMac(CodeGen::CodeGenModule &cgm);
01187 
01188   llvm::Function *ModuleInitFunction() override;
01189 
01190   CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
01191                                       ReturnValueSlot Return,
01192                                       QualType ResultType,
01193                                       Selector Sel, llvm::Value *Receiver,
01194                                       const CallArgList &CallArgs,
01195                                       const ObjCInterfaceDecl *Class,
01196                                       const ObjCMethodDecl *Method) override;
01197 
01198   CodeGen::RValue
01199   GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
01200                            ReturnValueSlot Return, QualType ResultType,
01201                            Selector Sel, const ObjCInterfaceDecl *Class,
01202                            bool isCategoryImpl, llvm::Value *Receiver,
01203                            bool IsClassMessage, const CallArgList &CallArgs,
01204                            const ObjCMethodDecl *Method) override;
01205 
01206   llvm::Value *GetClass(CodeGenFunction &CGF,
01207                         const ObjCInterfaceDecl *ID) override;
01208 
01209   llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
01210                            bool lval = false) override;
01211 
01212   /// The NeXT/Apple runtimes do not support typed selectors; just emit an
01213   /// untyped one.
01214   llvm::Value *GetSelector(CodeGenFunction &CGF,
01215                            const ObjCMethodDecl *Method) override;
01216 
01217   llvm::Constant *GetEHType(QualType T) override;
01218 
01219   void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
01220 
01221   void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
01222 
01223   void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override {}
01224 
01225   llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
01226                                    const ObjCProtocolDecl *PD) override;
01227 
01228   llvm::Constant *GetPropertyGetFunction() override;
01229   llvm::Constant *GetPropertySetFunction() override;
01230   llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
01231                                                   bool copy) override;
01232   llvm::Constant *GetGetStructFunction() override;
01233   llvm::Constant *GetSetStructFunction() override;
01234   llvm::Constant *GetCppAtomicObjectGetFunction() override;
01235   llvm::Constant *GetCppAtomicObjectSetFunction() override;
01236   llvm::Constant *EnumerationMutationFunction() override;
01237 
01238   void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
01239                    const ObjCAtTryStmt &S) override;
01240   void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
01241                             const ObjCAtSynchronizedStmt &S) override;
01242   void EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF, const Stmt &S);
01243   void EmitThrowStmt(CodeGen::CodeGenFunction &CGF, const ObjCAtThrowStmt &S,
01244                      bool ClearInsertionPoint=true) override;
01245   llvm::Value * EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
01246                                  llvm::Value *AddrWeakObj) override;
01247   void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
01248                           llvm::Value *src, llvm::Value *dst) override;
01249   void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
01250                             llvm::Value *src, llvm::Value *dest,
01251                             bool threadlocal = false) override;
01252   void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
01253                           llvm::Value *src, llvm::Value *dest,
01254                           llvm::Value *ivarOffset) override;
01255   void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
01256                                 llvm::Value *src, llvm::Value *dest) override;
01257   void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
01258                                 llvm::Value *dest, llvm::Value *src,
01259                                 llvm::Value *size) override;
01260 
01261   LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF, QualType ObjectTy,
01262                               llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
01263                               unsigned CVRQualifiers) override;
01264   llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
01265                               const ObjCInterfaceDecl *Interface,
01266                               const ObjCIvarDecl *Ivar) override;
01267 
01268   /// GetClassGlobal - Return the global variable for the Objective-C
01269   /// class of the given name.
01270   llvm::GlobalVariable *GetClassGlobal(const std::string &Name,
01271                                        bool Weak = false) override {
01272     llvm_unreachable("CGObjCMac::GetClassGlobal");
01273   }
01274 };
01275 
01276 class CGObjCNonFragileABIMac : public CGObjCCommonMac {
01277 private:
01278   ObjCNonFragileABITypesHelper ObjCTypes;
01279   llvm::GlobalVariable* ObjCEmptyCacheVar;
01280   llvm::GlobalVariable* ObjCEmptyVtableVar;
01281 
01282   /// SuperClassReferences - uniqued super class references.
01283   llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> SuperClassReferences;
01284 
01285   /// MetaClassReferences - uniqued meta class references.
01286   llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> MetaClassReferences;
01287 
01288   /// EHTypeReferences - uniqued class ehtype references.
01289   llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> EHTypeReferences;
01290 
01291   /// VTableDispatchMethods - List of methods for which we generate
01292   /// vtable-based message dispatch.
01293   llvm::DenseSet<Selector> VTableDispatchMethods;
01294 
01295   /// DefinedMetaClasses - List of defined meta-classes.
01296   std::vector<llvm::GlobalValue*> DefinedMetaClasses;
01297   
01298   /// isVTableDispatchedSelector - Returns true if SEL is a
01299   /// vtable-based selector.
01300   bool isVTableDispatchedSelector(Selector Sel);
01301 
01302   /// FinishNonFragileABIModule - Write out global data structures at the end of
01303   /// processing a translation unit.
01304   void FinishNonFragileABIModule();
01305 
01306   /// AddModuleClassList - Add the given list of class pointers to the
01307   /// module with the provided symbol and section names.
01308   void AddModuleClassList(ArrayRef<llvm::GlobalValue*> Container,
01309                           const char *SymbolName,
01310                           const char *SectionName);
01311 
01312   llvm::GlobalVariable * BuildClassRoTInitializer(unsigned flags,
01313                                               unsigned InstanceStart,
01314                                               unsigned InstanceSize,
01315                                               const ObjCImplementationDecl *ID);
01316   llvm::GlobalVariable * BuildClassMetaData(const std::string &ClassName,
01317                                             llvm::Constant *IsAGV,
01318                                             llvm::Constant *SuperClassGV,
01319                                             llvm::Constant *ClassRoGV,
01320                                             bool HiddenVisibility,
01321                                             bool Weak);
01322 
01323   llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
01324 
01325   llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
01326 
01327   /// EmitMethodList - Emit the method list for the given
01328   /// implementation. The return value has type MethodListnfABITy.
01329   llvm::Constant *EmitMethodList(Twine Name,
01330                                  const char *Section,
01331                                  ArrayRef<llvm::Constant*> Methods);
01332   /// EmitIvarList - Emit the ivar list for the given
01333   /// implementation. If ForClass is true the list of class ivars
01334   /// (i.e. metaclass ivars) is emitted, otherwise the list of
01335   /// interface ivars will be emitted. The return value has type
01336   /// IvarListnfABIPtrTy.
01337   llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID);
01338 
01339   llvm::Constant *EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
01340                                     const ObjCIvarDecl *Ivar,
01341                                     unsigned long int offset);
01342 
01343   /// GetOrEmitProtocol - Get the protocol object for the given
01344   /// declaration, emitting it if necessary. The return value has type
01345   /// ProtocolPtrTy.
01346   llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override;
01347 
01348   /// GetOrEmitProtocolRef - Get a forward reference to the protocol
01349   /// object for the given declaration, emitting it if needed. These
01350   /// forward references will be filled in with empty bodies if no
01351   /// definition is seen. The return value has type ProtocolPtrTy.
01352   llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) override;
01353 
01354   /// EmitProtocolList - Generate the list of referenced
01355   /// protocols. The return value has type ProtocolListPtrTy.
01356   llvm::Constant *EmitProtocolList(Twine Name,
01357                                    ObjCProtocolDecl::protocol_iterator begin,
01358                                    ObjCProtocolDecl::protocol_iterator end);
01359 
01360   CodeGen::RValue EmitVTableMessageSend(CodeGen::CodeGenFunction &CGF,
01361                                         ReturnValueSlot Return,
01362                                         QualType ResultType,
01363                                         Selector Sel,
01364                                         llvm::Value *Receiver,
01365                                         QualType Arg0Ty,
01366                                         bool IsSuper,
01367                                         const CallArgList &CallArgs,
01368                                         const ObjCMethodDecl *Method);
01369   
01370   /// GetClassGlobal - Return the global variable for the Objective-C
01371   /// class of the given name.
01372   llvm::GlobalVariable *GetClassGlobal(const std::string &Name,
01373                                        bool Weak = false) override;
01374 
01375   /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
01376   /// for the given class reference.
01377   llvm::Value *EmitClassRef(CodeGenFunction &CGF,
01378                             const ObjCInterfaceDecl *ID);
01379   
01380   llvm::Value *EmitClassRefFromId(CodeGenFunction &CGF,
01381                                   IdentifierInfo *II, bool Weak,
01382                                   const ObjCInterfaceDecl *ID);
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, bool Weak);
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(nullptr) {}
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 = nullptr;
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 = nullptr;
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 : nullptr);
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 = nullptr;
02073   const FieldDecl *LastFieldBitfieldOrUnnamed = nullptr;
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 = nullptr;
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->hasPrivateLinkage());
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->getObjCRuntimeNameAsString()),
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->hasPrivateLinkage());
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                                nullptr,
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(), nullptr,
02712                      PD, 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(), Init,
02727                            StringRef(), 0, true);
02728 }
02729 
02730 /*
02731   struct objc_protocol_list {
02732     struct objc_protocol_list *next;
02733     long count;
02734     Protocol *list[];
02735   };
02736 */
02737 llvm::Constant *
02738 CGObjCMac::EmitProtocolList(Twine Name,
02739                             ObjCProtocolDecl::protocol_iterator begin,
02740                             ObjCProtocolDecl::protocol_iterator end) {
02741   SmallVector<llvm::Constant *, 16> ProtocolRefs;
02742 
02743   for (; begin != end; ++begin)
02744     ProtocolRefs.push_back(GetProtocolRef(*begin));
02745 
02746   // Just return null for empty protocol lists
02747   if (ProtocolRefs.empty())
02748     return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
02749 
02750   // This list is null terminated.
02751   ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
02752 
02753   llvm::Constant *Values[3];
02754   // This field is only used by the runtime.
02755   Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
02756   Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy,
02757                                      ProtocolRefs.size() - 1);
02758   Values[2] =
02759     llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
02760                                                   ProtocolRefs.size()),
02761                              ProtocolRefs);
02762 
02763   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
02764   llvm::GlobalVariable *GV =
02765     CreateMetadataVar(Name, Init, "__OBJC,__cat_cls_meth,regular,no_dead_strip",
02766                       4, false);
02767   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
02768 }
02769 
02770 void CGObjCCommonMac::
02771 PushProtocolProperties(llvm::SmallPtrSet<const IdentifierInfo*,16> &PropertySet,
02772                        SmallVectorImpl<llvm::Constant *> &Properties,
02773                        const Decl *Container,
02774                        const ObjCProtocolDecl *Proto,
02775                        const ObjCCommonTypesHelper &ObjCTypes) {
02776   for (const auto *P : Proto->protocols()) 
02777     PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes);
02778   for (const auto *PD : Proto->properties()) {
02779     if (!PropertySet.insert(PD->getIdentifier()))
02780       continue;
02781     llvm::Constant *Prop[] = {
02782       GetPropertyName(PD->getIdentifier()),
02783       GetPropertyTypeString(PD, Container)
02784     };
02785     Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy, Prop));
02786   }
02787 }
02788 
02789 /*
02790   struct _objc_property {
02791     const char * const name;
02792     const char * const attributes;
02793   };
02794 
02795   struct _objc_property_list {
02796     uint32_t entsize; // sizeof (struct _objc_property)
02797     uint32_t prop_count;
02798     struct _objc_property[prop_count];
02799   };
02800 */
02801 llvm::Constant *CGObjCCommonMac::EmitPropertyList(Twine Name,
02802                                        const Decl *Container,
02803                                        const ObjCContainerDecl *OCD,
02804                                        const ObjCCommonTypesHelper &ObjCTypes) {
02805   SmallVector<llvm::Constant *, 16> Properties;
02806   llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
02807   for (const auto *PD : OCD->properties()) {
02808     PropertySet.insert(PD->getIdentifier());
02809     llvm::Constant *Prop[] = {
02810       GetPropertyName(PD->getIdentifier()),
02811       GetPropertyTypeString(PD, Container)
02812     };
02813     Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
02814                                                    Prop));
02815   }
02816   if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD)) {
02817     for (const auto *P : OID->all_referenced_protocols())
02818       PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes);
02819   }
02820   else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD)) {
02821     for (const auto *P : CD->protocols())
02822       PushProtocolProperties(PropertySet, Properties, Container, P, ObjCTypes);
02823   }
02824 
02825   // Return null for empty list.
02826   if (Properties.empty())
02827     return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
02828 
02829   unsigned PropertySize =
02830     CGM.getDataLayout().getTypeAllocSize(ObjCTypes.PropertyTy);
02831   llvm::Constant *Values[3];
02832   Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
02833   Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
02834   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
02835                                              Properties.size());
02836   Values[2] = llvm::ConstantArray::get(AT, Properties);
02837   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
02838 
02839   llvm::GlobalVariable *GV =
02840     CreateMetadataVar(Name, Init,
02841                       (ObjCABI == 2) ? "__DATA, __objc_const" :
02842                       "__OBJC,__property,regular,no_dead_strip",
02843                       (ObjCABI == 2) ? 8 : 4,
02844                       true);
02845   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.PropertyListPtrTy);
02846 }
02847 
02848 llvm::Constant *
02849 CGObjCCommonMac::EmitProtocolMethodTypes(Twine Name,
02850                                          ArrayRef<llvm::Constant*> MethodTypes,
02851                                          const ObjCCommonTypesHelper &ObjCTypes) {
02852   // Return null for empty list.
02853   if (MethodTypes.empty())
02854     return llvm::Constant::getNullValue(ObjCTypes.Int8PtrPtrTy);
02855 
02856   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
02857                                              MethodTypes.size());
02858   llvm::Constant *Init = llvm::ConstantArray::get(AT, MethodTypes);
02859 
02860   llvm::GlobalVariable *GV = CreateMetadataVar(
02861       Name, Init, (ObjCABI == 2) ? "__DATA, __objc_const" : StringRef(),
02862       (ObjCABI == 2) ? 8 : 4, true);
02863   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.Int8PtrPtrTy);
02864 }
02865 
02866 /*
02867   struct objc_method_description_list {
02868   int count;
02869   struct objc_method_description list[];
02870   };
02871 */
02872 llvm::Constant *
02873 CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
02874   llvm::Constant *Desc[] = {
02875     llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
02876                                    ObjCTypes.SelectorPtrTy),
02877     GetMethodVarType(MD)
02878   };
02879   if (!Desc[1])
02880     return nullptr;
02881 
02882   return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
02883                                    Desc);
02884 }
02885 
02886 llvm::Constant *
02887 CGObjCMac::EmitMethodDescList(Twine Name, const char *Section,
02888                               ArrayRef<llvm::Constant*> Methods) {
02889   // Return null for empty list.
02890   if (Methods.empty())
02891     return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
02892 
02893   llvm::Constant *Values[2];
02894   Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
02895   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
02896                                              Methods.size());
02897   Values[1] = llvm::ConstantArray::get(AT, Methods);
02898   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
02899 
02900   llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
02901   return llvm::ConstantExpr::getBitCast(GV,
02902                                         ObjCTypes.MethodDescriptionListPtrTy);
02903 }
02904 
02905 /*
02906   struct _objc_category {
02907   char *category_name;
02908   char *class_name;
02909   struct _objc_method_list *instance_methods;
02910   struct _objc_method_list *class_methods;
02911   struct _objc_protocol_list *protocols;
02912   uint32_t size; // <rdar://4585769>
02913   struct _objc_property_list *instance_properties;
02914   };
02915 */
02916 void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
02917   unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.CategoryTy);
02918 
02919   // FIXME: This is poor design, the OCD should have a pointer to the category
02920   // decl. Additionally, note that Category can be null for the @implementation
02921   // w/o an @interface case. Sema should just create one for us as it does for
02922   // @implementation so everyone else can live life under a clear blue sky.
02923   const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
02924   const ObjCCategoryDecl *Category =
02925     Interface->FindCategoryDeclaration(OCD->getIdentifier());
02926 
02927   SmallString<256> ExtName;
02928   llvm::raw_svector_ostream(ExtName) << Interface->getName() << '_'
02929                                      << OCD->getName();
02930 
02931   SmallVector<llvm::Constant *, 16> InstanceMethods, ClassMethods;
02932   for (const auto *I : OCD->instance_methods())
02933     // Instance methods should always be defined.
02934     InstanceMethods.push_back(GetMethodConstant(I));
02935 
02936   for (const auto *I : OCD->class_methods())
02937     // Class methods should always be defined.
02938     ClassMethods.push_back(GetMethodConstant(I));
02939 
02940   llvm::Constant *Values[7];
02941   Values[0] = GetClassName(OCD->getName());
02942   Values[1] = GetClassName(Interface->getObjCRuntimeNameAsString());
02943   LazySymbols.insert(Interface->getIdentifier());
02944   Values[2] =
02945     EmitMethodList("\01L_OBJC_CATEGORY_INSTANCE_METHODS_" + ExtName.str(),
02946                    "__OBJC,__cat_inst_meth,regular,no_dead_strip",
02947                    InstanceMethods);
02948   Values[3] =
02949     EmitMethodList("\01L_OBJC_CATEGORY_CLASS_METHODS_" + ExtName.str(),
02950                    "__OBJC,__cat_cls_meth,regular,no_dead_strip",
02951                    ClassMethods);
02952   if (Category) {
02953     Values[4] =
02954       EmitProtocolList("\01L_OBJC_CATEGORY_PROTOCOLS_" + ExtName.str(),
02955                        Category->protocol_begin(),
02956                        Category->protocol_end());
02957   } else {
02958     Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
02959   }
02960   Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
02961 
02962   // If there is no category @interface then there can be no properties.
02963   if (Category) {
02964     Values[6] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(),
02965                                  OCD, Category, ObjCTypes);
02966   } else {
02967     Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
02968   }
02969 
02970   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
02971                                                    Values);
02972 
02973   llvm::GlobalVariable *GV =
02974     CreateMetadataVar("\01L_OBJC_CATEGORY_" + ExtName.str(), Init,
02975                       "__OBJC,__category,regular,no_dead_strip",
02976                       4, true);
02977   DefinedCategories.push_back(GV);
02978   DefinedCategoryNames.insert(ExtName.str());
02979   // method definition entries must be clear for next implementation.
02980   MethodDefinitions.clear();
02981 }
02982 
02983 enum FragileClassFlags {
02984   FragileABI_Class_Factory                 = 0x00001,
02985   FragileABI_Class_Meta                    = 0x00002,
02986   FragileABI_Class_HasCXXStructors         = 0x02000,
02987   FragileABI_Class_Hidden                  = 0x20000
02988 };
02989 
02990 enum NonFragileClassFlags {
02991   /// Is a meta-class.
02992   NonFragileABI_Class_Meta                 = 0x00001,
02993 
02994   /// Is a root class.
02995   NonFragileABI_Class_Root                 = 0x00002,
02996 
02997   /// Has a C++ constructor and destructor.
02998   NonFragileABI_Class_HasCXXStructors      = 0x00004,
02999 
03000   /// Has hidden visibility.
03001   NonFragileABI_Class_Hidden               = 0x00010,
03002 
03003   /// Has the exception attribute.
03004   NonFragileABI_Class_Exception            = 0x00020,
03005 
03006   /// (Obsolete) ARC-specific: this class has a .release_ivars method
03007   NonFragileABI_Class_HasIvarReleaser      = 0x00040,
03008 
03009   /// Class implementation was compiled under ARC.
03010   NonFragileABI_Class_CompiledByARC        = 0x00080,
03011 
03012   /// Class has non-trivial destructors, but zero-initialization is okay.
03013   NonFragileABI_Class_HasCXXDestructorOnly = 0x00100
03014 };
03015 
03016 /*
03017   struct _objc_class {
03018   Class isa;
03019   Class super_class;
03020   const char *name;
03021   long version;
03022   long info;
03023   long instance_size;
03024   struct _objc_ivar_list *ivars;
03025   struct _objc_method_list *methods;
03026   struct _objc_cache *cache;
03027   struct _objc_protocol_list *protocols;
03028   // Objective-C 1.0 extensions (<rdr://4585769>)
03029   const char *ivar_layout;
03030   struct _objc_class_ext *ext;
03031   };
03032 
03033   See EmitClassExtension();
03034 */
03035 void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
03036   DefinedSymbols.insert(ID->getIdentifier());
03037 
03038   std::string ClassName = ID->getNameAsString();
03039   // FIXME: Gross
03040   ObjCInterfaceDecl *Interface =
03041     const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
03042   llvm::Constant *Protocols =
03043     EmitProtocolList("\01L_OBJC_CLASS_PROTOCOLS_" + ID->getName(),
03044                      Interface->all_referenced_protocol_begin(),
03045                      Interface->all_referenced_protocol_end());
03046   unsigned Flags = FragileABI_Class_Factory;
03047   if (ID->hasNonZeroConstructors() || ID->hasDestructors())
03048     Flags |= FragileABI_Class_HasCXXStructors;
03049   unsigned Size =
03050     CGM.getContext().getASTObjCImplementationLayout(ID).getSize().getQuantity();
03051 
03052   // FIXME: Set CXX-structors flag.
03053   if (ID->getClassInterface()->getVisibility() == HiddenVisibility)
03054     Flags |= FragileABI_Class_Hidden;
03055 
03056   SmallVector<llvm::Constant *, 16> InstanceMethods, ClassMethods;
03057   for (const auto *I : ID->instance_methods())
03058     // Instance methods should always be defined.
03059     InstanceMethods.push_back(GetMethodConstant(I));
03060 
03061   for (const auto *I : ID->class_methods())
03062     // Class methods should always be defined.
03063     ClassMethods.push_back(GetMethodConstant(I));
03064 
03065   for (const auto *PID : ID->property_impls()) {
03066     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
03067       ObjCPropertyDecl *PD = PID->getPropertyDecl();
03068 
03069       if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
03070         if (llvm::Constant *C = GetMethodConstant(MD))
03071           InstanceMethods.push_back(C);
03072       if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
03073         if (llvm::Constant *C = GetMethodConstant(MD))
03074           InstanceMethods.push_back(C);
03075     }
03076   }
03077 
03078   llvm::Constant *Values[12];
03079   Values[ 0] = EmitMetaClass(ID, Protocols, ClassMethods);
03080   if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
03081     // Record a reference to the super class.
03082     LazySymbols.insert(Super->getIdentifier());
03083 
03084     Values[ 1] =
03085       llvm::ConstantExpr::getBitCast(GetClassName(Super->getObjCRuntimeNameAsString()),
03086                                      ObjCTypes.ClassPtrTy);
03087   } else {
03088     Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
03089   }
03090   Values[ 2] = GetClassName(ID->getObjCRuntimeNameAsString());
03091   // Version is always 0.
03092   Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
03093   Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
03094   Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
03095   Values[ 6] = EmitIvarList(ID, false);
03096   Values[ 7] =
03097     EmitMethodList("\01L_OBJC_INSTANCE_METHODS_" + ID->getName(),
03098                    "__OBJC,__inst_meth,regular,no_dead_strip",
03099                    InstanceMethods);
03100   // cache is always NULL.
03101   Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
03102   Values[ 9] = Protocols;
03103   Values[10] = BuildIvarLayout(ID, true);
03104   Values[11] = EmitClassExtension(ID);
03105   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
03106                                                    Values);
03107   std::string Name("\01L_OBJC_CLASS_");
03108   Name += ClassName;
03109   const char *Section = "__OBJC,__class,regular,no_dead_strip";
03110   // Check for a forward reference.
03111   llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
03112   if (GV) {
03113     assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
03114            "Forward metaclass reference has incorrect type.");
03115     GV->setInitializer(Init);
03116     GV->setSection(Section);
03117     GV->setAlignment(4);
03118     CGM.addCompilerUsedGlobal(GV);
03119   } else
03120     GV = CreateMetadataVar(Name, Init, Section, 4, true);
03121   assertPrivateName(GV);
03122   DefinedClasses.push_back(GV);
03123   ImplementedClasses.push_back(Interface);
03124   // method definition entries must be clear for next implementation.
03125   MethodDefinitions.clear();
03126 }
03127 
03128 llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
03129                                          llvm::Constant *Protocols,
03130                                          ArrayRef<llvm::Constant*> Methods) {
03131   unsigned Flags = FragileABI_Class_Meta;
03132   unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassTy);
03133 
03134   if (ID->getClassInterface()->getVisibility() == HiddenVisibility)
03135     Flags |= FragileABI_Class_Hidden;
03136 
03137   llvm::Constant *Values[12];
03138   // The isa for the metaclass is the root of the hierarchy.
03139   const ObjCInterfaceDecl *Root = ID->getClassInterface();
03140   while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
03141     Root = Super;
03142   Values[ 0] =
03143     llvm::ConstantExpr::getBitCast(GetClassName(Root->getObjCRuntimeNameAsString()),
03144                                    ObjCTypes.ClassPtrTy);
03145   // The super class for the metaclass is emitted as the name of the
03146   // super class. The runtime fixes this up to point to the
03147   // *metaclass* for the super class.
03148   if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
03149     Values[ 1] =
03150       llvm::ConstantExpr::getBitCast(GetClassName(Super->getObjCRuntimeNameAsString()),
03151                                      ObjCTypes.ClassPtrTy);
03152   } else {
03153     Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
03154   }
03155   Values[ 2] = GetClassName(ID->getObjCRuntimeNameAsString());
03156   // Version is always 0.
03157   Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
03158   Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
03159   Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
03160   Values[ 6] = EmitIvarList(ID, true);
03161   Values[ 7] =
03162     EmitMethodList("\01L_OBJC_CLASS_METHODS_" + ID->getNameAsString(),
03163                    "__OBJC,__cls_meth,regular,no_dead_strip",
03164                    Methods);
03165   // cache is always NULL.
03166   Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
03167   Values[ 9] = Protocols;
03168   // ivar_layout for metaclass is always NULL.
03169   Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
03170   // The class extension is always unused for metaclasses.
03171   Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
03172   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
03173                                                    Values);
03174 
03175   std::string Name("\01L_OBJC_METACLASS_");
03176   Name += ID->getName();
03177 
03178   // Check for a forward reference.
03179   llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
03180   if (GV) {
03181     assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
03182            "Forward metaclass reference has incorrect type.");
03183     GV->setInitializer(Init);
03184   } else {
03185     GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
03186                                   llvm::GlobalValue::PrivateLinkage,
03187                                   Init, Name);
03188   }
03189   assertPrivateName(GV);
03190   GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
03191   GV->setAlignment(4);
03192   CGM.addCompilerUsedGlobal(GV);
03193 
03194   return GV;
03195 }
03196 
03197 llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
03198   std::string Name = "\01L_OBJC_METACLASS_" + ID->getNameAsString();
03199 
03200   // FIXME: Should we look these up somewhere other than the module. Its a bit
03201   // silly since we only generate these while processing an implementation, so
03202   // exactly one pointer would work if know when we entered/exitted an
03203   // implementation block.
03204 
03205   // Check for an existing forward reference.
03206   // Previously, metaclass with internal linkage may have been defined.
03207   // pass 'true' as 2nd argument so it is returned.
03208   llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
03209   if (!GV)
03210     GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
03211                                   llvm::GlobalValue::PrivateLinkage, nullptr,
03212                                   Name);
03213 
03214   assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
03215          "Forward metaclass reference has incorrect type.");
03216   assertPrivateName(GV);
03217   return GV;
03218 }
03219 
03220 llvm::Value *CGObjCMac::EmitSuperClassRef(const ObjCInterfaceDecl *ID) {
03221   std::string Name = "\01L_OBJC_CLASS_" + ID->getNameAsString();
03222   llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name, true);
03223 
03224   if (!GV)
03225     GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassTy, false,
03226                                   llvm::GlobalValue::PrivateLinkage, nullptr,
03227                                   Name);
03228 
03229   assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
03230          "Forward class metadata reference has incorrect type.");
03231   assertPrivateName(GV);
03232   return GV;
03233 }
03234 
03235 /*
03236   struct objc_class_ext {
03237   uint32_t size;
03238   const char *weak_ivar_layout;
03239   struct _objc_property_list *properties;
03240   };
03241 */
03242 llvm::Constant *
03243 CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
03244   uint64_t Size =
03245     CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassExtensionTy);
03246 
03247   llvm::Constant *Values[3];
03248   Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
03249   Values[1] = BuildIvarLayout(ID, false);
03250   Values[2] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getName(),
03251                                ID, ID->getClassInterface(), ObjCTypes);
03252 
03253   // Return null if no extension bits are used.
03254   if (Values[1]->isNullValue() && Values[2]->isNullValue())
03255     return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
03256 
03257   llvm::Constant *Init =
03258     llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
03259   return CreateMetadataVar("\01L_OBJC_CLASSEXT_" + ID->getName(),
03260                            Init, "__OBJC,__class_ext,regular,no_dead_strip",
03261                            4, true);
03262 }
03263 
03264 /*
03265   struct objc_ivar {
03266     char *ivar_name;
03267     char *ivar_type;
03268     int ivar_offset;
03269   };
03270 
03271   struct objc_ivar_list {
03272     int ivar_count;
03273     struct objc_ivar list[count];
03274   };
03275 */
03276 llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
03277                                         bool ForClass) {
03278   std::vector<llvm::Constant*> Ivars;
03279 
03280   // When emitting the root class GCC emits ivar entries for the
03281   // actual class structure. It is not clear if we need to follow this
03282   // behavior; for now lets try and get away with not doing it. If so,
03283   // the cleanest solution would be to make up an ObjCInterfaceDecl
03284   // for the class.
03285   if (ForClass)
03286     return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
03287 
03288   const ObjCInterfaceDecl *OID = ID->getClassInterface();
03289 
03290   for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin(); 
03291        IVD; IVD = IVD->getNextIvar()) {
03292     // Ignore unnamed bit-fields.
03293     if (!IVD->getDeclName())
03294       continue;
03295     llvm::Constant *Ivar[] = {
03296       GetMethodVarName(IVD->getIdentifier()),
03297       GetMethodVarType(IVD),
03298       llvm::ConstantInt::get(ObjCTypes.IntTy,
03299                              ComputeIvarBaseOffset(CGM, OID, IVD))
03300     };
03301     Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
03302   }
03303 
03304   // Return null for empty list.
03305   if (Ivars.empty())
03306     return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
03307 
03308   llvm::Constant *Values[2];
03309   Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
03310   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
03311                                              Ivars.size());
03312   Values[1] = llvm::ConstantArray::get(AT, Ivars);
03313   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
03314 
03315   llvm::GlobalVariable *GV;
03316   if (ForClass)
03317     GV = CreateMetadataVar("\01L_OBJC_CLASS_VARIABLES_" + ID->getName(),
03318                            Init, "__OBJC,__class_vars,regular,no_dead_strip",
03319                            4, true);
03320   else
03321     GV = CreateMetadataVar("\01L_OBJC_INSTANCE_VARIABLES_" + ID->getName(),
03322                            Init, "__OBJC,__instance_vars,regular,no_dead_strip",
03323                            4, true);
03324   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListPtrTy);
03325 }
03326 
03327 /*
03328   struct objc_method {
03329   SEL method_name;
03330   char *method_types;
03331   void *method;
03332   };
03333 
03334   struct objc_method_list {
03335   struct objc_method_list *obsolete;
03336   int count;
03337   struct objc_method methods_list[count];
03338   };
03339 */
03340 
03341 /// GetMethodConstant - Return a struct objc_method constant for the
03342 /// given method if it has been defined. The result is null if the
03343 /// method has not been defined. The return value has type MethodPtrTy.
03344 llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
03345   llvm::Function *Fn = GetMethodDefinition(MD);
03346   if (!Fn)
03347     return nullptr;
03348 
03349   llvm::Constant *Method[] = {
03350     llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
03351                                    ObjCTypes.SelectorPtrTy),
03352     GetMethodVarType(MD),
03353     llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy)
03354   };
03355   return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
03356 }
03357 
03358 llvm::Constant *CGObjCMac::EmitMethodList(Twine Name,
03359                                           const char *Section,
03360                                           ArrayRef<llvm::Constant*> Methods) {
03361   // Return null for empty list.
03362   if (Methods.empty())
03363     return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
03364 
03365   llvm::Constant *Values[3];
03366   Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
03367   Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
03368   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
03369                                              Methods.size());
03370   Values[2] = llvm::ConstantArray::get(AT, Methods);
03371   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
03372 
03373   llvm::GlobalVariable *GV = CreateMetadataVar(Name, Init, Section, 4, true);
03374   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListPtrTy);
03375 }
03376 
03377 llvm::Function *CGObjCCommonMac::GenerateMethod(const ObjCMethodDecl *OMD,
03378                                                 const ObjCContainerDecl *CD) {
03379   SmallString<256> Name;
03380   GetNameForMethod(OMD, CD, Name);
03381 
03382   CodeGenTypes &Types = CGM.getTypes();
03383   llvm::FunctionType *MethodTy =
03384     Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
03385   llvm::Function *Method =
03386     llvm::Function::Create(MethodTy,
03387                            llvm::GlobalValue::InternalLinkage,
03388                            Name.str(),
03389                            &CGM.getModule());
03390   MethodDefinitions.insert(std::make_pair(OMD, Method));
03391 
03392   return Method;
03393 }
03394 
03395 llvm::GlobalVariable *CGObjCCommonMac::CreateMetadataVar(Twine Name,
03396                                                          llvm::Constant *Init,
03397                                                          StringRef Section,
03398                                                          unsigned Align,
03399                                                          bool AddToUsed) {
03400   llvm::Type *Ty = Init->getType();
03401   llvm::GlobalVariable *GV =
03402     new llvm::GlobalVariable(CGM.getModule(), Ty, false,
03403                              llvm::GlobalValue::PrivateLinkage, Init, Name);
03404   assertPrivateName(GV);
03405   if (!Section.empty())
03406     GV->setSection(Section);
03407   if (Align)
03408     GV->setAlignment(Align);
03409   if (AddToUsed)
03410     CGM.addCompilerUsedGlobal(GV);
03411   return GV;
03412 }
03413 
03414 llvm::Function *CGObjCMac::ModuleInitFunction() {
03415   // Abuse this interface function as a place to finalize.
03416   FinishModule();
03417   return nullptr;
03418 }
03419 
03420 llvm::Constant *CGObjCMac::GetPropertyGetFunction() {
03421   return ObjCTypes.getGetPropertyFn();
03422 }
03423 
03424 llvm::Constant *CGObjCMac::GetPropertySetFunction() {
03425   return ObjCTypes.getSetPropertyFn();
03426 }
03427 
03428 llvm::Constant *CGObjCMac::GetOptimizedPropertySetFunction(bool atomic, 
03429                                                            bool copy) {
03430   return ObjCTypes.getOptimizedSetPropertyFn(atomic, copy);
03431 }
03432 
03433 llvm::Constant *CGObjCMac::GetGetStructFunction() {
03434   return ObjCTypes.getCopyStructFn();
03435 }
03436 llvm::Constant *CGObjCMac::GetSetStructFunction() {
03437   return ObjCTypes.getCopyStructFn();
03438 }
03439 
03440 llvm::Constant *CGObjCMac::GetCppAtomicObjectGetFunction() {
03441   return ObjCTypes.getCppAtomicObjectFunction();
03442 }
03443 llvm::Constant *CGObjCMac::GetCppAtomicObjectSetFunction() {
03444   return ObjCTypes.getCppAtomicObjectFunction();
03445 }
03446 
03447 llvm::Constant *CGObjCMac::EnumerationMutationFunction() {
03448   return ObjCTypes.getEnumerationMutationFn();
03449 }
03450 
03451 void CGObjCMac::EmitTryStmt(CodeGenFunction &CGF, const ObjCAtTryStmt &S) {
03452   return EmitTryOrSynchronizedStmt(CGF, S);
03453 }
03454 
03455 void CGObjCMac::EmitSynchronizedStmt(CodeGenFunction &CGF,
03456                                      const ObjCAtSynchronizedStmt &S) {
03457   return EmitTryOrSynchronizedStmt(CGF, S);
03458 }
03459 
03460 namespace {
03461   struct PerformFragileFinally : EHScopeStack::Cleanup {
03462     const Stmt &S;
03463     llvm::Value *SyncArgSlot;
03464     llvm::Value *CallTryExitVar;
03465     llvm::Value *ExceptionData;
03466     ObjCTypesHelper &ObjCTypes;
03467     PerformFragileFinally(const Stmt *S,
03468                           llvm::Value *SyncArgSlot,
03469                           llvm::Value *CallTryExitVar,
03470                           llvm::Value *ExceptionData,
03471                           ObjCTypesHelper *ObjCTypes)
03472       : S(*S), SyncArgSlot(SyncArgSlot), CallTryExitVar(CallTryExitVar),
03473         ExceptionData(ExceptionData), ObjCTypes(*ObjCTypes) {}
03474 
03475     void Emit(CodeGenFunction &CGF, Flags flags) override {
03476       // Check whether we need to call objc_exception_try_exit.
03477       // In optimized code, this branch will always be folded.
03478       llvm::BasicBlock *FinallyCallExit =
03479         CGF.createBasicBlock("finally.call_exit");
03480       llvm::BasicBlock *FinallyNoCallExit =
03481         CGF.createBasicBlock("finally.no_call_exit");
03482       CGF.Builder.CreateCondBr(CGF.Builder.CreateLoad(CallTryExitVar),
03483                                FinallyCallExit, FinallyNoCallExit);
03484 
03485       CGF.EmitBlock(FinallyCallExit);
03486       CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryExitFn(),
03487                                   ExceptionData);
03488 
03489       CGF.EmitBlock(FinallyNoCallExit);
03490 
03491       if (isa<ObjCAtTryStmt>(S)) {
03492         if (const ObjCAtFinallyStmt* FinallyStmt =
03493               cast<ObjCAtTryStmt>(S).getFinallyStmt()) {
03494           // Don't try to do the @finally if this is an EH cleanup.
03495           if (flags.isForEHCleanup()) return;
03496 
03497           // Save the current cleanup destination in case there's
03498           // control flow inside the finally statement.
03499           llvm::Value *CurCleanupDest =
03500             CGF.Builder.CreateLoad(CGF.getNormalCleanupDestSlot());
03501 
03502           CGF.EmitStmt(FinallyStmt->getFinallyBody());
03503 
03504           if (CGF.HaveInsertPoint()) {
03505             CGF.Builder.CreateStore(CurCleanupDest,
03506                                     CGF.getNormalCleanupDestSlot());
03507           } else {
03508             // Currently, the end of the cleanup must always exist.
03509             CGF.EnsureInsertPoint();
03510           }
03511         }
03512       } else {
03513         // Emit objc_sync_exit(expr); as finally's sole statement for
03514         // @synchronized.
03515         llvm::Value *SyncArg = CGF.Builder.CreateLoad(SyncArgSlot);
03516         CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncExitFn(), SyncArg);
03517       }
03518     }
03519   };
03520 
03521   class FragileHazards {
03522     CodeGenFunction &CGF;
03523     SmallVector<llvm::Value*, 20> Locals;
03524     llvm::DenseSet<llvm::BasicBlock*> BlocksBeforeTry;
03525 
03526     llvm::InlineAsm *ReadHazard;
03527     llvm::InlineAsm *WriteHazard;
03528 
03529     llvm::FunctionType *GetAsmFnType();
03530 
03531     void collectLocals();
03532     void emitReadHazard(CGBuilderTy &Builder);
03533 
03534   public:
03535     FragileHazards(CodeGenFunction &CGF);
03536 
03537     void emitWriteHazard();
03538     void emitHazardsInNewBlocks();
03539   };
03540 }
03541 
03542 /// Create the fragile-ABI read and write hazards based on the current
03543 /// state of the function, which is presumed to be immediately prior
03544 /// to a @try block.  These hazards are used to maintain correct
03545 /// semantics in the face of optimization and the fragile ABI's
03546 /// cavalier use of setjmp/longjmp.
03547 FragileHazards::FragileHazards(CodeGenFunction &CGF) : CGF(CGF) {
03548   collectLocals();
03549 
03550   if (Locals.empty()) return;
03551 
03552   // Collect all the blocks in the function.
03553   for (llvm::Function::iterator
03554          I = CGF.CurFn->begin(), E = CGF.CurFn->end(); I != E; ++I)
03555     BlocksBeforeTry.insert(&*I);
03556 
03557   llvm::FunctionType *AsmFnTy = GetAsmFnType();
03558 
03559   // Create a read hazard for the allocas.  This inhibits dead-store
03560   // optimizations and forces the values to memory.  This hazard is
03561   // inserted before any 'throwing' calls in the protected scope to
03562   // reflect the possibility that the variables might be read from the
03563   // catch block if the call throws.
03564   {
03565     std::string Constraint;
03566     for (unsigned I = 0, E = Locals.size(); I != E; ++I) {
03567       if (I) Constraint += ',';
03568       Constraint += "*m";
03569     }
03570 
03571     ReadHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);
03572   }
03573 
03574   // Create a write hazard for the allocas.  This inhibits folding
03575   // loads across the hazard.  This hazard is inserted at the
03576   // beginning of the catch path to reflect the possibility that the
03577   // variables might have been written within the protected scope.
03578   {
03579     std::string Constraint;
03580     for (unsigned I = 0, E = Locals.size(); I != E; ++I) {
03581       if (I) Constraint += ',';
03582       Constraint += "=*m";
03583     }
03584 
03585     WriteHazard = llvm::InlineAsm::get(AsmFnTy, "", Constraint, true, false);
03586   }
03587 }
03588 
03589 /// Emit a write hazard at the current location.
03590 void FragileHazards::emitWriteHazard() {
03591   if (Locals.empty()) return;
03592 
03593   CGF.EmitNounwindRuntimeCall(WriteHazard, Locals);
03594 }
03595 
03596 void FragileHazards::emitReadHazard(CGBuilderTy &Builder) {
03597   assert(!Locals.empty());
03598   llvm::CallInst *call = Builder.CreateCall(ReadHazard, Locals);
03599   call->setDoesNotThrow();
03600   call->setCallingConv(CGF.getRuntimeCC());
03601 }
03602 
03603 /// Emit read hazards in all the protected blocks, i.e. all the blocks
03604 /// which have been inserted since the beginning of the try.
03605 void FragileHazards::emitHazardsInNewBlocks() {
03606   if (Locals.empty()) return;
03607 
03608   CGBuilderTy Builder(CGF.getLLVMContext());
03609 
03610   // Iterate through all blocks, skipping those prior to the try.
03611   for (llvm::Function::iterator
03612          FI = CGF.CurFn->begin(), FE = CGF.CurFn->end(); FI != FE; ++FI) {
03613     llvm::BasicBlock &BB = *FI;
03614     if (BlocksBeforeTry.count(&BB)) continue;
03615 
03616     // Walk through all the calls in the block.
03617     for (llvm::BasicBlock::iterator
03618            BI = BB.begin(), BE = BB.end(); BI != BE; ++BI) {
03619       llvm::Instruction &I = *BI;
03620 
03621       // Ignore instructions that aren't non-intrinsic calls.
03622       // These are the only calls that can possibly call longjmp.
03623       if (!isa<llvm::CallInst>(I) && !isa<llvm::InvokeInst>(I)) continue;
03624       if (isa<llvm::IntrinsicInst>(I))
03625         continue;
03626 
03627       // Ignore call sites marked nounwind.  This may be questionable,
03628       // since 'nounwind' doesn't necessarily mean 'does not call longjmp'.
03629       llvm::CallSite CS(&I);
03630       if (CS.doesNotThrow()) continue;
03631 
03632       // Insert a read hazard before the call.  This will ensure that
03633       // any writes to the locals are performed before making the
03634       // call.  If the call throws, then this is sufficient to
03635       // guarantee correctness as long as it doesn't also write to any
03636       // locals.
03637       Builder.SetInsertPoint(&BB, BI);
03638       emitReadHazard(Builder);
03639     }
03640   }
03641 }
03642 
03643 static void addIfPresent(llvm::DenseSet<llvm::Value*> &S, llvm::Value *V) {
03644   if (V) S.insert(V);
03645 }
03646 
03647 void FragileHazards::collectLocals() {
03648   // Compute a set of allocas to ignore.
03649   llvm::DenseSet<llvm::Value*> AllocasToIgnore;
03650   addIfPresent(AllocasToIgnore, CGF.ReturnValue);
03651   addIfPresent(AllocasToIgnore, CGF.NormalCleanupDest);
03652 
03653   // Collect all the allocas currently in the function.  This is
03654   // probably way too aggressive.
03655   llvm::BasicBlock &Entry = CGF.CurFn->getEntryBlock();
03656   for (llvm::BasicBlock::iterator
03657          I = Entry.begin(), E = Entry.end(); I != E; ++I)
03658     if (isa<llvm::AllocaInst>(*I) && !AllocasToIgnore.count(&*I))
03659       Locals.push_back(&*I);
03660 }
03661 
03662 llvm::FunctionType *FragileHazards::GetAsmFnType() {
03663   SmallVector<llvm::Type *, 16> tys(Locals.size());
03664   for (unsigned i = 0, e = Locals.size(); i != e; ++i)
03665     tys[i] = Locals[i]->getType();
03666   return llvm::FunctionType::get(CGF.VoidTy, tys, false);
03667 }
03668 
03669 /*
03670 
03671   Objective-C setjmp-longjmp (sjlj) Exception Handling
03672   --
03673 
03674   A catch buffer is a setjmp buffer plus:
03675     - a pointer to the exception that was caught
03676     - a pointer to the previous exception data buffer
03677     - two pointers of reserved storage
03678   Therefore catch buffers form a stack, with a pointer to the top
03679   of the stack kept in thread-local storage.
03680 
03681   objc_exception_try_enter pushes a catch buffer onto the EH stack.
03682   objc_exception_try_exit pops the given catch buffer, which is
03683     required to be the top of the EH stack.
03684   objc_exception_throw pops the top of the EH stack, writes the
03685     thrown exception into the appropriate field, and longjmps
03686     to the setjmp buffer.  It crashes the process (with a printf
03687     and an abort()) if there are no catch buffers on the stack.
03688   objc_exception_extract just reads the exception pointer out of the
03689     catch buffer.
03690 
03691   There's no reason an implementation couldn't use a light-weight
03692   setjmp here --- something like __builtin_setjmp, but API-compatible
03693   with the heavyweight setjmp.  This will be more important if we ever
03694   want to implement correct ObjC/C++ exception interactions for the
03695   fragile ABI.
03696 
03697   Note that for this use of setjmp/longjmp to be correct, we may need
03698   to mark some local variables volatile: if a non-volatile local
03699   variable is modified between the setjmp and the longjmp, it has
03700   indeterminate value.  For the purposes of LLVM IR, it may be
03701   sufficient to make loads and stores within the @try (to variables
03702   declared outside the @try) volatile.  This is necessary for
03703   optimized correctness, but is not currently being done; this is
03704   being tracked as rdar://problem/8160285
03705 
03706   The basic framework for a @try-catch-finally is as follows:
03707   {
03708   objc_exception_data d;
03709   id _rethrow = null;
03710   bool _call_try_exit = true;
03711 
03712   objc_exception_try_enter(&d);
03713   if (!setjmp(d.jmp_buf)) {
03714   ... try body ...
03715   } else {
03716   // exception path
03717   id _caught = objc_exception_extract(&d);
03718 
03719   // enter new try scope for handlers
03720   if (!setjmp(d.jmp_buf)) {
03721   ... match exception and execute catch blocks ...
03722 
03723   // fell off end, rethrow.
03724   _rethrow = _caught;
03725   ... jump-through-finally to finally_rethrow ...
03726   } else {
03727   // exception in catch block
03728   _rethrow = objc_exception_extract(&d);
03729   _call_try_exit = false;
03730   ... jump-through-finally to finally_rethrow ...
03731   }
03732   }
03733   ... jump-through-finally to finally_end ...
03734 
03735   finally:
03736   if (_call_try_exit)
03737   objc_exception_try_exit(&d);
03738 
03739   ... finally block ....
03740   ... dispatch to finally destination ...
03741 
03742   finally_rethrow:
03743   objc_exception_throw(_rethrow);
03744 
03745   finally_end:
03746   }
03747 
03748   This framework differs slightly from the one gcc uses, in that gcc
03749   uses _rethrow to determine if objc_exception_try_exit should be called
03750   and if the object should be rethrown. This breaks in the face of
03751   throwing nil and introduces unnecessary branches.
03752 
03753   We specialize this framework for a few particular circumstances:
03754 
03755   - If there are no catch blocks, then we avoid emitting the second
03756   exception handling context.
03757 
03758   - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
03759   e)) we avoid emitting the code to rethrow an uncaught exception.
03760 
03761   - FIXME: If there is no @finally block we can do a few more
03762   simplifications.
03763 
03764   Rethrows and Jumps-Through-Finally
03765   --
03766 
03767   '@throw;' is supported by pushing the currently-caught exception
03768   onto ObjCEHStack while the @catch blocks are emitted.
03769 
03770   Branches through the @finally block are handled with an ordinary
03771   normal cleanup.  We do not register an EH cleanup; fragile-ABI ObjC
03772   exceptions are not compatible with C++ exceptions, and this is
03773   hardly the only place where this will go wrong.
03774 
03775   @synchronized(expr) { stmt; } is emitted as if it were:
03776     id synch_value = expr;
03777     objc_sync_enter(synch_value);
03778     @try { stmt; } @finally { objc_sync_exit(synch_value); }
03779 */
03780 
03781 void CGObjCMac::EmitTryOrSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
03782                                           const Stmt &S) {
03783   bool isTry = isa<ObjCAtTryStmt>(S);
03784 
03785   // A destination for the fall-through edges of the catch handlers to
03786   // jump to.
03787   CodeGenFunction::JumpDest FinallyEnd =
03788     CGF.getJumpDestInCurrentScope("finally.end");
03789 
03790   // A destination for the rethrow edge of the catch handlers to jump
03791   // to.
03792   CodeGenFunction::JumpDest FinallyRethrow =
03793     CGF.getJumpDestInCurrentScope("finally.rethrow");
03794 
03795   // For @synchronized, call objc_sync_enter(sync.expr). The
03796   // evaluation of the expression must occur before we enter the
03797   // @synchronized.  We can't avoid a temp here because we need the
03798   // value to be preserved.  If the backend ever does liveness
03799   // correctly after setjmp, this will be unnecessary.
03800   llvm::Value *SyncArgSlot = nullptr;
03801   if (!isTry) {
03802     llvm::Value *SyncArg =
03803       CGF.EmitScalarExpr(cast<ObjCAtSynchronizedStmt>(S).getSynchExpr());
03804     SyncArg = CGF.Builder.CreateBitCast(SyncArg, ObjCTypes.ObjectPtrTy);
03805     CGF.EmitNounwindRuntimeCall(ObjCTypes.getSyncEnterFn(), SyncArg);
03806 
03807     SyncArgSlot = CGF.CreateTempAlloca(SyncArg->getType(), "sync.arg");
03808     CGF.Builder.CreateStore(SyncArg, SyncArgSlot);
03809   }
03810 
03811   // Allocate memory for the setjmp buffer.  This needs to be kept
03812   // live throughout the try and catch blocks.
03813   llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
03814                                                     "exceptiondata.ptr");
03815 
03816   // Create the fragile hazards.  Note that this will not capture any
03817   // of the allocas required for exception processing, but will
03818   // capture the current basic block (which extends all the way to the
03819   // setjmp call) as "before the @try".
03820   FragileHazards Hazards(CGF);
03821 
03822   // Create a flag indicating whether the cleanup needs to call
03823   // objc_exception_try_exit.  This is true except when
03824   //   - no catches match and we're branching through the cleanup
03825   //     just to rethrow the exception, or
03826   //   - a catch matched and we're falling out of the catch handler.
03827   // The setjmp-safety rule here is that we should always store to this
03828   // variable in a place that dominates the branch through the cleanup
03829   // without passing through any setjmps.
03830   llvm::Value *CallTryExitVar = CGF.CreateTempAlloca(CGF.Builder.getInt1Ty(),
03831                                                      "_call_try_exit");
03832 
03833   // A slot containing the exception to rethrow.  Only needed when we
03834   // have both a @catch and a @finally.
03835   llvm::Value *PropagatingExnVar = nullptr;
03836 
03837   // Push a normal cleanup to leave the try scope.
03838   CGF.EHStack.pushCleanup<PerformFragileFinally>(NormalAndEHCleanup, &S,
03839                                                  SyncArgSlot,
03840                                                  CallTryExitVar,
03841                                                  ExceptionData,
03842                                                  &ObjCTypes);
03843 
03844   // Enter a try block:
03845   //  - Call objc_exception_try_enter to push ExceptionData on top of
03846   //    the EH stack.
03847   CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(), ExceptionData);
03848 
03849   //  - Call setjmp on the exception data buffer.
03850   llvm::Constant *Zero = llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
03851   llvm::Value *GEPIndexes[] = { Zero, Zero, Zero };
03852   llvm::Value *SetJmpBuffer =
03853     CGF.Builder.CreateGEP(ExceptionData, GEPIndexes, "setjmp_buffer");
03854   llvm::CallInst *SetJmpResult =
03855     CGF.EmitNounwindRuntimeCall(ObjCTypes.getSetJmpFn(), SetJmpBuffer, "setjmp_result");
03856   SetJmpResult->setCanReturnTwice();
03857 
03858   // If setjmp returned 0, enter the protected block; otherwise,
03859   // branch to the handler.
03860   llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
03861   llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
03862   llvm::Value *DidCatch =
03863     CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
03864   CGF.Builder.CreateCondBr(DidCatch, TryHandler, TryBlock);
03865 
03866   // Emit the protected block.
03867   CGF.EmitBlock(TryBlock);
03868   CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
03869   CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
03870                      : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
03871 
03872   CGBuilderTy::InsertPoint TryFallthroughIP = CGF.Builder.saveAndClearIP();
03873 
03874   // Emit the exception handler block.
03875   CGF.EmitBlock(TryHandler);
03876 
03877   // Don't optimize loads of the in-scope locals across this point.
03878   Hazards.emitWriteHazard();
03879 
03880   // For a @synchronized (or a @try with no catches), just branch
03881   // through the cleanup to the rethrow block.
03882   if (!isTry || !cast<ObjCAtTryStmt>(S).getNumCatchStmts()) {
03883     // Tell the cleanup not to re-pop the exit.
03884     CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
03885     CGF.EmitBranchThroughCleanup(FinallyRethrow);
03886 
03887   // Otherwise, we have to match against the caught exceptions.
03888   } else {
03889     // Retrieve the exception object.  We may emit multiple blocks but
03890     // nothing can cross this so the value is already in SSA form.
03891     llvm::CallInst *Caught =
03892       CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
03893                                   ExceptionData, "caught");
03894 
03895     // Push the exception to rethrow onto the EH value stack for the
03896     // benefit of any @throws in the handlers.
03897     CGF.ObjCEHValueStack.push_back(Caught);
03898 
03899     const ObjCAtTryStmt* AtTryStmt = cast<ObjCAtTryStmt>(&S);
03900 
03901     bool HasFinally = (AtTryStmt->getFinallyStmt() != nullptr);
03902 
03903     llvm::BasicBlock *CatchBlock = nullptr;
03904     llvm::BasicBlock *CatchHandler = nullptr;
03905     if (HasFinally) {
03906       // Save the currently-propagating exception before
03907       // objc_exception_try_enter clears the exception slot.
03908       PropagatingExnVar = CGF.CreateTempAlloca(Caught->getType(),
03909                                                "propagating_exception");
03910       CGF.Builder.CreateStore(Caught, PropagatingExnVar);
03911 
03912       // Enter a new exception try block (in case a @catch block
03913       // throws an exception).
03914       CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(),
03915                                   ExceptionData);
03916 
03917       llvm::CallInst *SetJmpResult =
03918         CGF.EmitNounwindRuntimeCall(ObjCTypes.getSetJmpFn(),
03919                                     SetJmpBuffer, "setjmp.result");
03920       SetJmpResult->setCanReturnTwice();
03921 
03922       llvm::Value *Threw =
03923         CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
03924 
03925       CatchBlock = CGF.createBasicBlock("catch");
03926       CatchHandler = CGF.createBasicBlock("catch_for_catch");
03927       CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
03928 
03929       CGF.EmitBlock(CatchBlock);
03930     }
03931 
03932     CGF.Builder.CreateStore(CGF.Builder.getInt1(HasFinally), CallTryExitVar);
03933 
03934     // Handle catch list. As a special case we check if everything is
03935     // matched and avoid generating code for falling off the end if
03936     // so.
03937     bool AllMatched = false;
03938     for (unsigned I = 0, N = AtTryStmt->getNumCatchStmts(); I != N; ++I) {
03939       const ObjCAtCatchStmt *CatchStmt = AtTryStmt->getCatchStmt(I);
03940 
03941       const VarDecl *CatchParam = CatchStmt->getCatchParamDecl();
03942       const ObjCObjectPointerType *OPT = nullptr;
03943 
03944       // catch(...) always matches.
03945       if (!CatchParam) {
03946         AllMatched = true;
03947       } else {
03948         OPT = CatchParam->getType()->getAs<ObjCObjectPointerType>();
03949 
03950         // catch(id e) always matches under this ABI, since only
03951         // ObjC exceptions end up here in the first place.
03952         // FIXME: For the time being we also match id<X>; this should
03953         // be rejected by Sema instead.
03954         if (OPT && (OPT->isObjCIdType() || OPT->isObjCQualifiedIdType()))
03955           AllMatched = true;
03956       }
03957 
03958       // If this is a catch-all, we don't need to test anything.
03959       if (AllMatched) {
03960         CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
03961 
03962         if (CatchParam) {
03963           CGF.EmitAutoVarDecl(*CatchParam);
03964           assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
03965 
03966           // These types work out because ConvertType(id) == i8*.
03967           CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
03968         }
03969 
03970         CGF.EmitStmt(CatchStmt->getCatchBody());
03971 
03972         // The scope of the catch variable ends right here.
03973         CatchVarCleanups.ForceCleanup();
03974 
03975         CGF.EmitBranchThroughCleanup(FinallyEnd);
03976         break;
03977       }
03978 
03979       assert(OPT && "Unexpected non-object pointer type in @catch");
03980       const ObjCObjectType *ObjTy = OPT->getObjectType();
03981 
03982       // FIXME: @catch (Class c) ?
03983       ObjCInterfaceDecl *IDecl = ObjTy->getInterface();
03984       assert(IDecl && "Catch parameter must have Objective-C type!");
03985 
03986       // Check if the @catch block matches the exception object.
03987       llvm::Value *Class = EmitClassRef(CGF, IDecl);
03988 
03989       llvm::Value *matchArgs[] = { Class, Caught };
03990       llvm::CallInst *Match =
03991         CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionMatchFn(),
03992                                     matchArgs, "match");
03993 
03994       llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("match");
03995       llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch.next");
03996 
03997       CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
03998                                MatchedBlock, NextCatchBlock);
03999 
04000       // Emit the @catch block.
04001       CGF.EmitBlock(MatchedBlock);
04002 
04003       // Collect any cleanups for the catch variable.  The scope lasts until
04004       // the end of the catch body.
04005       CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
04006 
04007       CGF.EmitAutoVarDecl(*CatchParam);
04008       assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
04009 
04010       // Initialize the catch variable.
04011       llvm::Value *Tmp =
04012         CGF.Builder.CreateBitCast(Caught,
04013                                   CGF.ConvertType(CatchParam->getType()));
04014       CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
04015 
04016       CGF.EmitStmt(CatchStmt->getCatchBody());
04017 
04018       // We're done with the catch variable.
04019       CatchVarCleanups.ForceCleanup();
04020 
04021       CGF.EmitBranchThroughCleanup(FinallyEnd);
04022 
04023       CGF.EmitBlock(NextCatchBlock);
04024     }
04025 
04026     CGF.ObjCEHValueStack.pop_back();
04027 
04028     // If nothing wanted anything to do with the caught exception,
04029     // kill the extract call.
04030     if (Caught->use_empty())
04031       Caught->eraseFromParent();
04032 
04033     if (!AllMatched)
04034       CGF.EmitBranchThroughCleanup(FinallyRethrow);
04035 
04036     if (HasFinally) {
04037       // Emit the exception handler for the @catch blocks.
04038       CGF.EmitBlock(CatchHandler);
04039 
04040       // In theory we might now need a write hazard, but actually it's
04041       // unnecessary because there's no local-accessing code between
04042       // the try's write hazard and here.
04043       //Hazards.emitWriteHazard();
04044 
04045       // Extract the new exception and save it to the
04046       // propagating-exception slot.
04047       assert(PropagatingExnVar);
04048       llvm::CallInst *NewCaught =
04049         CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
04050                                     ExceptionData, "caught");
04051       CGF.Builder.CreateStore(NewCaught, PropagatingExnVar);
04052 
04053       // Don't pop the catch handler; the throw already did.
04054       CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
04055       CGF.EmitBranchThroughCleanup(FinallyRethrow);
04056     }
04057   }
04058 
04059   // Insert read hazards as required in the new blocks.
04060   Hazards.emitHazardsInNewBlocks();
04061 
04062   // Pop the cleanup.
04063   CGF.Builder.restoreIP(TryFallthroughIP);
04064   if (CGF.HaveInsertPoint())
04065     CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
04066   CGF.PopCleanupBlock();
04067   CGF.EmitBlock(FinallyEnd.getBlock(), true);
04068 
04069   // Emit the rethrow block.
04070   CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
04071   CGF.EmitBlock(FinallyRethrow.getBlock(), true);
04072   if (CGF.HaveInsertPoint()) {
04073     // If we have a propagating-exception variable, check it.
04074     llvm::Value *PropagatingExn;
04075     if (PropagatingExnVar) {
04076       PropagatingExn = CGF.Builder.CreateLoad(PropagatingExnVar);
04077 
04078     // Otherwise, just look in the buffer for the exception to throw.
04079     } else {
04080       llvm::CallInst *Caught =
04081         CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
04082                                     ExceptionData);
04083       PropagatingExn = Caught;
04084     }
04085 
04086     CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionThrowFn(),
04087                                 PropagatingExn);
04088     CGF.Builder.CreateUnreachable();
04089   }
04090 
04091   CGF.Builder.restoreIP(SavedIP);
04092 }
04093 
04094 void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
04095                               const ObjCAtThrowStmt &S,
04096                               bool ClearInsertionPoint) {
04097   llvm::Value *ExceptionAsObject;
04098 
04099   if (const Expr *ThrowExpr = S.getThrowExpr()) {
04100     llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
04101     ExceptionAsObject =
04102       CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
04103   } else {
04104     assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
04105            "Unexpected rethrow outside @catch block.");
04106     ExceptionAsObject = CGF.ObjCEHValueStack.back();
04107   }
04108 
04109   CGF.EmitRuntimeCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject)
04110     ->setDoesNotReturn();
04111   CGF.Builder.CreateUnreachable();
04112 
04113   // Clear the insertion point to indicate we are in unreachable code.
04114   if (ClearInsertionPoint)
04115     CGF.Builder.ClearInsertionPoint();
04116 }
04117 
04118 /// EmitObjCWeakRead - Code gen for loading value of a __weak
04119 /// object: objc_read_weak (id *src)
04120 ///
04121 llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
04122                                           llvm::Value *AddrWeakObj) {
04123   llvm::Type* DestTy =
04124     cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
04125   AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj,
04126                                           ObjCTypes.PtrObjectPtrTy);
04127   llvm::Value *read_weak =
04128     CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(),
04129                                 AddrWeakObj, "weakread");
04130   read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
04131   return read_weak;
04132 }
04133 
04134 /// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
04135 /// objc_assign_weak (id src, id *dst)
04136 ///
04137 void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
04138                                    llvm::Value *src, llvm::Value *dst) {
04139   llvm::Type * SrcTy = src->getType();
04140   if (!isa<llvm::PointerType>(SrcTy)) {
04141     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
04142     assert(Size <= 8 && "does not support size > 8");
04143     src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
04144       : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
04145     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
04146   }
04147   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
04148   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
04149   llvm::Value *args[] = { src, dst };
04150   CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(),
04151                               args, "weakassign");
04152   return;
04153 }
04154 
04155 /// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
04156 /// objc_assign_global (id src, id *dst)
04157 ///
04158 void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
04159                                      llvm::Value *src, llvm::Value *dst,
04160                                      bool threadlocal) {
04161   llvm::Type * SrcTy = src->getType();
04162   if (!isa<llvm::PointerType>(SrcTy)) {
04163     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
04164     assert(Size <= 8 && "does not support size > 8");
04165     src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
04166       : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
04167     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
04168   }
04169   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
04170   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
04171   llvm::Value *args[] = { src, dst };
04172   if (!threadlocal)
04173     CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(),
04174                                 args, "globalassign");
04175   else
04176     CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(),
04177                                 args, "threadlocalassign");
04178   return;
04179 }
04180 
04181 /// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
04182 /// objc_assign_ivar (id src, id *dst, ptrdiff_t ivaroffset)
04183 ///
04184 void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
04185                                    llvm::Value *src, llvm::Value *dst,
04186                                    llvm::Value *ivarOffset) {
04187   assert(ivarOffset && "EmitObjCIvarAssign - ivarOffset is NULL");
04188   llvm::Type * SrcTy = src->getType();
04189   if (!isa<llvm::PointerType>(SrcTy)) {
04190     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
04191     assert(Size <= 8 && "does not support size > 8");
04192     src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
04193       : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
04194     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
04195   }
04196   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
04197   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
04198   llvm::Value *args[] = { src, dst, ivarOffset };
04199   CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args);
04200   return;
04201 }
04202 
04203 /// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
04204 /// objc_assign_strongCast (id src, id *dst)
04205 ///
04206 void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
04207                                          llvm::Value *src, llvm::Value *dst) {
04208   llvm::Type * SrcTy = src->getType();
04209   if (!isa<llvm::PointerType>(SrcTy)) {
04210     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
04211     assert(Size <= 8 && "does not support size > 8");
04212     src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
04213       : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
04214     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
04215   }
04216   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
04217   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
04218   llvm::Value *args[] = { src, dst };
04219   CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(),
04220                               args, "weakassign");
04221   return;
04222 }
04223 
04224 void CGObjCMac::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
04225                                          llvm::Value *DestPtr,
04226                                          llvm::Value *SrcPtr,
04227                                          llvm::Value *size) {
04228   SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
04229   DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
04230   llvm::Value *args[] = { DestPtr, SrcPtr, size };
04231   CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args);
04232 }
04233 
04234 /// EmitObjCValueForIvar - Code Gen for ivar reference.
04235 ///
04236 LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
04237                                        QualType ObjectTy,
04238                                        llvm::Value *BaseValue,
04239                                        const ObjCIvarDecl *Ivar,
04240                                        unsigned CVRQualifiers) {
04241   const ObjCInterfaceDecl *ID =
04242     ObjectTy->getAs<ObjCObjectType>()->getInterface();
04243   return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
04244                                   EmitIvarOffset(CGF, ID, Ivar));
04245 }
04246 
04247 llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
04248                                        const ObjCInterfaceDecl *Interface,
04249                                        const ObjCIvarDecl *Ivar) {
04250   uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
04251   return llvm::ConstantInt::get(
04252     CGM.getTypes().ConvertType(CGM.getContext().LongTy),
04253     Offset);
04254 }
04255 
04256 /* *** Private Interface *** */
04257 
04258 /// EmitImageInfo - Emit the image info marker used to encode some module
04259 /// level information.
04260 ///
04261 /// See: <rdr://4810609&4810587&4810587>
04262 /// struct IMAGE_INFO {
04263 ///   unsigned version;
04264 ///   unsigned flags;
04265 /// };
04266 enum ImageInfoFlags {
04267   eImageInfo_FixAndContinue      = (1 << 0), // This flag is no longer set by clang.
04268   eImageInfo_GarbageCollected    = (1 << 1),
04269   eImageInfo_GCOnly              = (1 << 2),
04270   eImageInfo_OptimizedByDyld     = (1 << 3), // This flag is set by the dyld shared cache.
04271 
04272   // A flag indicating that the module has no instances of a @synthesize of a
04273   // superclass variable. <rdar://problem/6803242>
04274   eImageInfo_CorrectedSynthesize = (1 << 4), // This flag is no longer set by clang.
04275   eImageInfo_ImageIsSimulated    = (1 << 5)
04276 };
04277 
04278 void CGObjCCommonMac::EmitImageInfo() {
04279   unsigned version = 0; // Version is unused?
04280   const char *Section = (ObjCABI == 1) ?
04281     "__OBJC, __image_info,regular" :
04282     "__DATA, __objc_imageinfo, regular, no_dead_strip";
04283 
04284   // Generate module-level named metadata to convey this information to the
04285   // linker and code-gen.
04286   llvm::Module &Mod = CGM.getModule();
04287 
04288   // Add the ObjC ABI version to the module flags.
04289   Mod.addModuleFlag(llvm::Module::Error, "Objective-C Version", ObjCABI);
04290   Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Version",
04291                     version);
04292   Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Section",
04293                     llvm::MDString::get(VMContext,Section));
04294 
04295   if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
04296     // Non-GC overrides those files which specify GC.
04297     Mod.addModuleFlag(llvm::Module::Override,
04298                       "Objective-C Garbage Collection", (uint32_t)0);
04299   } else {
04300     // Add the ObjC garbage collection value.
04301     Mod.addModuleFlag(llvm::Module::Error,
04302                       "Objective-C Garbage Collection",
04303                       eImageInfo_GarbageCollected);
04304 
04305     if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
04306       // Add the ObjC GC Only value.
04307       Mod.addModuleFlag(llvm::Module::Error, "Objective-C GC Only",
04308                         eImageInfo_GCOnly);
04309 
04310       // Require that GC be specified and set to eImageInfo_GarbageCollected.
04311       llvm::Value *Ops[2] = {
04312         llvm::MDString::get(VMContext, "Objective-C Garbage Collection"),
04313         llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
04314                                eImageInfo_GarbageCollected)
04315       };
04316       Mod.addModuleFlag(llvm::Module::Require, "Objective-C GC Only",
04317                         llvm::MDNode::get(VMContext, Ops));
04318     }
04319   }
04320 
04321   // Indicate whether we're compiling this to run on a simulator.
04322   const llvm::Triple &Triple = CGM.getTarget().getTriple();
04323   if (Triple.isiOS() &&
04324       (Triple.getArch() == llvm::Triple::x86 ||
04325        Triple.getArch() == llvm::Triple::x86_64))
04326     Mod.addModuleFlag(llvm::Module::Error, "Objective-C Is Simulated",
04327                       eImageInfo_ImageIsSimulated);
04328 }
04329 
04330 // struct objc_module {
04331 //   unsigned long version;
04332 //   unsigned long size;
04333 //   const char *name;
04334 //   Symtab symtab;
04335 // };
04336 
04337 // FIXME: Get from somewhere
04338 static const int ModuleVersion = 7;
04339 
04340 void CGObjCMac::EmitModuleInfo() {
04341   uint64_t Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ModuleTy);
04342 
04343   llvm::Constant *Values[] = {
04344     llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion),
04345     llvm::ConstantInt::get(ObjCTypes.LongTy, Size),
04346     // This used to be the filename, now it is unused. <rdr://4327263>
04347     GetClassName(StringRef("")),
04348     EmitModuleSymbols()
04349   };
04350   CreateMetadataVar("\01L_OBJC_MODULES",
04351                     llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
04352                     "__OBJC,__module_info,regular,no_dead_strip",
04353                     4, true);
04354 }
04355 
04356 llvm::Constant *CGObjCMac::EmitModuleSymbols() {
04357   unsigned NumClasses = DefinedClasses.size();
04358   unsigned NumCategories = DefinedCategories.size();
04359 
04360   // Return null if no symbols were defined.
04361   if (!NumClasses && !NumCategories)
04362     return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
04363 
04364   llvm::Constant *Values[5];
04365   Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
04366   Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
04367   Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
04368   Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
04369 
04370   // The runtime expects exactly the list of defined classes followed
04371   // by the list of defined categories, in a single array.
04372   SmallVector<llvm::Constant*, 8> Symbols(NumClasses + NumCategories);
04373   for (unsigned i=0; i<NumClasses; i++) {
04374     const ObjCInterfaceDecl *ID = ImplementedClasses[i];
04375     assert(ID);
04376     if (ObjCImplementationDecl *IMP = ID->getImplementation())
04377       // We are implementing a weak imported interface. Give it external linkage
04378       if (ID->isWeakImported() && !IMP->isWeakImported())
04379         DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
04380     
04381     Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
04382                                                 ObjCTypes.Int8PtrTy);
04383   }
04384   for (unsigned i=0; i<NumCategories; i++)
04385     Symbols[NumClasses + i] =
04386       llvm::ConstantExpr::getBitCast(DefinedCategories[i],
04387                                      ObjCTypes.Int8PtrTy);
04388 
04389   Values[4] =
04390     llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
04391                                                   Symbols.size()),
04392                              Symbols);
04393 
04394   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
04395 
04396   llvm::GlobalVariable *GV =
04397     CreateMetadataVar("\01L_OBJC_SYMBOLS", Init,
04398                       "__OBJC,__symbols,regular,no_dead_strip",
04399                       4, true);
04400   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
04401 }
04402 
04403 llvm::Value *CGObjCMac::EmitClassRefFromId(CodeGenFunction &CGF,
04404                                            IdentifierInfo *II) {
04405   LazySymbols.insert(II);
04406   
04407   llvm::GlobalVariable *&Entry = ClassReferences[II];
04408   
04409   if (!Entry) {
04410     llvm::Constant *Casted =
04411     llvm::ConstantExpr::getBitCast(GetClassName(II->getName()),
04412                                    ObjCTypes.ClassPtrTy);
04413     Entry =
04414     CreateMetadataVar("\01L_OBJC_CLASS_REFERENCES_", Casted,
04415                       "__OBJC,__cls_refs,literal_pointers,no_dead_strip",
04416                       4, true);
04417   }
04418   
04419   return CGF.Builder.CreateLoad(Entry);
04420 }
04421 
04422 llvm::Value *CGObjCMac::EmitClassRef(CodeGenFunction &CGF,
04423                                      const ObjCInterfaceDecl *ID) {
04424   return EmitClassRefFromId(CGF, ID->getIdentifier());
04425 }
04426 
04427 llvm::Value *CGObjCMac::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
04428   IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
04429   return EmitClassRefFromId(CGF, II);
04430 }
04431 
04432 llvm::Value *CGObjCMac::EmitSelector(CodeGenFunction &CGF, Selector Sel,
04433                                      bool lvalue) {
04434   llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
04435 
04436   if (!Entry) {
04437     llvm::Constant *Casted =
04438       llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
04439                                      ObjCTypes.SelectorPtrTy);
04440     Entry =
04441       CreateMetadataVar("\01L_OBJC_SELECTOR_REFERENCES_", Casted,
04442                         "__OBJC,__message_refs,literal_pointers,no_dead_strip",
04443                         4, true);
04444     Entry->setExternallyInitialized(true);
04445   }
04446 
04447   if (lvalue)
04448     return Entry;
04449   return CGF.Builder.CreateLoad(Entry);
04450 }
04451 
04452 llvm::Constant *CGObjCCommonMac::GetClassName(StringRef RuntimeName) {
04453     llvm::GlobalVariable *&Entry = ClassNames[RuntimeName];
04454     if (!Entry)
04455         Entry = CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
04456                                   llvm::ConstantDataArray::getString(VMContext,
04457                                                                      RuntimeName),
04458                                   ((ObjCABI == 2) ?
04459                                    "__TEXT,__objc_classname,cstring_literals" :
04460                                    "__TEXT,__cstring,cstring_literals"),
04461                                   1, true);
04462     return getConstantGEP(VMContext, Entry, 0, 0);
04463 }
04464 
04465 llvm::Function *CGObjCCommonMac::GetMethodDefinition(const ObjCMethodDecl *MD) {
04466   llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*>::iterator
04467       I = MethodDefinitions.find(MD);
04468   if (I != MethodDefinitions.end())
04469     return I->second;
04470 
04471   return nullptr;
04472 }
04473 
04474 /// GetIvarLayoutName - Returns a unique constant for the given
04475 /// ivar layout bitmap.
04476 llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
04477                                        const ObjCCommonTypesHelper &ObjCTypes) {
04478   return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
04479 }
04480 
04481 void CGObjCCommonMac::BuildAggrIvarRecordLayout(const RecordType *RT,
04482                                                 unsigned int BytePos,
04483                                                 bool ForStrongLayout,
04484                                                 bool &HasUnion) {
04485   const RecordDecl *RD = RT->getDecl();
04486   // FIXME - Use iterator.
04487   SmallVector<const FieldDecl*, 16> Fields(RD->fields());
04488   llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
04489   const llvm::StructLayout *RecLayout =
04490     CGM.getDataLayout().getStructLayout(cast<llvm::StructType>(Ty));
04491 
04492   BuildAggrIvarLayout(nullptr, RecLayout, RD, Fields, BytePos, ForStrongLayout,
04493                       HasUnion);
04494 }
04495 
04496 void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
04497                              const llvm::StructLayout *Layout,
04498                              const RecordDecl *RD,
04499                              ArrayRef<const FieldDecl*> RecFields,
04500                              unsigned int BytePos, bool ForStrongLayout,
04501                              bool &HasUnion) {
04502   bool IsUnion = (RD && RD->isUnion());
04503   uint64_t MaxUnionIvarSize = 0;
04504   uint64_t MaxSkippedUnionIvarSize = 0;
04505   const FieldDecl *MaxField = nullptr;
04506   const FieldDecl *MaxSkippedField = nullptr;
04507   const FieldDecl *LastFieldBitfieldOrUnnamed = nullptr;
04508   uint64_t MaxFieldOffset = 0;
04509   uint64_t MaxSkippedFieldOffset = 0;
04510   uint64_t LastBitfieldOrUnnamedOffset = 0;
04511   uint64_t FirstFieldDelta = 0;
04512 
04513   if (RecFields.empty())
04514     return;
04515   unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
04516   unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
04517   if (!RD && CGM.getLangOpts().ObjCAutoRefCount) {
04518     const FieldDecl *FirstField = RecFields[0];
04519     FirstFieldDelta = 
04520       ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(FirstField));
04521   }
04522   
04523   for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
04524     const FieldDecl *Field = RecFields[i];
04525     uint64_t FieldOffset;
04526     if (RD) {
04527       // Note that 'i' here is actually the field index inside RD of Field,
04528       // although this dependency is hidden.
04529       const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
04530       FieldOffset = (RL.getFieldOffset(i) / ByteSizeInBits) - FirstFieldDelta;
04531     } else
04532       FieldOffset = 
04533         ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field)) - FirstFieldDelta;
04534 
04535     // Skip over unnamed or bitfields
04536     if (!Field->getIdentifier() || Field->isBitField()) {
04537       LastFieldBitfieldOrUnnamed = Field;
04538       LastBitfieldOrUnnamedOffset = FieldOffset;
04539       continue;
04540     }
04541 
04542     LastFieldBitfieldOrUnnamed = nullptr;
04543     QualType FQT = Field->getType();
04544     if (FQT->isRecordType() || FQT->isUnionType()) {
04545       if (FQT->isUnionType())
04546         HasUnion = true;
04547 
04548       BuildAggrIvarRecordLayout(FQT->getAs<RecordType>(),
04549                                 BytePos + FieldOffset,
04550                                 ForStrongLayout, HasUnion);
04551       continue;
04552     }
04553 
04554     if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
04555       const ConstantArrayType *CArray =
04556         dyn_cast_or_null<ConstantArrayType>(Array);
04557       uint64_t ElCount = CArray->getSize().getZExtValue();
04558       assert(CArray && "only array with known element size is supported");
04559       FQT = CArray->getElementType();
04560       while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
04561         const ConstantArrayType *CArray =
04562           dyn_cast_or_null<ConstantArrayType>(Array);
04563         ElCount *= CArray->getSize().getZExtValue();
04564         FQT = CArray->getElementType();
04565       }
04566       if (FQT->isRecordType() && ElCount) {
04567         int OldIndex = IvarsInfo.size() - 1;
04568         int OldSkIndex = SkipIvars.size() -1;
04569 
04570         const RecordType *RT = FQT->getAs<RecordType>();
04571         BuildAggrIvarRecordLayout(RT, BytePos + FieldOffset,
04572                                   ForStrongLayout, HasUnion);
04573 
04574         // Replicate layout information for each array element. Note that
04575         // one element is already done.
04576         uint64_t ElIx = 1;
04577         for (int FirstIndex = IvarsInfo.size() - 1,
04578                FirstSkIndex = SkipIvars.size() - 1 ;ElIx < ElCount; ElIx++) {
04579           uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
04580           for (int i = OldIndex+1; i <= FirstIndex; ++i)
04581             IvarsInfo.push_back(GC_IVAR(IvarsInfo[i].ivar_bytepos + Size*ElIx,
04582                                         IvarsInfo[i].ivar_size));
04583           for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i)
04584             SkipIvars.push_back(GC_IVAR(SkipIvars[i].ivar_bytepos + Size*ElIx,
04585                                         SkipIvars[i].ivar_size));
04586         }
04587         continue;
04588       }
04589     }
04590     // At this point, we are done with Record/Union and array there of.
04591     // For other arrays we are down to its element type.
04592     Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), FQT);
04593 
04594     unsigned FieldSize = CGM.getContext().getTypeSize(Field->getType());
04595     if ((ForStrongLayout && GCAttr == Qualifiers::Strong)
04596         || (!ForStrongLayout && GCAttr == Qualifiers::Weak)) {
04597       if (IsUnion) {
04598         uint64_t UnionIvarSize = FieldSize / WordSizeInBits;
04599         if (UnionIvarSize > MaxUnionIvarSize) {
04600           MaxUnionIvarSize = UnionIvarSize;
04601           MaxField = Field;
04602           MaxFieldOffset = FieldOffset;
04603         }
04604       } else {
04605         IvarsInfo.push_back(GC_IVAR(BytePos + FieldOffset,
04606                                     FieldSize / WordSizeInBits));
04607       }
04608     } else if ((ForStrongLayout &&
04609                 (GCAttr == Qualifiers::GCNone || GCAttr == Qualifiers::Weak))
04610                || (!ForStrongLayout && GCAttr != Qualifiers::Weak)) {
04611       if (IsUnion) {
04612         // FIXME: Why the asymmetry? We divide by word size in bits on other
04613         // side.
04614         uint64_t UnionIvarSize = FieldSize / ByteSizeInBits;
04615         if (UnionIvarSize > MaxSkippedUnionIvarSize) {
04616           MaxSkippedUnionIvarSize = UnionIvarSize;
04617           MaxSkippedField = Field;
04618           MaxSkippedFieldOffset = FieldOffset;
04619         }
04620       } else {
04621         // FIXME: Why the asymmetry, we divide by byte size in bits here?
04622         SkipIvars.push_back(GC_IVAR(BytePos + FieldOffset,
04623                                     FieldSize / ByteSizeInBits));
04624       }
04625     }
04626   }
04627 
04628   if (LastFieldBitfieldOrUnnamed) {
04629     if (LastFieldBitfieldOrUnnamed->isBitField()) {
04630       // Last field was a bitfield. Must update skip info.
04631       uint64_t BitFieldSize
04632           = LastFieldBitfieldOrUnnamed->getBitWidthValue(CGM.getContext());
04633       GC_IVAR skivar;
04634       skivar.ivar_bytepos = BytePos + LastBitfieldOrUnnamedOffset;
04635       skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
04636         + ((BitFieldSize % ByteSizeInBits) != 0);
04637       SkipIvars.push_back(skivar);
04638     } else {
04639       assert(!LastFieldBitfieldOrUnnamed->getIdentifier() &&"Expected unnamed");
04640       // Last field was unnamed. Must update skip info.
04641       unsigned FieldSize
04642           = CGM.getContext().getTypeSize(LastFieldBitfieldOrUnnamed->getType());
04643       SkipIvars.push_back(GC_IVAR(BytePos + LastBitfieldOrUnnamedOffset,
04644                                   FieldSize / ByteSizeInBits));
04645     }
04646   }
04647 
04648   if (MaxField)
04649     IvarsInfo.push_back(GC_IVAR(BytePos + MaxFieldOffset,
04650                                 MaxUnionIvarSize));
04651   if (MaxSkippedField)
04652     SkipIvars.push_back(GC_IVAR(BytePos + MaxSkippedFieldOffset,
04653                                 MaxSkippedUnionIvarSize));
04654 }
04655 
04656 /// BuildIvarLayoutBitmap - This routine is the horsework for doing all
04657 /// the computations and returning the layout bitmap (for ivar or blocks) in
04658 /// the given argument BitMap string container. Routine reads
04659 /// two containers, IvarsInfo and SkipIvars which are assumed to be
04660 /// filled already by the caller.
04661 llvm::Constant *CGObjCCommonMac::BuildIvarLayoutBitmap(std::string &BitMap) {
04662   unsigned int WordsToScan, WordsToSkip;
04663   llvm::Type *PtrTy = CGM.Int8PtrTy;
04664   
04665   // Build the string of skip/scan nibbles
04666   SmallVector<SKIP_SCAN, 32> SkipScanIvars;
04667   unsigned int WordSize =
04668   CGM.getTypes().getDataLayout().getTypeAllocSize(PtrTy);
04669   if (IvarsInfo[0].ivar_bytepos == 0) {
04670     WordsToSkip = 0;
04671     WordsToScan = IvarsInfo[0].ivar_size;
04672   } else {
04673     WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
04674     WordsToScan = IvarsInfo[0].ivar_size;
04675   }
04676   for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++) {
04677     unsigned int TailPrevGCObjC =
04678     IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
04679     if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC) {
04680       // consecutive 'scanned' object pointers.
04681       WordsToScan += IvarsInfo[i].ivar_size;
04682     } else {
04683       // Skip over 'gc'able object pointer which lay over each other.
04684       if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
04685         continue;
04686       // Must skip over 1 or more words. We save current skip/scan values
04687       //  and start a new pair.
04688       SKIP_SCAN SkScan;
04689       SkScan.skip = WordsToSkip;
04690       SkScan.scan = WordsToScan;
04691       SkipScanIvars.push_back(SkScan);
04692       
04693       // Skip the hole.
04694       SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
04695       SkScan.scan = 0;
04696       SkipScanIvars.push_back(SkScan);
04697       WordsToSkip = 0;
04698       WordsToScan = IvarsInfo[i].ivar_size;
04699     }
04700   }
04701   if (WordsToScan > 0) {
04702     SKIP_SCAN SkScan;
04703     SkScan.skip = WordsToSkip;
04704     SkScan.scan = WordsToScan;
04705     SkipScanIvars.push_back(SkScan);
04706   }
04707   
04708   if (!SkipIvars.empty()) {
04709     unsigned int LastIndex = SkipIvars.size()-1;
04710     int LastByteSkipped =
04711     SkipIvars[LastIndex].ivar_bytepos + SkipIvars[LastIndex].ivar_size;
04712     LastIndex = IvarsInfo.size()-1;
04713     int LastByteScanned =
04714     IvarsInfo[LastIndex].ivar_bytepos +
04715     IvarsInfo[LastIndex].ivar_size * WordSize;
04716     // Compute number of bytes to skip at the tail end of the last ivar scanned.
04717     if (LastByteSkipped > LastByteScanned) {
04718       unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
04719       SKIP_SCAN SkScan;
04720       SkScan.skip = TotalWords - (LastByteScanned/WordSize);
04721       SkScan.scan = 0;
04722       SkipScanIvars.push_back(SkScan);
04723     }
04724   }
04725   // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
04726   // as 0xMN.
04727   int SkipScan = SkipScanIvars.size()-1;
04728   for (int i = 0; i <= SkipScan; i++) {
04729     if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
04730         && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
04731       // 0xM0 followed by 0x0N detected.
04732       SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
04733       for (int j = i+1; j < SkipScan; j++)
04734         SkipScanIvars[j] = SkipScanIvars[j+1];
04735       --SkipScan;
04736     }
04737   }
04738   
04739   // Generate the string.
04740   for (int i = 0; i <= SkipScan; i++) {
04741     unsigned char byte;
04742     unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
04743     unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
04744     unsigned int skip_big  = SkipScanIvars[i].skip / 0xf;
04745     unsigned int scan_big  = SkipScanIvars[i].scan / 0xf;
04746     
04747     // first skip big.
04748     for (unsigned int ix = 0; ix < skip_big; ix++)
04749       BitMap += (unsigned char)(0xf0);
04750     
04751     // next (skip small, scan)
04752     if (skip_small) {
04753       byte = skip_small << 4;
04754       if (scan_big > 0) {
04755         byte |= 0xf;
04756         --scan_big;
04757       } else if (scan_small) {
04758         byte |= scan_small;
04759         scan_small = 0;
04760       }
04761       BitMap += byte;
04762     }
04763     // next scan big
04764     for (unsigned int ix = 0; ix < scan_big; ix++)
04765       BitMap += (unsigned char)(0x0f);
04766     // last scan small
04767     if (scan_small) {
04768       byte = scan_small;
04769       BitMap += byte;
04770     }
04771   }
04772   // null terminate string.
04773   unsigned char zero = 0;
04774   BitMap += zero;
04775   
04776   llvm::GlobalVariable * Entry =
04777   CreateMetadataVar("\01L_OBJC_CLASS_NAME_",
04778                     llvm::ConstantDataArray::getString(VMContext, BitMap,false),
04779                     ((ObjCABI == 2) ?
04780                      "__TEXT,__objc_classname,cstring_literals" :
04781                      "__TEXT,__cstring,cstring_literals"),
04782                     1, true);
04783   return getConstantGEP(VMContext, Entry, 0, 0);
04784 }
04785 
04786 /// BuildIvarLayout - Builds ivar layout bitmap for the class
04787 /// implementation for the __strong or __weak case.
04788 /// The layout map displays which words in ivar list must be skipped
04789 /// and which must be scanned by GC (see below). String is built of bytes.
04790 /// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
04791 /// of words to skip and right nibble is count of words to scan. So, each
04792 /// nibble represents up to 15 workds to skip or scan. Skipping the rest is
04793 /// represented by a 0x00 byte which also ends the string.
04794 /// 1. when ForStrongLayout is true, following ivars are scanned:
04795 /// - id, Class
04796 /// - object *
04797 /// - __strong anything
04798 ///
04799 /// 2. When ForStrongLayout is false, following ivars are scanned:
04800 /// - __weak anything
04801 ///
04802 llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
04803   const ObjCImplementationDecl *OMD,
04804   bool ForStrongLayout) {
04805   bool hasUnion = false;
04806 
04807   llvm::Type *PtrTy = CGM.Int8PtrTy;
04808   if (CGM.getLangOpts().getGC() == LangOptions::NonGC &&
04809       !CGM.getLangOpts().ObjCAutoRefCount)
04810     return llvm::Constant::getNullValue(PtrTy);
04811 
04812   const ObjCInterfaceDecl *OI = OMD->getClassInterface();
04813   SmallVector<const FieldDecl*, 32> RecFields;
04814   if (CGM.getLangOpts().ObjCAutoRefCount) {
04815     for (const ObjCIvarDecl *IVD = OI->all_declared_ivar_begin(); 
04816          IVD; IVD = IVD->getNextIvar())
04817       RecFields.push_back(cast<FieldDecl>(IVD));
04818   }
04819   else {
04820     SmallVector<const ObjCIvarDecl*, 32> Ivars;
04821     CGM.getContext().DeepCollectObjCIvars(OI, true, Ivars);
04822 
04823     // FIXME: This is not ideal; we shouldn't have to do this copy.
04824     RecFields.append(Ivars.begin(), Ivars.end());
04825   }
04826 
04827   if (RecFields.empty())
04828     return llvm::Constant::getNullValue(PtrTy);
04829 
04830   SkipIvars.clear();
04831   IvarsInfo.clear();
04832 
04833   BuildAggrIvarLayout(OMD, nullptr, nullptr, RecFields, 0, ForStrongLayout,
04834                       hasUnion);
04835   if (IvarsInfo.empty())
04836     return llvm::Constant::getNullValue(PtrTy);
04837   // Sort on byte position in case we encounterred a union nested in
04838   // the ivar list.
04839   if (hasUnion && !IvarsInfo.empty())
04840     std::sort(IvarsInfo.begin(), IvarsInfo.end());
04841   if (hasUnion && !SkipIvars.empty())
04842     std::sort(SkipIvars.begin(), SkipIvars.end());
04843   
04844   std::string BitMap;
04845   llvm::Constant *C = BuildIvarLayoutBitmap(BitMap);
04846   
04847    if (CGM.getLangOpts().ObjCGCBitmapPrint) {
04848     printf("\n%s ivar layout for class '%s': ",
04849            ForStrongLayout ? "strong" : "weak",
04850            OMD->getClassInterface()->getName().str().c_str());
04851     const unsigned char *s = (const unsigned char*)BitMap.c_str();
04852     for (unsigned i = 0, e = BitMap.size(); i < e; i++)
04853       if (!(s[i] & 0xf0))
04854         printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
04855       else
04856         printf("0x%x%s",  s[i], s[i] != 0 ? ", " : "");
04857     printf("\n");
04858   }
04859   return C;
04860 }
04861 
04862 llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
04863   llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
04864 
04865   // FIXME: Avoid std::string in "Sel.getAsString()"
04866   if (!Entry)
04867     Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_NAME_",
04868                llvm::ConstantDataArray::getString(VMContext, Sel.getAsString()),
04869                               ((ObjCABI == 2) ?
04870                                "__TEXT,__objc_methname,cstring_literals" :
04871                                "__TEXT,__cstring,cstring_literals"),
04872                               1, true);
04873 
04874   return getConstantGEP(VMContext, Entry, 0, 0);
04875 }
04876 
04877 // FIXME: Merge into a single cstring creation function.
04878 llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
04879   return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
04880 }
04881 
04882 llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
04883   std::string TypeStr;
04884   CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
04885 
04886   llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
04887 
04888   if (!Entry)
04889     Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
04890                          llvm::ConstantDataArray::getString(VMContext, TypeStr),
04891                               ((ObjCABI == 2) ?
04892                                "__TEXT,__objc_methtype,cstring_literals" :
04893                                "__TEXT,__cstring,cstring_literals"),
04894                               1, true);
04895 
04896   return getConstantGEP(VMContext, Entry, 0, 0);
04897 }
04898 
04899 llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D,
04900                                                   bool Extended) {
04901   std::string TypeStr;
04902   if (CGM.getContext().getObjCEncodingForMethodDecl(D, TypeStr, Extended))
04903     return nullptr;
04904 
04905   llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
04906 
04907   if (!Entry)
04908     Entry = CreateMetadataVar("\01L_OBJC_METH_VAR_TYPE_",
04909                          llvm::ConstantDataArray::getString(VMContext, TypeStr),
04910                               ((ObjCABI == 2) ?
04911                                "__TEXT,__objc_methtype,cstring_literals" :
04912                                "__TEXT,__cstring,cstring_literals"),
04913                               1, true);
04914 
04915   return getConstantGEP(VMContext, Entry, 0, 0);
04916 }
04917 
04918 // FIXME: Merge into a single cstring creation function.
04919 llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
04920   llvm::GlobalVariable *&Entry = PropertyNames[Ident];
04921 
04922   if (!Entry)
04923     Entry = CreateMetadataVar(
04924         "\01L_OBJC_PROP_NAME_ATTR_",
04925         llvm::ConstantDataArray::getString(VMContext, Ident->getName()),
04926         "__TEXT,__cstring,cstring_literals", 1, true);
04927 
04928   return getConstantGEP(VMContext, Entry, 0, 0);
04929 }
04930 
04931 // FIXME: Merge into a single cstring creation function.
04932 // FIXME: This Decl should be more precise.
04933 llvm::Constant *
04934 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
04935                                        const Decl *Container) {
04936   std::string TypeStr;
04937   CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
04938   return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
04939 }
04940 
04941 void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
04942                                        const ObjCContainerDecl *CD,
04943                                        SmallVectorImpl<char> &Name) {
04944   llvm::raw_svector_ostream OS(Name);
04945   assert (CD && "Missing container decl in GetNameForMethod");
04946   OS << '\01' << (D->isInstanceMethod() ? '-' : '+')
04947      << '[' << CD->getName();
04948   if (const ObjCCategoryImplDecl *CID =
04949       dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext()))
04950     OS << '(' << *CID << ')';
04951   OS << ' ' << D->getSelector().getAsString() << ']';
04952 }
04953 
04954 void CGObjCMac::FinishModule() {
04955   EmitModuleInfo();
04956 
04957   // Emit the dummy bodies for any protocols which were referenced but
04958   // never defined.
04959   for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
04960          I = Protocols.begin(), e = Protocols.end(); I != e; ++I) {
04961     if (I->second->hasInitializer())
04962       continue;
04963 
04964     llvm::Constant *Values[5];
04965     Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
04966     Values[1] = GetClassName(I->first->getName());
04967     Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
04968     Values[3] = Values[4] =
04969       llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
04970     assertPrivateName(I->second);
04971     I->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
04972                                                         Values));
04973     CGM.addCompilerUsedGlobal(I->second);
04974   }
04975 
04976   // Add assembler directives to add lazy undefined symbol references
04977   // for classes which are referenced but not defined. This is
04978   // important for correct linker interaction.
04979   //
04980   // FIXME: It would be nice if we had an LLVM construct for this.
04981   if (!LazySymbols.empty() || !DefinedSymbols.empty()) {
04982     SmallString<256> Asm;
04983     Asm += CGM.getModule().getModuleInlineAsm();
04984     if (!Asm.empty() && Asm.back() != '\n')
04985       Asm += '\n';
04986 
04987     llvm::raw_svector_ostream OS(Asm);
04988     for (llvm::SetVector<IdentifierInfo*>::iterator I = DefinedSymbols.begin(),
04989            e = DefinedSymbols.end(); I != e; ++I)
04990       OS << "\t.objc_class_name_" << (*I)->getName() << "=0\n"
04991          << "\t.globl .objc_class_name_" << (*I)->getName() << "\n";
04992     for (llvm::SetVector<IdentifierInfo*>::iterator I = LazySymbols.begin(),
04993          e = LazySymbols.end(); I != e; ++I) {
04994       OS << "\t.lazy_reference .objc_class_name_" << (*I)->getName() << "\n";
04995     }
04996 
04997     for (size_t i = 0, e = DefinedCategoryNames.size(); i < e; ++i) {
04998       OS << "\t.objc_category_name_" << DefinedCategoryNames[i] << "=0\n"
04999          << "\t.globl .objc_category_name_" << DefinedCategoryNames[i] << "\n";
05000     }
05001     
05002     CGM.getModule().setModuleInlineAsm(OS.str());
05003   }
05004 }
05005 
05006 CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
05007   : CGObjCCommonMac(cgm),
05008     ObjCTypes(cgm) {
05009   ObjCEmptyCacheVar = ObjCEmptyVtableVar = nullptr;
05010   ObjCABI = 2;
05011 }
05012 
05013 /* *** */
05014 
05015 ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
05016   : VMContext(cgm.getLLVMContext()), CGM(cgm), ExternalProtocolPtrTy(nullptr)
05017 {
05018   CodeGen::CodeGenTypes &Types = CGM.getTypes();
05019   ASTContext &Ctx = CGM.getContext();
05020 
05021   ShortTy = Types.ConvertType(Ctx.ShortTy);
05022   IntTy = Types.ConvertType(Ctx.IntTy);
05023   LongTy = Types.ConvertType(Ctx.LongTy);
05024   LongLongTy = Types.ConvertType(Ctx.LongLongTy);
05025   Int8PtrTy = CGM.Int8PtrTy;
05026   Int8PtrPtrTy = CGM.Int8PtrPtrTy;
05027 
05028   // arm64 targets use "int" ivar offset variables. All others,
05029   // including OS X x86_64 and Windows x86_64, use "long" ivar offsets.
05030   if (CGM.getTarget().getTriple().getArch() == llvm::Triple::aarch64)
05031     IvarOffsetVarTy = IntTy;
05032   else
05033     IvarOffsetVarTy = LongTy;
05034 
05035   ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
05036   PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
05037   SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
05038 
05039   // I'm not sure I like this. The implicit coordination is a bit
05040   // gross. We should solve this in a reasonable fashion because this
05041   // is a pretty common task (match some runtime data structure with
05042   // an LLVM data structure).
05043 
05044   // FIXME: This is leaked.
05045   // FIXME: Merge with rewriter code?
05046 
05047   // struct _objc_super {
05048   //   id self;
05049   //   Class cls;
05050   // }
05051   RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct,
05052                                       Ctx.getTranslationUnitDecl(),
05053                                       SourceLocation(), SourceLocation(),
05054                                       &Ctx.Idents.get("_objc_super"));
05055   RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
05056                                 nullptr, Ctx.getObjCIdType(), nullptr, nullptr,
05057                                 false, ICIS_NoInit));
05058   RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
05059                                 nullptr, Ctx.getObjCClassType(), nullptr,
05060                                 nullptr, false, ICIS_NoInit));
05061   RD->completeDefinition();
05062 
05063   SuperCTy = Ctx.getTagDeclType(RD);
05064   SuperPtrCTy = Ctx.getPointerType(SuperCTy);
05065 
05066   SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
05067   SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
05068 
05069   // struct _prop_t {
05070   //   char *name;
05071   //   char *attributes;
05072   // }
05073   PropertyTy = llvm::StructType::create("struct._prop_t",
05074                                         Int8PtrTy, Int8PtrTy, NULL);
05075 
05076   // struct _prop_list_t {
05077   //   uint32_t entsize;      // sizeof(struct _prop_t)
05078   //   uint32_t count_of_properties;
05079   //   struct _prop_t prop_list[count_of_properties];
05080   // }
05081   PropertyListTy =
05082     llvm::StructType::create("struct._prop_list_t", IntTy, IntTy,
05083                              llvm::ArrayType::get(PropertyTy, 0), NULL);
05084   // struct _prop_list_t *
05085   PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
05086 
05087   // struct _objc_method {
05088   //   SEL _cmd;
05089   //   char *method_type;
05090   //   char *_imp;
05091   // }
05092   MethodTy = llvm::StructType::create("struct._objc_method",
05093                                       SelectorPtrTy, Int8PtrTy, Int8PtrTy,
05094                                       NULL);
05095 
05096   // struct _objc_cache *
05097   CacheTy = llvm::StructType::create(VMContext, "struct._objc_cache");
05098   CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
05099     
05100 }
05101 
05102 ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
05103   : ObjCCommonTypesHelper(cgm) {
05104   // struct _objc_method_description {
05105   //   SEL name;
05106   //   char *types;
05107   // }
05108   MethodDescriptionTy =
05109     llvm::StructType::create("struct._objc_method_description",
05110                              SelectorPtrTy, Int8PtrTy, NULL);
05111 
05112   // struct _objc_method_description_list {
05113   //   int count;
05114   //   struct _objc_method_description[1];
05115   // }
05116   MethodDescriptionListTy =
05117     llvm::StructType::create("struct._objc_method_description_list",
05118                              IntTy,
05119                              llvm::ArrayType::get(MethodDescriptionTy, 0),NULL);
05120 
05121   // struct _objc_method_description_list *
05122   MethodDescriptionListPtrTy =
05123     llvm::PointerType::getUnqual(MethodDescriptionListTy);
05124 
05125   // Protocol description structures
05126 
05127   // struct _objc_protocol_extension {
05128   //   uint32_t size;  // sizeof(struct _objc_protocol_extension)
05129   //   struct _objc_method_description_list *optional_instance_methods;
05130   //   struct _objc_method_description_list *optional_class_methods;
05131   //   struct _objc_property_list *instance_properties;
05132   //   const char ** extendedMethodTypes;
05133   // }
05134   ProtocolExtensionTy =
05135     llvm::StructType::create("struct._objc_protocol_extension",
05136                              IntTy, MethodDescriptionListPtrTy,
05137                              MethodDescriptionListPtrTy, PropertyListPtrTy,
05138                              Int8PtrPtrTy, NULL);
05139 
05140   // struct _objc_protocol_extension *
05141   ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
05142 
05143   // Handle recursive construction of Protocol and ProtocolList types
05144 
05145   ProtocolTy =
05146     llvm::StructType::create(VMContext, "struct._objc_protocol");
05147 
05148   ProtocolListTy =
05149     llvm::StructType::create(VMContext, "struct._objc_protocol_list");
05150   ProtocolListTy->setBody(llvm::PointerType::getUnqual(ProtocolListTy),
05151                           LongTy,
05152                           llvm::ArrayType::get(ProtocolTy, 0),
05153                           NULL);
05154 
05155   // struct _objc_protocol {
05156   //   struct _objc_protocol_extension *isa;
05157   //   char *protocol_name;
05158   //   struct _objc_protocol **_objc_protocol_list;
05159   //   struct _objc_method_description_list *instance_methods;
05160   //   struct _objc_method_description_list *class_methods;
05161   // }
05162   ProtocolTy->setBody(ProtocolExtensionPtrTy, Int8PtrTy,
05163                       llvm::PointerType::getUnqual(ProtocolListTy),
05164                       MethodDescriptionListPtrTy,
05165                       MethodDescriptionListPtrTy,
05166                       NULL);
05167 
05168   // struct _objc_protocol_list *
05169   ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
05170 
05171   ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
05172 
05173   // Class description structures
05174 
05175   // struct _objc_ivar {
05176   //   char *ivar_name;
05177   //   char *ivar_type;
05178   //   int  ivar_offset;
05179   // }
05180   IvarTy = llvm::StructType::create("struct._objc_ivar",
05181                                     Int8PtrTy, Int8PtrTy, IntTy, NULL);
05182 
05183   // struct _objc_ivar_list *
05184   IvarListTy =
05185     llvm::StructType::create(VMContext, "struct._objc_ivar_list");
05186   IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
05187 
05188   // struct _objc_method_list *
05189   MethodListTy =
05190     llvm::StructType::create(VMContext, "struct._objc_method_list");
05191   MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
05192 
05193   // struct _objc_class_extension *
05194   ClassExtensionTy =
05195     llvm::StructType::create("struct._objc_class_extension",
05196                              IntTy, Int8PtrTy, PropertyListPtrTy, NULL);
05197   ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
05198 
05199   ClassTy = llvm::StructType::create(VMContext, "struct._objc_class");
05200 
05201   // struct _objc_class {
05202   //   Class isa;
05203   //   Class super_class;
05204   //   char *name;
05205   //   long version;
05206   //   long info;
05207   //   long instance_size;
05208   //   struct _objc_ivar_list *ivars;
05209   //   struct _objc_method_list *methods;
05210   //   struct _objc_cache *cache;
05211   //   struct _objc_protocol_list *protocols;
05212   //   char *ivar_layout;
05213   //   struct _objc_class_ext *ext;
05214   // };
05215   ClassTy->setBody(llvm::PointerType::getUnqual(ClassTy),
05216                    llvm::PointerType::getUnqual(ClassTy),
05217                    Int8PtrTy,
05218                    LongTy,
05219                    LongTy,
05220                    LongTy,
05221                    IvarListPtrTy,
05222                    MethodListPtrTy,
05223                    CachePtrTy,
05224                    ProtocolListPtrTy,
05225                    Int8PtrTy,
05226                    ClassExtensionPtrTy,
05227                    NULL);
05228 
05229   ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
05230 
05231   // struct _objc_category {
05232   //   char *category_name;
05233   //   char *class_name;
05234   //   struct _objc_method_list *instance_method;
05235   //   struct _objc_method_list *class_method;
05236   //   uint32_t size;  // sizeof(struct _objc_category)
05237   //   struct _objc_property_list *instance_properties;// category's @property
05238   // }
05239   CategoryTy =
05240     llvm::StructType::create("struct._objc_category",
05241                              Int8PtrTy, Int8PtrTy, MethodListPtrTy,
05242                              MethodListPtrTy, ProtocolListPtrTy,
05243                              IntTy, PropertyListPtrTy, NULL);
05244 
05245   // Global metadata structures
05246 
05247   // struct _objc_symtab {
05248   //   long sel_ref_cnt;
05249   //   SEL *refs;
05250   //   short cls_def_cnt;
05251   //   short cat_def_cnt;
05252   //   char *defs[cls_def_cnt + cat_def_cnt];
05253   // }
05254   SymtabTy =
05255     llvm::StructType::create("struct._objc_symtab",
05256                              LongTy, SelectorPtrTy, ShortTy, ShortTy,
05257                              llvm::ArrayType::get(Int8PtrTy, 0), NULL);
05258   SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
05259 
05260   // struct _objc_module {
05261   //   long version;
05262   //   long size;   // sizeof(struct _objc_module)
05263   //   char *name;
05264   //   struct _objc_symtab* symtab;
05265   //  }
05266   ModuleTy =
05267     llvm::StructType::create("struct._objc_module",
05268                              LongTy, LongTy, Int8PtrTy, SymtabPtrTy, NULL);
05269 
05270 
05271   // FIXME: This is the size of the setjmp buffer and should be target
05272   // specific. 18 is what's used on 32-bit X86.
05273   uint64_t SetJmpBufferSize = 18;
05274 
05275   // Exceptions
05276   llvm::Type *StackPtrTy = llvm::ArrayType::get(CGM.Int8PtrTy, 4);
05277 
05278   ExceptionDataTy =
05279     llvm::StructType::create("struct._objc_exception_data",
05280                              llvm::ArrayType::get(CGM.Int32Ty,SetJmpBufferSize),
05281                              StackPtrTy, NULL);
05282 
05283 }
05284 
05285 ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
05286   : ObjCCommonTypesHelper(cgm) {
05287   // struct _method_list_t {
05288   //   uint32_t entsize;  // sizeof(struct _objc_method)
05289   //   uint32_t method_count;
05290   //   struct _objc_method method_list[method_count];
05291   // }
05292   MethodListnfABITy =
05293     llvm::StructType::create("struct.__method_list_t", IntTy, IntTy,
05294                              llvm::ArrayType::get(MethodTy, 0), NULL);
05295   // struct method_list_t *
05296   MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
05297 
05298   // struct _protocol_t {
05299   //   id isa;  // NULL
05300   //   const char * const protocol_name;
05301   //   const struct _protocol_list_t * protocol_list; // super protocols
05302   //   const struct method_list_t * const instance_methods;
05303   //   const struct method_list_t * const class_methods;
05304   //   const struct method_list_t *optionalInstanceMethods;
05305   //   const struct method_list_t *optionalClassMethods;
05306   //   const struct _prop_list_t * properties;
05307   //   const uint32_t size;  // sizeof(struct _protocol_t)
05308   //   const uint32_t flags;  // = 0
05309   //   const char ** extendedMethodTypes;
05310   // }
05311 
05312   // Holder for struct _protocol_list_t *
05313   ProtocolListnfABITy =
05314     llvm::StructType::create(VMContext, "struct._objc_protocol_list");
05315 
05316   ProtocolnfABITy =
05317     llvm::StructType::create("struct._protocol_t", ObjectPtrTy, Int8PtrTy,
05318                              llvm::PointerType::getUnqual(ProtocolListnfABITy),
05319                              MethodListnfABIPtrTy, MethodListnfABIPtrTy,
05320                              MethodListnfABIPtrTy, MethodListnfABIPtrTy,
05321                              PropertyListPtrTy, IntTy, IntTy, Int8PtrPtrTy,
05322                              NULL);
05323 
05324   // struct _protocol_t*
05325   ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
05326 
05327   // struct _protocol_list_t {
05328   //   long protocol_count;   // Note, this is 32/64 bit
05329   //   struct _protocol_t *[protocol_count];
05330   // }
05331   ProtocolListnfABITy->setBody(LongTy,
05332                                llvm::ArrayType::get(ProtocolnfABIPtrTy, 0),
05333                                NULL);
05334 
05335   // struct _objc_protocol_list*
05336   ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
05337 
05338   // struct _ivar_t {
05339   //   unsigned [long] int *offset;  // pointer to ivar offset location
05340   //   char *name;
05341   //   char *type;
05342   //   uint32_t alignment;
05343   //   uint32_t size;
05344   // }
05345   IvarnfABITy = llvm::StructType::create(
05346       "struct._ivar_t", llvm::PointerType::getUnqual(IvarOffsetVarTy),
05347       Int8PtrTy, Int8PtrTy, IntTy, IntTy, NULL);
05348 
05349   // struct _ivar_list_t {
05350   //   uint32 entsize;  // sizeof(struct _ivar_t)
05351   //   uint32 count;
05352   //   struct _iver_t list[count];
05353   // }
05354   IvarListnfABITy =
05355     llvm::StructType::create("struct._ivar_list_t", IntTy, IntTy,
05356                              llvm::ArrayType::get(IvarnfABITy, 0), NULL);
05357 
05358   IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
05359 
05360   // struct _class_ro_t {
05361   //   uint32_t const flags;
05362   //   uint32_t const instanceStart;
05363   //   uint32_t const instanceSize;
05364   //   uint32_t const reserved;  // only when building for 64bit targets
05365   //   const uint8_t * const ivarLayout;
05366   //   const char *const name;
05367   //   const struct _method_list_t * const baseMethods;
05368   //   const struct _objc_protocol_list *const baseProtocols;
05369   //   const struct _ivar_list_t *const ivars;
05370   //   const uint8_t * const weakIvarLayout;
05371   //   const struct _prop_list_t * const properties;
05372   // }
05373 
05374   // FIXME. Add 'reserved' field in 64bit abi mode!
05375   ClassRonfABITy = llvm::StructType::create("struct._class_ro_t",
05376                                             IntTy, IntTy, IntTy, Int8PtrTy,
05377                                             Int8PtrTy, MethodListnfABIPtrTy,
05378                                             ProtocolListnfABIPtrTy,
05379                                             IvarListnfABIPtrTy,
05380                                             Int8PtrTy, PropertyListPtrTy, NULL);
05381 
05382   // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
05383   llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
05384   ImpnfABITy = llvm::FunctionType::get(ObjectPtrTy, params, false)
05385                  ->getPointerTo();
05386 
05387   // struct _class_t {
05388   //   struct _class_t *isa;
05389   //   struct _class_t * const superclass;
05390   //   void *cache;
05391   //   IMP *vtable;
05392   //   struct class_ro_t *ro;
05393   // }
05394 
05395   ClassnfABITy = llvm::StructType::create(VMContext, "struct._class_t");
05396   ClassnfABITy->setBody(llvm::PointerType::getUnqual(ClassnfABITy),
05397                         llvm::PointerType::getUnqual(ClassnfABITy),
05398                         CachePtrTy,
05399                         llvm::PointerType::getUnqual(ImpnfABITy),
05400                         llvm::PointerType::getUnqual(ClassRonfABITy),
05401                         NULL);
05402 
05403   // LLVM for struct _class_t *
05404   ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
05405 
05406   // struct _category_t {
05407   //   const char * const name;
05408   //   struct _class_t *const cls;
05409   //   const struct _method_list_t * const instance_methods;
05410   //   const struct _method_list_t * const class_methods;
05411   //   const struct _protocol_list_t * const protocols;
05412   //   const struct _prop_list_t * const properties;
05413   // }
05414   CategorynfABITy = llvm::StructType::create("struct._category_t",
05415                                              Int8PtrTy, ClassnfABIPtrTy,
05416                                              MethodListnfABIPtrTy,
05417                                              MethodListnfABIPtrTy,
05418                                              ProtocolListnfABIPtrTy,
05419                                              PropertyListPtrTy,
05420                                              NULL);
05421 
05422   // New types for nonfragile abi messaging.
05423   CodeGen::CodeGenTypes &Types = CGM.getTypes();
05424   ASTContext &Ctx = CGM.getContext();
05425 
05426   // MessageRefTy - LLVM for:
05427   // struct _message_ref_t {
05428   //   IMP messenger;
05429   //   SEL name;
05430   // };
05431 
05432   // First the clang type for struct _message_ref_t
05433   RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct,
05434                                       Ctx.getTranslationUnitDecl(),
05435                                       SourceLocation(), SourceLocation(),
05436                                       &Ctx.Idents.get("_message_ref_t"));
05437   RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
05438                                 nullptr, Ctx.VoidPtrTy, nullptr, nullptr, false,
05439                                 ICIS_NoInit));
05440   RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
05441                                 nullptr, Ctx.getObjCSelType(), nullptr, nullptr,
05442                                 false, ICIS_NoInit));
05443   RD->completeDefinition();
05444 
05445   MessageRefCTy = Ctx.getTagDeclType(RD);
05446   MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
05447   MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
05448 
05449   // MessageRefPtrTy - LLVM for struct _message_ref_t*
05450   MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
05451 
05452   // SuperMessageRefTy - LLVM for:
05453   // struct _super_message_ref_t {
05454   //   SUPER_IMP messenger;
05455   //   SEL name;
05456   // };
05457   SuperMessageRefTy =
05458     llvm::StructType::create("struct._super_message_ref_t",
05459                              ImpnfABITy, SelectorPtrTy, NULL);
05460 
05461   // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
05462   SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
05463     
05464 
05465   // struct objc_typeinfo {
05466   //   const void** vtable; // objc_ehtype_vtable + 2
05467   //   const char*  name;    // c++ typeinfo string
05468   //   Class        cls;
05469   // };
05470   EHTypeTy =
05471     llvm::StructType::create("struct._objc_typeinfo",
05472                              llvm::PointerType::getUnqual(Int8PtrTy),
05473                              Int8PtrTy, ClassnfABIPtrTy, NULL);
05474   EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
05475 }
05476 
05477 llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
05478   FinishNonFragileABIModule();
05479 
05480   return nullptr;
05481 }
05482 
05483 void CGObjCNonFragileABIMac::
05484 AddModuleClassList(ArrayRef<llvm::GlobalValue*> Container,
05485                    const char *SymbolName,
05486                    const char *SectionName) {
05487   unsigned NumClasses = Container.size();
05488 
05489   if (!NumClasses)
05490     return;
05491 
05492   SmallVector<llvm::Constant*, 8> Symbols(NumClasses);
05493   for (unsigned i=0; i<NumClasses; i++)
05494     Symbols[i] = llvm::ConstantExpr::getBitCast(Container[i],
05495                                                 ObjCTypes.Int8PtrTy);
05496   llvm::Constant *Init =
05497     llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
05498                                                   Symbols.size()),
05499                              Symbols);
05500 
05501   llvm::GlobalVariable *GV =
05502     new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
05503                              llvm::GlobalValue::PrivateLinkage,
05504                              Init,
05505                              SymbolName);
05506   assertPrivateName(GV);
05507   GV->setAlignment(CGM.getDataLayout().getABITypeAlignment(Init->getType()));
05508   GV->setSection(SectionName);
05509   CGM.addCompilerUsedGlobal(GV);
05510 }
05511 
05512 void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
05513   // nonfragile abi has no module definition.
05514 
05515   // Build list of all implemented class addresses in array
05516   // L_OBJC_LABEL_CLASS_$.
05517 
05518   for (unsigned i=0, NumClasses=ImplementedClasses.size(); i<NumClasses; i++) {
05519     const ObjCInterfaceDecl *ID = ImplementedClasses[i];
05520     assert(ID);
05521     if (ObjCImplementationDecl *IMP = ID->getImplementation())
05522       // We are implementing a weak imported interface. Give it external linkage
05523       if (ID->isWeakImported() && !IMP->isWeakImported()) {
05524         DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
05525         DefinedMetaClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
05526       }
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->getObjCRuntimeNameAsString();
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(nullptr, ObjCTypes)
05643     : BuildIvarLayout(ID, true);
05644   Values[ 4] = GetClassName(ID->getObjCRuntimeNameAsString());
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_";
05650     MethodListName += ID->getObjCRuntimeNameAsString();
05651     for (const auto *I : ID->class_methods())
05652       // Class methods should always be defined.
05653       Methods.push_back(GetMethodConstant(I));
05654   } else {
05655     MethodListName += "INSTANCE_METHODS_";
05656     MethodListName += ID->getObjCRuntimeNameAsString();
05657     for (const auto *I : ID->instance_methods())
05658       // Instance methods should always be defined.
05659       Methods.push_back(GetMethodConstant(I));
05660 
05661     for (const auto *PID : ID->property_impls()) {
05662       if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
05663         ObjCPropertyDecl *PD = PID->getPropertyDecl();
05664 
05665         if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
05666           if (llvm::Constant *C = GetMethodConstant(MD))
05667             Methods.push_back(C);
05668         if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
05669           if (llvm::Constant *C = GetMethodConstant(MD))
05670             Methods.push_back(C);
05671       }
05672     }
05673   }
05674   Values[ 5] = EmitMethodList(MethodListName,
05675                               "__DATA, __objc_const", Methods);
05676 
05677   const ObjCInterfaceDecl *OID = ID->getClassInterface();
05678   assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
05679   Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
05680                                 + OID->getObjCRuntimeNameAsString(),
05681                                 OID->all_referenced_protocol_begin(),
05682                                 OID->all_referenced_protocol_end());
05683 
05684   if (flags & NonFragileABI_Class_Meta) {
05685     Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
05686     Values[ 8] = GetIvarLayoutName(nullptr, ObjCTypes);
05687     Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
05688   } else {
05689     Values[ 7] = EmitIvarList(ID);
05690     Values[ 8] = BuildIvarLayout(ID, false);
05691     Values[ 9] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getObjCRuntimeNameAsString(),
05692                                   ID, ID->getClassInterface(), ObjCTypes);
05693   }
05694   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
05695                                                    Values);
05696   llvm::GlobalVariable *CLASS_RO_GV =
05697     new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassRonfABITy, false,
05698                              llvm::GlobalValue::PrivateLinkage,
05699                              Init,
05700                              (flags & NonFragileABI_Class_Meta) ?
05701                              std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
05702                              std::string("\01l_OBJC_CLASS_RO_$_")+ClassName);
05703   assertPrivateName(CLASS_RO_GV);
05704   CLASS_RO_GV->setAlignment(
05705     CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ClassRonfABITy));
05706   CLASS_RO_GV->setSection("__DATA, __objc_const");
05707   return CLASS_RO_GV;
05708 
05709 }
05710 
05711 /// BuildClassMetaData - This routine defines that to-level meta-data
05712 /// for the given ClassName for:
05713 /// struct _class_t {
05714 ///   struct _class_t *isa;
05715 ///   struct _class_t * const superclass;
05716 ///   void *cache;
05717 ///   IMP *vtable;
05718 ///   struct class_ro_t *ro;
05719 /// }
05720 ///
05721 llvm::GlobalVariable *CGObjCNonFragileABIMac::BuildClassMetaData(
05722     const std::string &ClassName, llvm::Constant *IsAGV, llvm::Constant *SuperClassGV,
05723     llvm::Constant *ClassRoGV, bool HiddenVisibility, bool Weak) {
05724   llvm::Constant *Values[] = {
05725     IsAGV,
05726     SuperClassGV,
05727     ObjCEmptyCacheVar,  // &ObjCEmptyCacheVar
05728     ObjCEmptyVtableVar, // &ObjCEmptyVtableVar
05729     ClassRoGV           // &CLASS_RO_GV
05730   };
05731   if (!Values[1])
05732     Values[1] = llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
05733   if (!Values[3])
05734     Values[3] = llvm::Constant::getNullValue(
05735                   llvm::PointerType::getUnqual(ObjCTypes.ImpnfABITy));
05736   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
05737                                                    Values);
05738   llvm::GlobalVariable *GV = GetClassGlobal(ClassName, Weak);
05739   GV->setInitializer(Init);
05740   GV->setSection("__DATA, __objc_data");
05741   GV->setAlignment(
05742     CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ClassnfABITy));
05743   if (HiddenVisibility)
05744     GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
05745   return GV;
05746 }
05747 
05748 bool
05749 CGObjCNonFragileABIMac::ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
05750   return OD->getClassMethod(GetNullarySelector("load")) != nullptr;
05751 }
05752 
05753 void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
05754                                               uint32_t &InstanceStart,
05755                                               uint32_t &InstanceSize) {
05756   const ASTRecordLayout &RL =
05757     CGM.getContext().getASTObjCImplementationLayout(OID);
05758 
05759   // InstanceSize is really instance end.
05760   InstanceSize = RL.getDataSize().getQuantity();
05761 
05762   // If there are no fields, the start is the same as the end.
05763   if (!RL.getFieldCount())
05764     InstanceStart = InstanceSize;
05765   else
05766     InstanceStart = RL.getFieldOffset(0) / CGM.getContext().getCharWidth();
05767 }
05768 
05769 void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
05770   std::string ClassName = ID->getObjCRuntimeNameAsString();
05771   if (!ObjCEmptyCacheVar) {
05772     ObjCEmptyCacheVar = new llvm::GlobalVariable(
05773       CGM.getModule(),
05774       ObjCTypes.CacheTy,
05775       false,
05776       llvm::GlobalValue::ExternalLinkage,
05777       nullptr,
05778       "_objc_empty_cache");
05779 
05780     // Make this entry NULL for any iOS device target, any iOS simulator target,
05781     // OS X with deployment target 10.9 or later.
05782     const llvm::Triple &Triple = CGM.getTarget().getTriple();
05783     if (Triple.isiOS() || (Triple.isMacOSX() && !Triple.isMacOSXVersionLT(10, 9)))
05784       // This entry will be null.
05785       ObjCEmptyVtableVar = nullptr;
05786     else
05787       ObjCEmptyVtableVar = new llvm::GlobalVariable(
05788                                                     CGM.getModule(),
05789                                                     ObjCTypes.ImpnfABITy,
05790                                                     false,
05791                                                     llvm::GlobalValue::ExternalLinkage,
05792                                                     nullptr,
05793                                                     "_objc_empty_vtable");
05794   }
05795   assert(ID->getClassInterface() &&
05796          "CGObjCNonFragileABIMac::GenerateClass - class is 0");
05797   // FIXME: Is this correct (that meta class size is never computed)?
05798   uint32_t InstanceStart =
05799     CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassnfABITy);
05800   uint32_t InstanceSize = InstanceStart;
05801   uint32_t flags = NonFragileABI_Class_Meta;
05802   llvm::SmallString<64> ObjCMetaClassName(getMetaclassSymbolPrefix());
05803   llvm::SmallString<64> ObjCClassName(getClassSymbolPrefix());
05804   llvm::SmallString<64> TClassName;
05805 
05806   llvm::GlobalVariable *SuperClassGV, *IsAGV;
05807 
05808   // Build the flags for the metaclass.
05809   bool classIsHidden =
05810     ID->getClassInterface()->getVisibility() == HiddenVisibility;
05811   if (classIsHidden)
05812     flags |= NonFragileABI_Class_Hidden;
05813 
05814   // FIXME: why is this flag set on the metaclass?
05815   // ObjC metaclasses have no fields and don't really get constructed.
05816   if (ID->hasNonZeroConstructors() || ID->hasDestructors()) {
05817     flags |= NonFragileABI_Class_HasCXXStructors;
05818     if (!ID->hasNonZeroConstructors())
05819       flags |= NonFragileABI_Class_HasCXXDestructorOnly;  
05820   }
05821 
05822   if (!ID->getClassInterface()->getSuperClass()) {
05823     // class is root
05824     flags |= NonFragileABI_Class_Root;
05825     TClassName = ObjCClassName;
05826     TClassName += ClassName;
05827     SuperClassGV = GetClassGlobal(TClassName.str(),
05828                                   ID->getClassInterface()->isWeakImported());
05829     TClassName = ObjCMetaClassName;
05830     TClassName += ClassName;
05831     IsAGV = GetClassGlobal(TClassName.str(),
05832                            ID->getClassInterface()->isWeakImported());
05833   } else {
05834     // Has a root. Current class is not a root.
05835     const ObjCInterfaceDecl *Root = ID->getClassInterface();
05836     while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
05837       Root = Super;
05838     TClassName = ObjCMetaClassName ;
05839     TClassName += Root->getObjCRuntimeNameAsString();
05840     IsAGV = GetClassGlobal(TClassName.str(),
05841                            Root->isWeakImported());
05842 
05843     // work on super class metadata symbol.
05844     TClassName = ObjCMetaClassName;
05845     TClassName += ID->getClassInterface()->getSuperClass()->getObjCRuntimeNameAsString();
05846     SuperClassGV = GetClassGlobal(
05847                                   TClassName.str(),
05848                                   ID->getClassInterface()->getSuperClass()->isWeakImported());
05849   }
05850   llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
05851                                                                InstanceStart,
05852                                                                InstanceSize,ID);
05853   TClassName = ObjCMetaClassName;
05854   TClassName += ClassName;
05855   llvm::GlobalVariable *MetaTClass = BuildClassMetaData(
05856       TClassName.str(), IsAGV, SuperClassGV, CLASS_RO_GV, classIsHidden,
05857       ID->getClassInterface()->isWeakImported());
05858   DefinedMetaClasses.push_back(MetaTClass);
05859 
05860   // Metadata for the class
05861   flags = 0;
05862   if (classIsHidden)
05863     flags |= NonFragileABI_Class_Hidden;
05864 
05865   if (ID->hasNonZeroConstructors() || ID->hasDestructors()) {
05866     flags |= NonFragileABI_Class_HasCXXStructors;
05867 
05868     // Set a flag to enable a runtime optimization when a class has
05869     // fields that require destruction but which don't require
05870     // anything except zero-initialization during construction.  This
05871     // is most notably true of __strong and __weak types, but you can
05872     // also imagine there being C++ types with non-trivial default
05873     // constructors that merely set all fields to null.
05874     if (!ID->hasNonZeroConstructors())
05875       flags |= NonFragileABI_Class_HasCXXDestructorOnly;
05876   }
05877 
05878   if (hasObjCExceptionAttribute(CGM.getContext(), ID->getClassInterface()))
05879     flags |= NonFragileABI_Class_Exception;
05880 
05881   if (!ID->getClassInterface()->getSuperClass()) {
05882     flags |= NonFragileABI_Class_Root;
05883     SuperClassGV = nullptr;
05884   } else {
05885     // Has a root. Current class is not a root.
05886     TClassName = ObjCClassName;
05887     TClassName += ID->getClassInterface()->getSuperClass()->getObjCRuntimeNameAsString();
05888     SuperClassGV = GetClassGlobal(
05889                                   TClassName.str(),
05890                                   ID->getClassInterface()->getSuperClass()->isWeakImported());
05891   }
05892   GetClassSizeInfo(ID, InstanceStart, InstanceSize);
05893   CLASS_RO_GV = BuildClassRoTInitializer(flags,
05894                                          InstanceStart,
05895                                          InstanceSize,
05896                                          ID);
05897 
05898   TClassName = ObjCClassName;
05899   TClassName += ClassName;
05900   llvm::GlobalVariable *ClassMD =
05901     BuildClassMetaData(TClassName.str(), MetaTClass, SuperClassGV, CLASS_RO_GV,
05902                        classIsHidden,
05903                        ID->getClassInterface()->isWeakImported());
05904   DefinedClasses.push_back(ClassMD);
05905   ImplementedClasses.push_back(ID->getClassInterface());
05906 
05907   // Determine if this class is also "non-lazy".
05908   if (ImplementationIsNonLazy(ID))
05909     DefinedNonLazyClasses.push_back(ClassMD);
05910 
05911   // Force the definition of the EHType if necessary.
05912   if (flags & NonFragileABI_Class_Exception)
05913     GetInterfaceEHType(ID->getClassInterface(), true);
05914   // Make sure method definition entries are all clear for next implementation.
05915   MethodDefinitions.clear();
05916 }
05917 
05918 /// GenerateProtocolRef - This routine is called to generate code for
05919 /// a protocol reference expression; as in:
05920 /// @code
05921 ///   @protocol(Proto1);
05922 /// @endcode
05923 /// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
05924 /// which will hold address of the protocol meta-data.
05925 ///
05926 llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CodeGenFunction &CGF,
05927                                                          const ObjCProtocolDecl *PD) {
05928 
05929   // This routine is called for @protocol only. So, we must build definition
05930   // of protocol's meta-data (not a reference to it!)
05931   //
05932   llvm::Constant *Init =
05933     llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
05934                                    ObjCTypes.getExternalProtocolPtrTy());
05935 
05936   std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
05937   ProtocolName += PD->getObjCRuntimeNameAsString();
05938 
05939   llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
05940   if (PTGV)
05941     return CGF.Builder.CreateLoad(PTGV);
05942   PTGV = new llvm::GlobalVariable(
05943     CGM.getModule(),
05944     Init->getType(), false,
05945     llvm::GlobalValue::WeakAnyLinkage,
05946     Init,
05947     ProtocolName);
05948   PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
05949   PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
05950   CGM.addCompilerUsedGlobal(PTGV);
05951   return CGF.Builder.CreateLoad(PTGV);
05952 }
05953 
05954 /// GenerateCategory - Build metadata for a category implementation.
05955 /// struct _category_t {
05956 ///   const char * const name;
05957 ///   struct _class_t *const cls;
05958 ///   const struct _method_list_t * const instance_methods;
05959 ///   const struct _method_list_t * const class_methods;
05960 ///   const struct _protocol_list_t * const protocols;
05961 ///   const struct _prop_list_t * const properties;
05962 /// }
05963 ///
05964 void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
05965   const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
05966   const char *Prefix = "\01l_OBJC_$_CATEGORY_";
05967     
05968   llvm::SmallString<64> ExtCatName(Prefix);
05969   ExtCatName += Interface->getObjCRuntimeNameAsString();
05970   ExtCatName += "_$_";
05971   ExtCatName += OCD->getNameAsString();
05972     
05973   llvm::SmallString<64> ExtClassName(getClassSymbolPrefix());
05974   ExtClassName += Interface->getObjCRuntimeNameAsString();
05975 
05976   llvm::Constant *Values[6];
05977   Values[0] = GetClassName(OCD->getIdentifier()->getName());
05978   // meta-class entry symbol
05979   llvm::GlobalVariable *ClassGV =
05980       GetClassGlobal(ExtClassName.str(), Interface->isWeakImported());
05981 
05982   Values[1] = ClassGV;
05983   std::vector<llvm::Constant*> Methods;
05984   llvm::SmallString<64> MethodListName(Prefix);
05985     
05986   MethodListName += "INSTANCE_METHODS_";
05987   MethodListName += Interface->getObjCRuntimeNameAsString();
05988   MethodListName += "_$_";
05989   MethodListName += OCD->getName();
05990 
05991   for (const auto *I : OCD->instance_methods())
05992     // Instance methods should always be defined.
05993     Methods.push_back(GetMethodConstant(I));
05994 
05995   Values[2] = EmitMethodList(MethodListName.str(),
05996                              "__DATA, __objc_const",
05997                              Methods);
05998 
05999   MethodListName = Prefix;
06000   MethodListName += "CLASS_METHODS_";
06001   MethodListName += Interface->getObjCRuntimeNameAsString();
06002   MethodListName += "_$_";
06003   MethodListName += OCD->getNameAsString();
06004     
06005   Methods.clear();
06006   for (const auto *I : OCD->class_methods())
06007     // Class methods should always be defined.
06008     Methods.push_back(GetMethodConstant(I));
06009 
06010   Values[3] = EmitMethodList(MethodListName.str(),
06011                              "__DATA, __objc_const",
06012                              Methods);
06013   const ObjCCategoryDecl *Category =
06014     Interface->FindCategoryDeclaration(OCD->getIdentifier());
06015   if (Category) {
06016     SmallString<256> ExtName;
06017     llvm::raw_svector_ostream(ExtName) << Interface->getObjCRuntimeNameAsString() << "_$_"
06018                                        << OCD->getName();
06019     Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
06020                                    + Interface->getObjCRuntimeNameAsString() + "_$_"
06021                                    + Category->getName(),
06022                                    Category->protocol_begin(),
06023                                    Category->protocol_end());
06024     Values[5] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(),
06025                                  OCD, Category, ObjCTypes);
06026   } else {
06027     Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
06028     Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
06029   }
06030 
06031   llvm::Constant *Init =
06032     llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
06033                               Values);
06034   llvm::GlobalVariable *GCATV
06035     = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.CategorynfABITy,
06036                                false,
06037                                llvm::GlobalValue::PrivateLinkage,
06038                                Init,
06039                                ExtCatName.str());
06040   assertPrivateName(GCATV);
06041   GCATV->setAlignment(
06042     CGM.getDataLayout().getABITypeAlignment(ObjCTypes.CategorynfABITy));
06043   GCATV->setSection("__DATA, __objc_const");
06044   CGM.addCompilerUsedGlobal(GCATV);
06045   DefinedCategories.push_back(GCATV);
06046 
06047   // Determine if this category is also "non-lazy".
06048   if (ImplementationIsNonLazy(OCD))
06049     DefinedNonLazyCategories.push_back(GCATV);
06050   // method definition entries must be clear for next implementation.
06051   MethodDefinitions.clear();
06052 }
06053 
06054 /// GetMethodConstant - Return a struct objc_method constant for the
06055 /// given method if it has been defined. The result is null if the
06056 /// method has not been defined. The return value has type MethodPtrTy.
06057 llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
06058   const ObjCMethodDecl *MD) {
06059   llvm::Function *Fn = GetMethodDefinition(MD);
06060   if (!Fn)
06061     return nullptr;
06062 
06063   llvm::Constant *Method[] = {
06064     llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
06065                                    ObjCTypes.SelectorPtrTy),
06066     GetMethodVarType(MD),
06067     llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy)
06068   };
06069   return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
06070 }
06071 
06072 /// EmitMethodList - Build meta-data for method declarations
06073 /// struct _method_list_t {
06074 ///   uint32_t entsize;  // sizeof(struct _objc_method)
06075 ///   uint32_t method_count;
06076 ///   struct _objc_method method_list[method_count];
06077 /// }
06078 ///
06079 llvm::Constant *
06080 CGObjCNonFragileABIMac::EmitMethodList(Twine Name,
06081                                        const char *Section,
06082                                        ArrayRef<llvm::Constant*> Methods) {
06083   // Return null for empty list.
06084   if (Methods.empty())
06085     return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
06086 
06087   llvm::Constant *Values[3];
06088   // sizeof(struct _objc_method)
06089   unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.MethodTy);
06090   Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
06091   // method_count
06092   Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
06093   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
06094                                              Methods.size());
06095   Values[2] = llvm::ConstantArray::get(AT, Methods);
06096   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
06097 
06098   llvm::GlobalVariable *GV =
06099     new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
06100                              llvm::GlobalValue::PrivateLinkage, Init, Name);
06101   assertPrivateName(GV);
06102   GV->setAlignment(CGM.getDataLayout().getABITypeAlignment(Init->getType()));
06103   GV->setSection(Section);
06104   CGM.addCompilerUsedGlobal(GV);
06105   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListnfABIPtrTy);
06106 }
06107 
06108 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
06109 /// the given ivar.
06110 llvm::GlobalVariable *
06111 CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
06112                                                const ObjCIvarDecl *Ivar) {
06113     
06114   const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();
06115   llvm::SmallString<64> Name("OBJC_IVAR_$_");
06116   Name += Container->getObjCRuntimeNameAsString();
06117   Name += ".";
06118   Name += Ivar->getName();
06119   llvm::GlobalVariable *IvarOffsetGV =
06120     CGM.getModule().getGlobalVariable(Name);
06121   if (!IvarOffsetGV)
06122     IvarOffsetGV = new llvm::GlobalVariable(
06123       CGM.getModule(), ObjCTypes.IvarOffsetVarTy, false,
06124       llvm::GlobalValue::ExternalLinkage, nullptr, Name.str());
06125   return IvarOffsetGV;
06126 }
06127 
06128 llvm::Constant *
06129 CGObjCNonFragileABIMac::EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
06130                                           const ObjCIvarDecl *Ivar,
06131                                           unsigned long int Offset) {
06132   llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
06133   IvarOffsetGV->setInitializer(
06134       llvm::ConstantInt::get(ObjCTypes.IvarOffsetVarTy, Offset));
06135   IvarOffsetGV->setAlignment(
06136       CGM.getDataLayout().getABITypeAlignment(ObjCTypes.IvarOffsetVarTy));
06137 
06138   // FIXME: This matches gcc, but shouldn't the visibility be set on the use as
06139   // well (i.e., in ObjCIvarOffsetVariable).
06140   if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
06141       Ivar->getAccessControl() == ObjCIvarDecl::Package ||
06142       ID->getVisibility() == HiddenVisibility)
06143     IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
06144   else
06145     IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
06146   IvarOffsetGV->setSection("__DATA, __objc_ivar");
06147   return IvarOffsetGV;
06148 }
06149 
06150 /// EmitIvarList - Emit the ivar list for the given
06151 /// implementation. The return value has type
06152 /// IvarListnfABIPtrTy.
06153 ///  struct _ivar_t {
06154 ///   unsigned [long] int *offset;  // pointer to ivar offset location
06155 ///   char *name;
06156 ///   char *type;
06157 ///   uint32_t alignment;
06158 ///   uint32_t size;
06159 /// }
06160 /// struct _ivar_list_t {
06161 ///   uint32 entsize;  // sizeof(struct _ivar_t)
06162 ///   uint32 count;
06163 ///   struct _iver_t list[count];
06164 /// }
06165 ///
06166 
06167 llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
06168   const ObjCImplementationDecl *ID) {
06169 
06170   std::vector<llvm::Constant*> Ivars;
06171 
06172   const ObjCInterfaceDecl *OID = ID->getClassInterface();
06173   assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
06174 
06175   // FIXME. Consolidate this with similar code in GenerateClass.
06176 
06177   for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin(); 
06178        IVD; IVD = IVD->getNextIvar()) {
06179     // Ignore unnamed bit-fields.
06180     if (!IVD->getDeclName())
06181       continue;
06182     llvm::Constant *Ivar[5];
06183     Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
06184                                 ComputeIvarBaseOffset(CGM, ID, IVD));
06185     Ivar[1] = GetMethodVarName(IVD->getIdentifier());
06186     Ivar[2] = GetMethodVarType(IVD);
06187     llvm::Type *FieldTy =
06188       CGM.getTypes().ConvertTypeForMem(IVD->getType());
06189     unsigned Size = CGM.getDataLayout().getTypeAllocSize(FieldTy);
06190     unsigned Align = CGM.getContext().getPreferredTypeAlign(
06191       IVD->getType().getTypePtr()) >> 3;
06192     Align = llvm::Log2_32(Align);
06193     Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
06194     // NOTE. Size of a bitfield does not match gcc's, because of the
06195     // way bitfields are treated special in each. But I am told that
06196     // 'size' for bitfield ivars is ignored by the runtime so it does
06197     // not matter.  If it matters, there is enough info to get the
06198     // bitfield right!
06199     Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
06200     Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
06201   }
06202   // Return null for empty list.
06203   if (Ivars.empty())
06204     return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
06205 
06206   llvm::Constant *Values[3];
06207   unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.IvarnfABITy);
06208   Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
06209   Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
06210   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
06211                                              Ivars.size());
06212   Values[2] = llvm::ConstantArray::get(AT, Ivars);
06213   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
06214   const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
06215   llvm::GlobalVariable *GV =
06216     new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
06217                              llvm::GlobalValue::PrivateLinkage,
06218                              Init,
06219                              Prefix + OID->getObjCRuntimeNameAsString());
06220   assertPrivateName(GV);
06221   GV->setAlignment(
06222     CGM.getDataLayout().getABITypeAlignment(Init->getType()));
06223   GV->setSection("__DATA, __objc_const");
06224 
06225   CGM.addCompilerUsedGlobal(GV);
06226   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListnfABIPtrTy);
06227 }
06228 
06229 llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
06230   const ObjCProtocolDecl *PD) {
06231   llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
06232 
06233   if (!Entry) {
06234     // We use the initializer as a marker of whether this is a forward
06235     // reference or not. At module finalization we add the empty
06236     // contents for protocols which were referenced but never defined.
06237     Entry =
06238         new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy,
06239                                  false, llvm::GlobalValue::WeakAnyLinkage,
06240                                  nullptr,
06241                                  "\01l_OBJC_PROTOCOL_$_" + PD->getObjCRuntimeNameAsString());
06242     Entry->setSection("__DATA,__datacoal_nt,coalesced");
06243   }
06244 
06245   return Entry;
06246 }
06247 
06248 /// GetOrEmitProtocol - Generate the protocol meta-data:
06249 /// @code
06250 /// struct _protocol_t {
06251 ///   id isa;  // NULL
06252 ///   const char * const protocol_name;
06253 ///   const struct _protocol_list_t * protocol_list; // super protocols
06254 ///   const struct method_list_t * const instance_methods;
06255 ///   const struct method_list_t * const class_methods;
06256 ///   const struct method_list_t *optionalInstanceMethods;
06257 ///   const struct method_list_t *optionalClassMethods;
06258 ///   const struct _prop_list_t * properties;
06259 ///   const uint32_t size;  // sizeof(struct _protocol_t)
06260 ///   const uint32_t flags;  // = 0
06261 ///   const char ** extendedMethodTypes;
06262 /// }
06263 /// @endcode
06264 ///
06265 
06266 llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
06267   const ObjCProtocolDecl *PD) {
06268   llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()];
06269 
06270   // Early exit if a defining object has already been generated.
06271   if (Entry && Entry->hasInitializer())
06272     return Entry;
06273 
06274   // Use the protocol definition, if there is one.
06275   if (const ObjCProtocolDecl *Def = PD->getDefinition())
06276     PD = Def;
06277   
06278   // Construct method lists.
06279   std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
06280   std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
06281   std::vector<llvm::Constant*> MethodTypesExt, OptMethodTypesExt;
06282   for (const auto *MD : PD->instance_methods()) {
06283     llvm::Constant *C = GetMethodDescriptionConstant(MD);
06284     if (!C)
06285       return GetOrEmitProtocolRef(PD);
06286     
06287     if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
06288       OptInstanceMethods.push_back(C);
06289       OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
06290     } else {
06291       InstanceMethods.push_back(C);
06292       MethodTypesExt.push_back(GetMethodVarType(MD, true));
06293     }
06294   }
06295 
06296   for (const auto *MD : PD->class_methods()) {
06297     llvm::Constant *C = GetMethodDescriptionConstant(MD);
06298     if (!C)
06299       return GetOrEmitProtocolRef(PD);
06300 
06301     if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
06302       OptClassMethods.push_back(C);
06303       OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
06304     } else {
06305       ClassMethods.push_back(C);
06306       MethodTypesExt.push_back(GetMethodVarType(MD, true));
06307     }
06308   }
06309 
06310   MethodTypesExt.insert(MethodTypesExt.end(),
06311                         OptMethodTypesExt.begin(), OptMethodTypesExt.end());
06312 
06313   llvm::Constant *Values[11];
06314   // isa is NULL
06315   Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
06316   Values[1] = GetClassName(PD->getObjCRuntimeNameAsString());
06317   Values[2] = EmitProtocolList("\01l_OBJC_$_PROTOCOL_REFS_" + PD->getObjCRuntimeNameAsString(),
06318                                PD->protocol_begin(),
06319                                PD->protocol_end());
06320 
06321   Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
06322                              + PD->getObjCRuntimeNameAsString(),
06323                              "__DATA, __objc_const",
06324                              InstanceMethods);
06325   Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
06326                              + PD->getObjCRuntimeNameAsString(),
06327                              "__DATA, __objc_const",
06328                              ClassMethods);
06329   Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
06330                              + PD->getObjCRuntimeNameAsString(),
06331                              "__DATA, __objc_const",
06332                              OptInstanceMethods);
06333   Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
06334                              + PD->getObjCRuntimeNameAsString(),
06335                              "__DATA, __objc_const",
06336                              OptClassMethods);
06337   Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getObjCRuntimeNameAsString(),
06338                                nullptr, PD, ObjCTypes);
06339   uint32_t Size =
06340     CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolnfABITy);
06341   Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
06342   Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
06343   Values[10] = EmitProtocolMethodTypes("\01l_OBJC_$_PROTOCOL_METHOD_TYPES_"
06344                                        + PD->getObjCRuntimeNameAsString(),
06345                                        MethodTypesExt, ObjCTypes);
06346   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
06347                                                    Values);
06348 
06349   if (Entry) {
06350     // Already created, update the initializer.
06351     assert(Entry->hasWeakAnyLinkage());
06352     Entry->setInitializer(Init);
06353   } else {
06354     Entry =
06355       new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy,
06356                                false, llvm::GlobalValue::WeakAnyLinkage, Init,
06357                                "\01l_OBJC_PROTOCOL_$_" + PD->getObjCRuntimeNameAsString());
06358     Entry->setAlignment(
06359       CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ProtocolnfABITy));
06360     Entry->setSection("__DATA,__datacoal_nt,coalesced");
06361 
06362     Protocols[PD->getIdentifier()] = Entry;
06363   }
06364   Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
06365   CGM.addCompilerUsedGlobal(Entry);
06366 
06367   // Use this protocol meta-data to build protocol list table in section
06368   // __DATA, __objc_protolist
06369   llvm::GlobalVariable *PTGV =
06370     new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABIPtrTy,
06371                              false, llvm::GlobalValue::WeakAnyLinkage, Entry,
06372                              "\01l_OBJC_LABEL_PROTOCOL_$_" + PD->getObjCRuntimeNameAsString());
06373   PTGV->setAlignment(
06374     CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
06375   PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
06376   PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
06377   CGM.addCompilerUsedGlobal(PTGV);
06378   return Entry;
06379 }
06380 
06381 /// EmitProtocolList - Generate protocol list meta-data:
06382 /// @code
06383 /// struct _protocol_list_t {
06384 ///   long protocol_count;   // Note, this is 32/64 bit
06385 ///   struct _protocol_t[protocol_count];
06386 /// }
06387 /// @endcode
06388 ///
06389 llvm::Constant *
06390 CGObjCNonFragileABIMac::EmitProtocolList(Twine Name,
06391                                       ObjCProtocolDecl::protocol_iterator begin,
06392                                       ObjCProtocolDecl::protocol_iterator end) {
06393   SmallVector<llvm::Constant *, 16> ProtocolRefs;
06394 
06395   // Just return null for empty protocol lists
06396   if (begin == end)
06397     return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
06398 
06399   // FIXME: We shouldn't need to do this lookup here, should we?
06400   SmallString<256> TmpName;
06401   Name.toVector(TmpName);
06402   llvm::GlobalVariable *GV =
06403     CGM.getModule().getGlobalVariable(TmpName.str(), true);
06404   if (GV)
06405     return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListnfABIPtrTy);
06406 
06407   for (; begin != end; ++begin)
06408     ProtocolRefs.push_back(GetProtocolRef(*begin));  // Implemented???
06409 
06410   // This list is null terminated.
06411   ProtocolRefs.push_back(llvm::Constant::getNullValue(
06412                            ObjCTypes.ProtocolnfABIPtrTy));
06413 
06414   llvm::Constant *Values[2];
06415   Values[0] =
06416     llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
06417   Values[1] =
06418     llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
06419                                                   ProtocolRefs.size()),
06420                              ProtocolRefs);
06421 
06422   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
06423   GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
06424                                 llvm::GlobalValue::PrivateLinkage,
06425                                 Init, Name);
06426   assertPrivateName(GV);
06427   GV->setSection("__DATA, __objc_const");
06428   GV->setAlignment(
06429     CGM.getDataLayout().getABITypeAlignment(Init->getType()));
06430   CGM.addCompilerUsedGlobal(GV);
06431   return llvm::ConstantExpr::getBitCast(GV,
06432                                         ObjCTypes.ProtocolListnfABIPtrTy);
06433 }
06434 
06435 /// GetMethodDescriptionConstant - This routine build following meta-data:
06436 /// struct _objc_method {
06437 ///   SEL _cmd;
06438 ///   char *method_type;
06439 ///   char *_imp;
06440 /// }
06441 
06442 llvm::Constant *
06443 CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
06444   llvm::Constant *Desc[3];
06445   Desc[0] =
06446     llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
06447                                    ObjCTypes.SelectorPtrTy);
06448   Desc[1] = GetMethodVarType(MD);
06449   if (!Desc[1])
06450     return nullptr;
06451 
06452   // Protocol methods have no implementation. So, this entry is always NULL.
06453   Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
06454   return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
06455 }
06456 
06457 /// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
06458 /// This code gen. amounts to generating code for:
06459 /// @code
06460 /// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
06461 /// @encode
06462 ///
06463 LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
06464                                                CodeGen::CodeGenFunction &CGF,
06465                                                QualType ObjectTy,
06466                                                llvm::Value *BaseValue,
06467                                                const ObjCIvarDecl *Ivar,
06468                                                unsigned CVRQualifiers) {
06469   ObjCInterfaceDecl *ID = ObjectTy->getAs<ObjCObjectType>()->getInterface();
06470   llvm::Value *Offset = EmitIvarOffset(CGF, ID, Ivar);
06471   return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
06472                                   Offset);
06473 }
06474 
06475 llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
06476   CodeGen::CodeGenFunction &CGF,
06477   const ObjCInterfaceDecl *Interface,
06478   const ObjCIvarDecl *Ivar) {
06479   llvm::Value *IvarOffsetValue = ObjCIvarOffsetVariable(Interface, Ivar);
06480   IvarOffsetValue = CGF.Builder.CreateLoad(IvarOffsetValue, "ivar");
06481   if (IsIvarOffsetKnownIdempotent(CGF, Ivar))
06482     cast<llvm::LoadInst>(IvarOffsetValue)
06483         ->setMetadata(CGM.getModule().getMDKindID("invariant.load"),
06484                       llvm::MDNode::get(VMContext, None));
06485 
06486   // This could be 32bit int or 64bit integer depending on the architecture.
06487   // Cast it to 64bit integer value, if it is a 32bit integer ivar offset value
06488   //  as this is what caller always expectes.
06489   if (ObjCTypes.IvarOffsetVarTy == ObjCTypes.IntTy)
06490     IvarOffsetValue = CGF.Builder.CreateIntCast(
06491         IvarOffsetValue, ObjCTypes.LongTy, true, "ivar.conv");
06492   return IvarOffsetValue;
06493 }
06494 
06495 static void appendSelectorForMessageRefTable(std::string &buffer,
06496                                              Selector selector) {
06497   if (selector.isUnarySelector()) {
06498     buffer += selector.getNameForSlot(0);
06499     return;
06500   }
06501 
06502   for (unsigned i = 0, e = selector.getNumArgs(); i != e; ++i) {
06503     buffer += selector.getNameForSlot(i);
06504     buffer += '_';
06505   }
06506 }
06507 
06508 /// Emit a "v-table" message send.  We emit a weak hidden-visibility
06509 /// struct, initially containing the selector pointer and a pointer to
06510 /// a "fixup" variant of the appropriate objc_msgSend.  To call, we
06511 /// load and call the function pointer, passing the address of the
06512 /// struct as the second parameter.  The runtime determines whether
06513 /// the selector is currently emitted using vtable dispatch; if so, it
06514 /// substitutes a stub function which simply tail-calls through the
06515 /// appropriate vtable slot, and if not, it substitues a stub function
06516 /// which tail-calls objc_msgSend.  Both stubs adjust the selector
06517 /// argument to correctly point to the selector.
06518 RValue
06519 CGObjCNonFragileABIMac::EmitVTableMessageSend(CodeGenFunction &CGF,
06520                                               ReturnValueSlot returnSlot,
06521                                               QualType resultType,
06522                                               Selector selector,
06523                                               llvm::Value *arg0,
06524                                               QualType arg0Type,
06525                                               bool isSuper,
06526                                               const CallArgList &formalArgs,
06527                                               const ObjCMethodDecl *method) {
06528   // Compute the actual arguments.
06529   CallArgList args;
06530 
06531   // First argument: the receiver / super-call structure.
06532   if (!isSuper)
06533     arg0 = CGF.Builder.CreateBitCast(arg0, ObjCTypes.ObjectPtrTy);
06534   args.add(RValue::get(arg0), arg0Type);
06535 
06536   // Second argument: a pointer to the message ref structure.  Leave
06537   // the actual argument value blank for now.
06538   args.add(RValue::get(nullptr), ObjCTypes.MessageRefCPtrTy);
06539 
06540   args.insert(args.end(), formalArgs.begin(), formalArgs.end());
06541 
06542   MessageSendInfo MSI = getMessageSendInfo(method, resultType, args);
06543 
06544   NullReturnState nullReturn;
06545 
06546   // Find the function to call and the mangled name for the message
06547   // ref structure.  Using a different mangled name wouldn't actually
06548   // be a problem; it would just be a waste.
06549   //
06550   // The runtime currently never uses vtable dispatch for anything
06551   // except normal, non-super message-sends.
06552   // FIXME: don't use this for that.
06553   llvm::Constant *fn = nullptr;
06554   std::string messageRefName("\01l_");
06555   if (CGM.ReturnSlotInterferesWithArgs(MSI.CallInfo)) {
06556     if (isSuper) {
06557       fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
06558       messageRefName += "objc_msgSendSuper2_stret_fixup";
06559     } else {
06560       nullReturn.init(CGF, arg0);
06561       fn = ObjCTypes.getMessageSendStretFixupFn();
06562       messageRefName += "objc_msgSend_stret_fixup";
06563     }
06564   } else if (!isSuper && CGM.ReturnTypeUsesFPRet(resultType)) {
06565     fn = ObjCTypes.getMessageSendFpretFixupFn();
06566     messageRefName += "objc_msgSend_fpret_fixup";
06567   } else {
06568     if (isSuper) {
06569       fn = ObjCTypes.getMessageSendSuper2FixupFn();
06570       messageRefName += "objc_msgSendSuper2_fixup";
06571     } else {
06572       fn = ObjCTypes.getMessageSendFixupFn();
06573       messageRefName += "objc_msgSend_fixup";
06574     }
06575   }
06576   assert(fn && "CGObjCNonFragileABIMac::EmitMessageSend");
06577   messageRefName += '_';
06578 
06579   // Append the selector name, except use underscores anywhere we
06580   // would have used colons.
06581   appendSelectorForMessageRefTable(messageRefName, selector);
06582 
06583   llvm::GlobalVariable *messageRef
06584     = CGM.getModule().getGlobalVariable(messageRefName);
06585   if (!messageRef) {
06586     // Build the message ref structure.
06587     llvm::Constant *values[] = { fn, GetMethodVarName(selector) };
06588     llvm::Constant *init = llvm::ConstantStruct::getAnon(values);
06589     messageRef = new llvm::GlobalVariable(CGM.getModule(),
06590                                           init->getType(),
06591                                           /*constant*/ false,
06592                                           llvm::GlobalValue::WeakAnyLinkage,
06593                                           init,
06594                                           messageRefName);
06595     messageRef->setVisibility(llvm::GlobalValue::HiddenVisibility);
06596     messageRef->setAlignment(16);
06597     messageRef->setSection("__DATA, __objc_msgrefs, coalesced");
06598   }
06599   
06600   bool requiresnullCheck = false;
06601   if (CGM.getLangOpts().ObjCAutoRefCount && method)
06602     for (const auto *ParamDecl : method->params()) {
06603       if (ParamDecl->hasAttr<NSConsumedAttr>()) {
06604         if (!nullReturn.NullBB)
06605           nullReturn.init(CGF, arg0);
06606         requiresnullCheck = true;
06607         break;
06608       }
06609     }
06610   
06611   llvm::Value *mref =
06612     CGF.Builder.CreateBitCast(messageRef, ObjCTypes.MessageRefPtrTy);
06613 
06614   // Update the message ref argument.
06615   args[1].RV = RValue::get(mref);
06616 
06617   // Load the function to call from the message ref table.
06618   llvm::Value *callee = CGF.Builder.CreateStructGEP(mref, 0);
06619   callee = CGF.Builder.CreateLoad(callee, "msgSend_fn");
06620 
06621   callee = CGF.Builder.CreateBitCast(callee, MSI.MessengerType);
06622 
06623   RValue result = CGF.EmitCall(MSI.CallInfo, callee, returnSlot, args);
06624   return nullReturn.complete(CGF, result, resultType, formalArgs,
06625                              requiresnullCheck ? method : nullptr);
06626 }
06627 
06628 /// Generate code for a message send expression in the nonfragile abi.
06629 CodeGen::RValue
06630 CGObjCNonFragileABIMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
06631                                             ReturnValueSlot Return,
06632                                             QualType ResultType,
06633                                             Selector Sel,
06634                                             llvm::Value *Receiver,
06635                                             const CallArgList &CallArgs,
06636                                             const ObjCInterfaceDecl *Class,
06637                                             const ObjCMethodDecl *Method) {
06638   return isVTableDispatchedSelector(Sel)
06639     ? EmitVTableMessageSend(CGF, Return, ResultType, Sel,
06640                             Receiver, CGF.getContext().getObjCIdType(),
06641                             false, CallArgs, Method)
06642     : EmitMessageSend(CGF, Return, ResultType,
06643                       EmitSelector(CGF, Sel),
06644                       Receiver, CGF.getContext().getObjCIdType(),
06645                       false, CallArgs, Method, ObjCTypes);
06646 }
06647 
06648 llvm::GlobalVariable *
06649 CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name, bool Weak) {
06650   llvm::GlobalValue::LinkageTypes L =
06651       Weak ? llvm::GlobalValue::ExternalWeakLinkage
06652            : llvm::GlobalValue::ExternalLinkage;
06653 
06654   llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
06655 
06656   if (!GV)
06657     GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABITy,
06658                                   false, L, nullptr, Name);
06659 
06660   assert(GV->getLinkage() == L);
06661   return GV;
06662 }
06663 
06664 llvm::Value *CGObjCNonFragileABIMac::EmitClassRefFromId(CodeGenFunction &CGF,
06665                                                         IdentifierInfo *II,
06666                                                         bool Weak,
06667                                                         const ObjCInterfaceDecl *ID) {
06668   llvm::GlobalVariable *&Entry = ClassReferences[II];
06669   
06670   if (!Entry) {
06671     std::string ClassName(
06672       getClassSymbolPrefix() +
06673       (ID ? ID->getObjCRuntimeNameAsString() : II->getName()).str());
06674     llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName, Weak);
06675     Entry =
06676     new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
06677                              false, llvm::GlobalValue::PrivateLinkage,
06678                              ClassGV,
06679                              "\01L_OBJC_CLASSLIST_REFERENCES_$_");
06680     Entry->setAlignment(
06681                         CGM.getDataLayout().getABITypeAlignment(
06682                                                                 ObjCTypes.ClassnfABIPtrTy));
06683     Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
06684     CGM.addCompilerUsedGlobal(Entry);
06685   }
06686   assertPrivateName(Entry);
06687   return CGF.Builder.CreateLoad(Entry);
06688 }
06689 
06690 llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CodeGenFunction &CGF,
06691                                                   const ObjCInterfaceDecl *ID) {
06692   return EmitClassRefFromId(CGF, ID->getIdentifier(), ID->isWeakImported(), ID);
06693 }
06694 
06695 llvm::Value *CGObjCNonFragileABIMac::EmitNSAutoreleasePoolClassRef(
06696                                                     CodeGenFunction &CGF) {
06697   IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
06698   return EmitClassRefFromId(CGF, II, false, 0);
06699 }
06700 
06701 llvm::Value *
06702 CGObjCNonFragileABIMac::EmitSuperClassRef(CodeGenFunction &CGF,
06703                                           const ObjCInterfaceDecl *ID) {
06704   llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
06705 
06706   if (!Entry) {
06707     llvm::SmallString<64> ClassName(getClassSymbolPrefix());
06708     ClassName += ID->getObjCRuntimeNameAsString();
06709     llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName.str(),
06710                                                    ID->isWeakImported());
06711     Entry =
06712       new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
06713                                false, llvm::GlobalValue::PrivateLinkage,
06714                                ClassGV,
06715                                "\01L_OBJC_CLASSLIST_SUP_REFS_$_");
06716     Entry->setAlignment(
06717       CGM.getDataLayout().getABITypeAlignment(
06718         ObjCTypes.ClassnfABIPtrTy));
06719     Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
06720     CGM.addCompilerUsedGlobal(Entry);
06721   }
06722   assertPrivateName(Entry);
06723   return CGF.Builder.CreateLoad(Entry);
06724 }
06725 
06726 /// EmitMetaClassRef - Return a Value * of the address of _class_t
06727 /// meta-data
06728 ///
06729 llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CodeGenFunction &CGF,
06730                                                       const ObjCInterfaceDecl *ID,
06731                                                       bool Weak) {
06732   llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
06733   if (!Entry) {
06734     llvm::SmallString<64> MetaClassName(getMetaclassSymbolPrefix());
06735     MetaClassName += ID->getObjCRuntimeNameAsString();
06736     llvm::GlobalVariable *MetaClassGV =
06737       GetClassGlobal(MetaClassName.str(), Weak);
06738       
06739     Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
06740                                      false, llvm::GlobalValue::PrivateLinkage,
06741                                      MetaClassGV,
06742                                      "\01L_OBJC_CLASSLIST_SUP_REFS_$_");
06743     Entry->setAlignment(
06744         CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ClassnfABIPtrTy));
06745 
06746     Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
06747     CGM.addCompilerUsedGlobal(Entry);
06748   }
06749 
06750   assertPrivateName(Entry);
06751   return CGF.Builder.CreateLoad(Entry);
06752 }
06753 
06754 /// GetClass - Return a reference to the class for the given interface
06755 /// decl.
06756 llvm::Value *CGObjCNonFragileABIMac::GetClass(CodeGenFunction &CGF,
06757                                               const ObjCInterfaceDecl *ID) {
06758   if (ID->isWeakImported()) {
06759     llvm::SmallString<64> ClassName(getClassSymbolPrefix());
06760     ClassName += ID->getObjCRuntimeNameAsString();
06761     llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName.str(), true);
06762     (void)ClassGV;
06763     assert(ClassGV->hasExternalWeakLinkage());
06764   }
06765   
06766   return EmitClassRef(CGF, ID);
06767 }
06768 
06769 /// Generates a message send where the super is the receiver.  This is
06770 /// a message send to self with special delivery semantics indicating
06771 /// which class's method should be called.
06772 CodeGen::RValue
06773 CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
06774                                                  ReturnValueSlot Return,
06775                                                  QualType ResultType,
06776                                                  Selector Sel,
06777                                                  const ObjCInterfaceDecl *Class,
06778                                                  bool isCategoryImpl,
06779                                                  llvm::Value *Receiver,
06780                                                  bool IsClassMessage,
06781                                                  const CodeGen::CallArgList &CallArgs,
06782                                                  const ObjCMethodDecl *Method) {
06783   // ...
06784   // Create and init a super structure; this is a (receiver, class)
06785   // pair we will pass to objc_msgSendSuper.
06786   llvm::Value *ObjCSuper =
06787     CGF.CreateTempAlloca(ObjCTypes.SuperTy, "objc_super");
06788 
06789   llvm::Value *ReceiverAsObject =
06790     CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
06791   CGF.Builder.CreateStore(ReceiverAsObject,
06792                           CGF.Builder.CreateStructGEP(ObjCSuper, 0));
06793 
06794   // If this is a class message the metaclass is passed as the target.
06795   llvm::Value *Target;
06796   if (IsClassMessage)
06797       Target = EmitMetaClassRef(CGF, Class, Class->isWeakImported());
06798   else
06799     Target = EmitSuperClassRef(CGF, Class);
06800 
06801   // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
06802   // ObjCTypes types.
06803   llvm::Type *ClassTy =
06804     CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
06805   Target = CGF.Builder.CreateBitCast(Target, ClassTy);
06806   CGF.Builder.CreateStore(Target,
06807                           CGF.Builder.CreateStructGEP(ObjCSuper, 1));
06808 
06809   return (isVTableDispatchedSelector(Sel))
06810     ? EmitVTableMessageSend(CGF, Return, ResultType, Sel,
06811                             ObjCSuper, ObjCTypes.SuperPtrCTy,
06812                             true, CallArgs, Method)
06813     : EmitMessageSend(CGF, Return, ResultType,
06814                       EmitSelector(CGF, Sel),
06815                       ObjCSuper, ObjCTypes.SuperPtrCTy,
06816                       true, CallArgs, Method, ObjCTypes);
06817 }
06818 
06819 llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CodeGenFunction &CGF,
06820                                                   Selector Sel, bool lval) {
06821   llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
06822 
06823   if (!Entry) {
06824     llvm::Constant *Casted =
06825       llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
06826                                      ObjCTypes.SelectorPtrTy);
06827     Entry =
06828       new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.SelectorPtrTy, false,
06829                                llvm::GlobalValue::PrivateLinkage,
06830                                Casted, "\01L_OBJC_SELECTOR_REFERENCES_");
06831     Entry->setExternallyInitialized(true);
06832     Entry->setSection("__DATA, __objc_selrefs, literal_pointers, no_dead_strip");
06833     CGM.addCompilerUsedGlobal(Entry);
06834   }
06835   assertPrivateName(Entry);
06836 
06837   if (lval)
06838     return Entry;
06839   llvm::LoadInst* LI = CGF.Builder.CreateLoad(Entry);
06840   
06841   LI->setMetadata(CGM.getModule().getMDKindID("invariant.load"), 
06842                   llvm::MDNode::get(VMContext, None));
06843   return LI;
06844 }
06845 /// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
06846 /// objc_assign_ivar (id src, id *dst, ptrdiff_t)
06847 ///
06848 void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
06849                                                 llvm::Value *src,
06850                                                 llvm::Value *dst,
06851                                                 llvm::Value *ivarOffset) {
06852   llvm::Type * SrcTy = src->getType();
06853   if (!isa<llvm::PointerType>(SrcTy)) {
06854     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
06855     assert(Size <= 8 && "does not support size > 8");
06856     src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
06857            : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
06858     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
06859   }
06860   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
06861   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
06862   llvm::Value *args[] = { src, dst, ivarOffset };
06863   CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args);
06864 }
06865 
06866 /// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
06867 /// objc_assign_strongCast (id src, id *dst)
06868 ///
06869 void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
06870   CodeGen::CodeGenFunction &CGF,
06871   llvm::Value *src, llvm::Value *dst) {
06872   llvm::Type * SrcTy = src->getType();
06873   if (!isa<llvm::PointerType>(SrcTy)) {
06874     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
06875     assert(Size <= 8 && "does not support size > 8");
06876     src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
06877            : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
06878     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
06879   }
06880   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
06881   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
06882   llvm::Value *args[] = { src, dst };
06883   CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(),
06884                               args, "weakassign");
06885 }
06886 
06887 void CGObjCNonFragileABIMac::EmitGCMemmoveCollectable(
06888   CodeGen::CodeGenFunction &CGF,
06889   llvm::Value *DestPtr,
06890   llvm::Value *SrcPtr,
06891   llvm::Value *Size) {
06892   SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
06893   DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
06894   llvm::Value *args[] = { DestPtr, SrcPtr, Size };
06895   CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args);
06896 }
06897 
06898 /// EmitObjCWeakRead - Code gen for loading value of a __weak
06899 /// object: objc_read_weak (id *src)
06900 ///
06901 llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
06902   CodeGen::CodeGenFunction &CGF,
06903   llvm::Value *AddrWeakObj) {
06904   llvm::Type* DestTy =
06905     cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
06906   AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
06907   llvm::Value *read_weak =
06908     CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(),
06909                                 AddrWeakObj, "weakread");
06910   read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
06911   return read_weak;
06912 }
06913 
06914 /// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
06915 /// objc_assign_weak (id src, id *dst)
06916 ///
06917 void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
06918                                                 llvm::Value *src, llvm::Value *dst) {
06919   llvm::Type * SrcTy = src->getType();
06920   if (!isa<llvm::PointerType>(SrcTy)) {
06921     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
06922     assert(Size <= 8 && "does not support size > 8");
06923     src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
06924            : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
06925     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
06926   }
06927   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
06928   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
06929   llvm::Value *args[] = { src, dst };
06930   CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(),
06931                               args, "weakassign");
06932 }
06933 
06934 /// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
06935 /// objc_assign_global (id src, id *dst)
06936 ///
06937 void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
06938                                           llvm::Value *src, llvm::Value *dst,
06939                                           bool threadlocal) {
06940   llvm::Type * SrcTy = src->getType();
06941   if (!isa<llvm::PointerType>(SrcTy)) {
06942     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
06943     assert(Size <= 8 && "does not support size > 8");
06944     src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
06945            : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
06946     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
06947   }
06948   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
06949   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
06950   llvm::Value *args[] = { src, dst };
06951   if (!threadlocal)
06952     CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(),
06953                                 args, "globalassign");
06954   else
06955     CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(),
06956                                 args, "threadlocalassign");
06957 }
06958 
06959 void
06960 CGObjCNonFragileABIMac::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
06961                                              const ObjCAtSynchronizedStmt &S) {
06962   EmitAtSynchronizedStmt(CGF, S,
06963       cast<llvm::Function>(ObjCTypes.getSyncEnterFn()),
06964       cast<llvm::Function>(ObjCTypes.getSyncExitFn()));
06965 }
06966 
06967 llvm::Constant *
06968 CGObjCNonFragileABIMac::GetEHType(QualType T) {
06969   // There's a particular fixed type info for 'id'.
06970   if (T->isObjCIdType() ||
06971       T->isObjCQualifiedIdType()) {
06972     llvm::Constant *IDEHType =
06973       CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
06974     if (!IDEHType)
06975       IDEHType =
06976         new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy,
06977                                  false,
06978                                  llvm::GlobalValue::ExternalLinkage,
06979                                  nullptr, "OBJC_EHTYPE_id");
06980     return IDEHType;
06981   }
06982 
06983   // All other types should be Objective-C interface pointer types.
06984   const ObjCObjectPointerType *PT =
06985     T->getAs<ObjCObjectPointerType>();
06986   assert(PT && "Invalid @catch type.");
06987   const ObjCInterfaceType *IT = PT->getInterfaceType();
06988   assert(IT && "Invalid @catch type.");
06989   return GetInterfaceEHType(IT->getDecl(), false);
06990 }                                                  
06991 
06992 void CGObjCNonFragileABIMac::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
06993                                          const ObjCAtTryStmt &S) {
06994   EmitTryCatchStmt(CGF, S,
06995       cast<llvm::Function>(ObjCTypes.getObjCBeginCatchFn()),
06996       cast<llvm::Function>(ObjCTypes.getObjCEndCatchFn()),
06997       cast<llvm::Function>(ObjCTypes.getExceptionRethrowFn()));
06998 }
06999 
07000 /// EmitThrowStmt - Generate code for a throw statement.
07001 void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
07002                                            const ObjCAtThrowStmt &S,
07003                                            bool ClearInsertionPoint) {
07004   if (const Expr *ThrowExpr = S.getThrowExpr()) {
07005     llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
07006     Exception = CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
07007     CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionThrowFn(), Exception)
07008       .setDoesNotReturn();
07009   } else {
07010     CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionRethrowFn())
07011       .setDoesNotReturn();
07012   }
07013 
07014   CGF.Builder.CreateUnreachable();
07015   if (ClearInsertionPoint)
07016     CGF.Builder.ClearInsertionPoint();
07017 }
07018 
07019 llvm::Constant *
07020 CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
07021                                            bool ForDefinition) {
07022   llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
07023 
07024   // If we don't need a definition, return the entry if found or check
07025   // if we use an external reference.
07026   if (!ForDefinition) {
07027     if (Entry)
07028       return Entry;
07029 
07030     // If this type (or a super class) has the __objc_exception__
07031     // attribute, emit an external reference.
07032     if (hasObjCExceptionAttribute(CGM.getContext(), ID))
07033       return Entry =
07034           new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false,
07035                                    llvm::GlobalValue::ExternalLinkage,
07036                                    nullptr,
07037                                    ("OBJC_EHTYPE_$_" +
07038                                     ID->getObjCRuntimeNameAsString()));
07039   }
07040 
07041   // Otherwise we need to either make a new entry or fill in the
07042   // initializer.
07043   assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
07044   llvm::SmallString<64> ClassName(getClassSymbolPrefix());
07045   ClassName += ID->getObjCRuntimeNameAsString();
07046   std::string VTableName = "objc_ehtype_vtable";
07047   llvm::GlobalVariable *VTableGV =
07048     CGM.getModule().getGlobalVariable(VTableName);
07049   if (!VTableGV)
07050     VTableGV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.Int8PtrTy,
07051                                         false,
07052                                         llvm::GlobalValue::ExternalLinkage,
07053                                         nullptr, VTableName);
07054 
07055   llvm::Value *VTableIdx = llvm::ConstantInt::get(CGM.Int32Ty, 2);
07056 
07057   llvm::Constant *Values[] = {
07058     llvm::ConstantExpr::getGetElementPtr(VTableGV, VTableIdx),
07059     GetClassName(ID->getObjCRuntimeNameAsString()),
07060     GetClassGlobal(ClassName.str())
07061   };
07062   llvm::Constant *Init =
07063     llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
07064 
07065   llvm::GlobalValue::LinkageTypes L = ForDefinition
07066                                           ? llvm::GlobalValue::ExternalLinkage
07067                                           : llvm::GlobalValue::WeakAnyLinkage;
07068   if (Entry) {
07069     Entry->setInitializer(Init);
07070   } else {
07071     llvm::SmallString<64> EHTYPEName("OBJC_EHTYPE_$_");
07072     EHTYPEName += ID->getObjCRuntimeNameAsString();
07073     Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false,
07074                                      L,
07075                                      Init,
07076                                      EHTYPEName.str());
07077   }
07078   assert(Entry->getLinkage() == L);
07079 
07080   if (ID->getVisibility() == HiddenVisibility)
07081     Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
07082   Entry->setAlignment(CGM.getDataLayout().getABITypeAlignment(
07083       ObjCTypes.EHTypeTy));
07084 
07085   if (ForDefinition)
07086     Entry->setSection("__DATA,__objc_const");
07087   else
07088     Entry->setSection("__DATA,__datacoal_nt,coalesced");
07089 
07090   return Entry;
07091 }
07092 
07093 /* *** */
07094 
07095 CodeGen::CGObjCRuntime *
07096 CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
07097   switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
07098   case ObjCRuntime::FragileMacOSX:
07099   return new CGObjCMac(CGM);
07100 
07101   case ObjCRuntime::MacOSX:
07102   case ObjCRuntime::iOS:
07103     return new CGObjCNonFragileABIMac(CGM);
07104 
07105   case ObjCRuntime::GNUstep:
07106   case ObjCRuntime::GCC:
07107   case ObjCRuntime::ObjFW:
07108     llvm_unreachable("these runtimes are not Mac runtimes");
07109   }
07110   llvm_unreachable("bad runtime");
07111 }