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