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