clang API Documentation

CGObjCMac.cpp
Go to the documentation of this file.
00001 //===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This provides Objective-C code generation targeting the Apple runtime.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "CGObjCRuntime.h"
00015 #include "CGBlocks.h"
00016 #include "CGCleanup.h"
00017 #include "CGRecordLayout.h"
00018 #include "CodeGenFunction.h"
00019 #include "CodeGenModule.h"
00020 #include "clang/AST/ASTContext.h"
00021 #include "clang/AST/Decl.h"
00022 #include "clang/AST/DeclObjC.h"
00023 #include "clang/AST/RecordLayout.h"
00024 #include "clang/AST/StmtObjC.h"
00025 #include "clang/Basic/LangOptions.h"
00026 #include "clang/CodeGen/CGFunctionInfo.h"
00027 #include "clang/Frontend/CodeGenOptions.h"
00028 #include "llvm/ADT/DenseSet.h"
00029 #include "llvm/ADT/SetVector.h"
00030 #include "llvm/ADT/SmallPtrSet.h"
00031 #include "llvm/ADT/SmallString.h"
00032 #include "llvm/IR/CallSite.h"
00033 #include "llvm/IR/DataLayout.h"
00034 #include "llvm/IR/InlineAsm.h"
00035 #include "llvm/IR/IntrinsicInst.h"
00036 #include "llvm/IR/LLVMContext.h"
00037 #include "llvm/IR/Module.h"
00038 #include "llvm/Support/raw_ostream.h"
00039 #include <cstdio>
00040 
00041 using namespace clang;
00042 using namespace CodeGen;
00043 
00044 namespace {
00045 
00046 // FIXME: We should find a nicer way to make the labels for metadata, string
00047 // concatenation is lame.
00048 
00049 class ObjCCommonTypesHelper {
00050 protected:
00051   llvm::LLVMContext &VMContext;
00052 
00053 private:
00054   // The types of these functions don't really matter because we
00055   // should always bitcast before calling them.
00056 
00057   /// id objc_msgSend (id, SEL, ...)
00058   /// 
00059   /// The default messenger, used for sends whose ABI is unchanged from
00060   /// the all-integer/pointer case.
00061   llvm::Constant *getMessageSendFn() const {
00062     // Add the non-lazy-bind attribute, since objc_msgSend is likely to
00063     // be called a lot.
00064     llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
00065     return
00066       CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
00067                                                         params, true),
00068                                 "objc_msgSend",
00069                                 llvm::AttributeSet::get(CGM.getLLVMContext(),
00070                                               llvm::AttributeSet::FunctionIndex,
00071                                                  llvm::Attribute::NonLazyBind));
00072   }
00073 
00074   /// void objc_msgSend_stret (id, SEL, ...)
00075   ///
00076   /// The messenger used when the return value is an aggregate returned
00077   /// by indirect reference in the first argument, and therefore the
00078   /// self and selector parameters are shifted over by one.
00079   llvm::Constant *getMessageSendStretFn() const {
00080     llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
00081     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.VoidTy,
00082                                                              params, true),
00083                                      "objc_msgSend_stret");
00084 
00085   }
00086 
00087   /// [double | long double] objc_msgSend_fpret(id self, SEL op, ...)
00088   ///
00089   /// The messenger used when the return value is returned on the x87
00090   /// floating-point stack; without a special entrypoint, the nil case
00091   /// would be unbalanced.
00092   llvm::Constant *getMessageSendFpretFn() const {
00093     llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
00094     return CGM.CreateRuntimeFunction(llvm::FunctionType::get(CGM.DoubleTy,
00095                                                              params, true),
00096                                      "objc_msgSend_fpret");
00097 
00098   }
00099 
00100   /// _Complex long double objc_msgSend_fp2ret(id self, SEL op, ...)
00101   ///
00102   /// The messenger used when the return value is returned in two values on the
00103   /// x87 floating point stack; without a special entrypoint, the nil case
00104   /// would be unbalanced. Only used on 64-bit X86.
00105   llvm::Constant *getMessageSendFp2retFn() const {
00106     llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
00107     llvm::Type *longDoubleType = llvm::Type::getX86_FP80Ty(VMContext);
00108     llvm::Type *resultType = 
00109       llvm::StructType::get(longDoubleType, longDoubleType, 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(), ExceptionData);
03814 
03815   //  - Call setjmp on the exception data buffer.
03816   llvm::Constant *Zero = llvm::ConstantInt::get(CGF.Builder.getInt32Ty(), 0);
03817   llvm::Value *GEPIndexes[] = { Zero, Zero, Zero };
03818   llvm::Value *SetJmpBuffer =
03819     CGF.Builder.CreateGEP(ExceptionData, GEPIndexes, "setjmp_buffer");
03820   llvm::CallInst *SetJmpResult =
03821     CGF.EmitNounwindRuntimeCall(ObjCTypes.getSetJmpFn(), SetJmpBuffer, "setjmp_result");
03822   SetJmpResult->setCanReturnTwice();
03823 
03824   // If setjmp returned 0, enter the protected block; otherwise,
03825   // branch to the handler.
03826   llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
03827   llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
03828   llvm::Value *DidCatch =
03829     CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
03830   CGF.Builder.CreateCondBr(DidCatch, TryHandler, TryBlock);
03831 
03832   // Emit the protected block.
03833   CGF.EmitBlock(TryBlock);
03834   CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
03835   CGF.EmitStmt(isTry ? cast<ObjCAtTryStmt>(S).getTryBody()
03836                      : cast<ObjCAtSynchronizedStmt>(S).getSynchBody());
03837 
03838   CGBuilderTy::InsertPoint TryFallthroughIP = CGF.Builder.saveAndClearIP();
03839 
03840   // Emit the exception handler block.
03841   CGF.EmitBlock(TryHandler);
03842 
03843   // Don't optimize loads of the in-scope locals across this point.
03844   Hazards.emitWriteHazard();
03845 
03846   // For a @synchronized (or a @try with no catches), just branch
03847   // through the cleanup to the rethrow block.
03848   if (!isTry || !cast<ObjCAtTryStmt>(S).getNumCatchStmts()) {
03849     // Tell the cleanup not to re-pop the exit.
03850     CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
03851     CGF.EmitBranchThroughCleanup(FinallyRethrow);
03852 
03853   // Otherwise, we have to match against the caught exceptions.
03854   } else {
03855     // Retrieve the exception object.  We may emit multiple blocks but
03856     // nothing can cross this so the value is already in SSA form.
03857     llvm::CallInst *Caught =
03858       CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
03859                                   ExceptionData, "caught");
03860 
03861     // Push the exception to rethrow onto the EH value stack for the
03862     // benefit of any @throws in the handlers.
03863     CGF.ObjCEHValueStack.push_back(Caught);
03864 
03865     const ObjCAtTryStmt* AtTryStmt = cast<ObjCAtTryStmt>(&S);
03866 
03867     bool HasFinally = (AtTryStmt->getFinallyStmt() != nullptr);
03868 
03869     llvm::BasicBlock *CatchBlock = nullptr;
03870     llvm::BasicBlock *CatchHandler = nullptr;
03871     if (HasFinally) {
03872       // Save the currently-propagating exception before
03873       // objc_exception_try_enter clears the exception slot.
03874       PropagatingExnVar = CGF.CreateTempAlloca(Caught->getType(),
03875                                                "propagating_exception");
03876       CGF.Builder.CreateStore(Caught, PropagatingExnVar);
03877 
03878       // Enter a new exception try block (in case a @catch block
03879       // throws an exception).
03880       CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionTryEnterFn(),
03881                                   ExceptionData);
03882 
03883       llvm::CallInst *SetJmpResult =
03884         CGF.EmitNounwindRuntimeCall(ObjCTypes.getSetJmpFn(),
03885                                     SetJmpBuffer, "setjmp.result");
03886       SetJmpResult->setCanReturnTwice();
03887 
03888       llvm::Value *Threw =
03889         CGF.Builder.CreateIsNotNull(SetJmpResult, "did_catch_exception");
03890 
03891       CatchBlock = CGF.createBasicBlock("catch");
03892       CatchHandler = CGF.createBasicBlock("catch_for_catch");
03893       CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
03894 
03895       CGF.EmitBlock(CatchBlock);
03896     }
03897 
03898     CGF.Builder.CreateStore(CGF.Builder.getInt1(HasFinally), CallTryExitVar);
03899 
03900     // Handle catch list. As a special case we check if everything is
03901     // matched and avoid generating code for falling off the end if
03902     // so.
03903     bool AllMatched = false;
03904     for (unsigned I = 0, N = AtTryStmt->getNumCatchStmts(); I != N; ++I) {
03905       const ObjCAtCatchStmt *CatchStmt = AtTryStmt->getCatchStmt(I);
03906 
03907       const VarDecl *CatchParam = CatchStmt->getCatchParamDecl();
03908       const ObjCObjectPointerType *OPT = nullptr;
03909 
03910       // catch(...) always matches.
03911       if (!CatchParam) {
03912         AllMatched = true;
03913       } else {
03914         OPT = CatchParam->getType()->getAs<ObjCObjectPointerType>();
03915 
03916         // catch(id e) always matches under this ABI, since only
03917         // ObjC exceptions end up here in the first place.
03918         // FIXME: For the time being we also match id<X>; this should
03919         // be rejected by Sema instead.
03920         if (OPT && (OPT->isObjCIdType() || OPT->isObjCQualifiedIdType()))
03921           AllMatched = true;
03922       }
03923 
03924       // If this is a catch-all, we don't need to test anything.
03925       if (AllMatched) {
03926         CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
03927 
03928         if (CatchParam) {
03929           CGF.EmitAutoVarDecl(*CatchParam);
03930           assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
03931 
03932           // These types work out because ConvertType(id) == i8*.
03933           CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(CatchParam));
03934         }
03935 
03936         CGF.EmitStmt(CatchStmt->getCatchBody());
03937 
03938         // The scope of the catch variable ends right here.
03939         CatchVarCleanups.ForceCleanup();
03940 
03941         CGF.EmitBranchThroughCleanup(FinallyEnd);
03942         break;
03943       }
03944 
03945       assert(OPT && "Unexpected non-object pointer type in @catch");
03946       const ObjCObjectType *ObjTy = OPT->getObjectType();
03947 
03948       // FIXME: @catch (Class c) ?
03949       ObjCInterfaceDecl *IDecl = ObjTy->getInterface();
03950       assert(IDecl && "Catch parameter must have Objective-C type!");
03951 
03952       // Check if the @catch block matches the exception object.
03953       llvm::Value *Class = EmitClassRef(CGF, IDecl);
03954 
03955       llvm::Value *matchArgs[] = { Class, Caught };
03956       llvm::CallInst *Match =
03957         CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionMatchFn(),
03958                                     matchArgs, "match");
03959 
03960       llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("match");
03961       llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch.next");
03962 
03963       CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
03964                                MatchedBlock, NextCatchBlock);
03965 
03966       // Emit the @catch block.
03967       CGF.EmitBlock(MatchedBlock);
03968 
03969       // Collect any cleanups for the catch variable.  The scope lasts until
03970       // the end of the catch body.
03971       CodeGenFunction::RunCleanupsScope CatchVarCleanups(CGF);
03972 
03973       CGF.EmitAutoVarDecl(*CatchParam);
03974       assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
03975 
03976       // Initialize the catch variable.
03977       llvm::Value *Tmp =
03978         CGF.Builder.CreateBitCast(Caught,
03979                                   CGF.ConvertType(CatchParam->getType()));
03980       CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(CatchParam));
03981 
03982       CGF.EmitStmt(CatchStmt->getCatchBody());
03983 
03984       // We're done with the catch variable.
03985       CatchVarCleanups.ForceCleanup();
03986 
03987       CGF.EmitBranchThroughCleanup(FinallyEnd);
03988 
03989       CGF.EmitBlock(NextCatchBlock);
03990     }
03991 
03992     CGF.ObjCEHValueStack.pop_back();
03993 
03994     // If nothing wanted anything to do with the caught exception,
03995     // kill the extract call.
03996     if (Caught->use_empty())
03997       Caught->eraseFromParent();
03998 
03999     if (!AllMatched)
04000       CGF.EmitBranchThroughCleanup(FinallyRethrow);
04001 
04002     if (HasFinally) {
04003       // Emit the exception handler for the @catch blocks.
04004       CGF.EmitBlock(CatchHandler);
04005 
04006       // In theory we might now need a write hazard, but actually it's
04007       // unnecessary because there's no local-accessing code between
04008       // the try's write hazard and here.
04009       //Hazards.emitWriteHazard();
04010 
04011       // Extract the new exception and save it to the
04012       // propagating-exception slot.
04013       assert(PropagatingExnVar);
04014       llvm::CallInst *NewCaught =
04015         CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
04016                                     ExceptionData, "caught");
04017       CGF.Builder.CreateStore(NewCaught, PropagatingExnVar);
04018 
04019       // Don't pop the catch handler; the throw already did.
04020       CGF.Builder.CreateStore(CGF.Builder.getFalse(), CallTryExitVar);
04021       CGF.EmitBranchThroughCleanup(FinallyRethrow);
04022     }
04023   }
04024 
04025   // Insert read hazards as required in the new blocks.
04026   Hazards.emitHazardsInNewBlocks();
04027 
04028   // Pop the cleanup.
04029   CGF.Builder.restoreIP(TryFallthroughIP);
04030   if (CGF.HaveInsertPoint())
04031     CGF.Builder.CreateStore(CGF.Builder.getTrue(), CallTryExitVar);
04032   CGF.PopCleanupBlock();
04033   CGF.EmitBlock(FinallyEnd.getBlock(), true);
04034 
04035   // Emit the rethrow block.
04036   CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();
04037   CGF.EmitBlock(FinallyRethrow.getBlock(), true);
04038   if (CGF.HaveInsertPoint()) {
04039     // If we have a propagating-exception variable, check it.
04040     llvm::Value *PropagatingExn;
04041     if (PropagatingExnVar) {
04042       PropagatingExn = CGF.Builder.CreateLoad(PropagatingExnVar);
04043 
04044     // Otherwise, just look in the buffer for the exception to throw.
04045     } else {
04046       llvm::CallInst *Caught =
04047         CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionExtractFn(),
04048                                     ExceptionData);
04049       PropagatingExn = Caught;
04050     }
04051 
04052     CGF.EmitNounwindRuntimeCall(ObjCTypes.getExceptionThrowFn(),
04053                                 PropagatingExn);
04054     CGF.Builder.CreateUnreachable();
04055   }
04056 
04057   CGF.Builder.restoreIP(SavedIP);
04058 }
04059 
04060 void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
04061                               const ObjCAtThrowStmt &S,
04062                               bool ClearInsertionPoint) {
04063   llvm::Value *ExceptionAsObject;
04064 
04065   if (const Expr *ThrowExpr = S.getThrowExpr()) {
04066     llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
04067     ExceptionAsObject =
04068       CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
04069   } else {
04070     assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
04071            "Unexpected rethrow outside @catch block.");
04072     ExceptionAsObject = CGF.ObjCEHValueStack.back();
04073   }
04074 
04075   CGF.EmitRuntimeCall(ObjCTypes.getExceptionThrowFn(), ExceptionAsObject)
04076     ->setDoesNotReturn();
04077   CGF.Builder.CreateUnreachable();
04078 
04079   // Clear the insertion point to indicate we are in unreachable code.
04080   if (ClearInsertionPoint)
04081     CGF.Builder.ClearInsertionPoint();
04082 }
04083 
04084 /// EmitObjCWeakRead - Code gen for loading value of a __weak
04085 /// object: objc_read_weak (id *src)
04086 ///
04087 llvm::Value * CGObjCMac::EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
04088                                           llvm::Value *AddrWeakObj) {
04089   llvm::Type* DestTy =
04090     cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
04091   AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj,
04092                                           ObjCTypes.PtrObjectPtrTy);
04093   llvm::Value *read_weak =
04094     CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(),
04095                                 AddrWeakObj, "weakread");
04096   read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
04097   return read_weak;
04098 }
04099 
04100 /// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
04101 /// objc_assign_weak (id src, id *dst)
04102 ///
04103 void CGObjCMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
04104                                    llvm::Value *src, llvm::Value *dst) {
04105   llvm::Type * SrcTy = src->getType();
04106   if (!isa<llvm::PointerType>(SrcTy)) {
04107     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
04108     assert(Size <= 8 && "does not support size > 8");
04109     src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
04110       : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
04111     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
04112   }
04113   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
04114   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
04115   llvm::Value *args[] = { src, dst };
04116   CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(),
04117                               args, "weakassign");
04118   return;
04119 }
04120 
04121 /// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
04122 /// objc_assign_global (id src, id *dst)
04123 ///
04124 void CGObjCMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
04125                                      llvm::Value *src, llvm::Value *dst,
04126                                      bool threadlocal) {
04127   llvm::Type * SrcTy = src->getType();
04128   if (!isa<llvm::PointerType>(SrcTy)) {
04129     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
04130     assert(Size <= 8 && "does not support size > 8");
04131     src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
04132       : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
04133     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
04134   }
04135   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
04136   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
04137   llvm::Value *args[] = { src, dst };
04138   if (!threadlocal)
04139     CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(),
04140                                 args, "globalassign");
04141   else
04142     CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(),
04143                                 args, "threadlocalassign");
04144   return;
04145 }
04146 
04147 /// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
04148 /// objc_assign_ivar (id src, id *dst, ptrdiff_t ivaroffset)
04149 ///
04150 void CGObjCMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
04151                                    llvm::Value *src, llvm::Value *dst,
04152                                    llvm::Value *ivarOffset) {
04153   assert(ivarOffset && "EmitObjCIvarAssign - ivarOffset is NULL");
04154   llvm::Type * SrcTy = src->getType();
04155   if (!isa<llvm::PointerType>(SrcTy)) {
04156     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
04157     assert(Size <= 8 && "does not support size > 8");
04158     src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
04159       : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
04160     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
04161   }
04162   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
04163   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
04164   llvm::Value *args[] = { src, dst, ivarOffset };
04165   CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args);
04166   return;
04167 }
04168 
04169 /// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
04170 /// objc_assign_strongCast (id src, id *dst)
04171 ///
04172 void CGObjCMac::EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
04173                                          llvm::Value *src, llvm::Value *dst) {
04174   llvm::Type * SrcTy = src->getType();
04175   if (!isa<llvm::PointerType>(SrcTy)) {
04176     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
04177     assert(Size <= 8 && "does not support size > 8");
04178     src = (Size == 4) ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
04179       : CGF.Builder.CreateBitCast(src, ObjCTypes.LongLongTy);
04180     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
04181   }
04182   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
04183   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
04184   llvm::Value *args[] = { src, dst };
04185   CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(),
04186                               args, "weakassign");
04187   return;
04188 }
04189 
04190 void CGObjCMac::EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
04191                                          llvm::Value *DestPtr,
04192                                          llvm::Value *SrcPtr,
04193                                          llvm::Value *size) {
04194   SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
04195   DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
04196   llvm::Value *args[] = { DestPtr, SrcPtr, size };
04197   CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args);
04198 }
04199 
04200 /// EmitObjCValueForIvar - Code Gen for ivar reference.
04201 ///
04202 LValue CGObjCMac::EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
04203                                        QualType ObjectTy,
04204                                        llvm::Value *BaseValue,
04205                                        const ObjCIvarDecl *Ivar,
04206                                        unsigned CVRQualifiers) {
04207   const ObjCInterfaceDecl *ID =
04208     ObjectTy->getAs<ObjCObjectType>()->getInterface();
04209   return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
04210                                   EmitIvarOffset(CGF, ID, Ivar));
04211 }
04212 
04213 llvm::Value *CGObjCMac::EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
04214                                        const ObjCInterfaceDecl *Interface,
04215                                        const ObjCIvarDecl *Ivar) {
04216   uint64_t Offset = ComputeIvarBaseOffset(CGM, Interface, Ivar);
04217   return llvm::ConstantInt::get(
04218     CGM.getTypes().ConvertType(CGM.getContext().LongTy),
04219     Offset);
04220 }
04221 
04222 /* *** Private Interface *** */
04223 
04224 /// EmitImageInfo - Emit the image info marker used to encode some module
04225 /// level information.
04226 ///
04227 /// See: <rdr://4810609&4810587&4810587>
04228 /// struct IMAGE_INFO {
04229 ///   unsigned version;
04230 ///   unsigned flags;
04231 /// };
04232 enum ImageInfoFlags {
04233   eImageInfo_FixAndContinue      = (1 << 0), // This flag is no longer set by clang.
04234   eImageInfo_GarbageCollected    = (1 << 1),
04235   eImageInfo_GCOnly              = (1 << 2),
04236   eImageInfo_OptimizedByDyld     = (1 << 3), // This flag is set by the dyld shared cache.
04237 
04238   // A flag indicating that the module has no instances of a @synthesize of a
04239   // superclass variable. <rdar://problem/6803242>
04240   eImageInfo_CorrectedSynthesize = (1 << 4), // This flag is no longer set by clang.
04241   eImageInfo_ImageIsSimulated    = (1 << 5)
04242 };
04243 
04244 void CGObjCCommonMac::EmitImageInfo() {
04245   unsigned version = 0; // Version is unused?
04246   const char *Section = (ObjCABI == 1) ?
04247     "__OBJC, __image_info,regular" :
04248     "__DATA, __objc_imageinfo, regular, no_dead_strip";
04249 
04250   // Generate module-level named metadata to convey this information to the
04251   // linker and code-gen.
04252   llvm::Module &Mod = CGM.getModule();
04253 
04254   // Add the ObjC ABI version to the module flags.
04255   Mod.addModuleFlag(llvm::Module::Error, "Objective-C Version", ObjCABI);
04256   Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Version",
04257                     version);
04258   Mod.addModuleFlag(llvm::Module::Error, "Objective-C Image Info Section",
04259                     llvm::MDString::get(VMContext,Section));
04260 
04261   if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
04262     // Non-GC overrides those files which specify GC.
04263     Mod.addModuleFlag(llvm::Module::Override,
04264                       "Objective-C Garbage Collection", (uint32_t)0);
04265   } else {
04266     // Add the ObjC garbage collection value.
04267     Mod.addModuleFlag(llvm::Module::Error,
04268                       "Objective-C Garbage Collection",
04269                       eImageInfo_GarbageCollected);
04270 
04271     if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
04272       // Add the ObjC GC Only value.
04273       Mod.addModuleFlag(llvm::Module::Error, "Objective-C GC Only",
04274                         eImageInfo_GCOnly);
04275 
04276       // Require that GC be specified and set to eImageInfo_GarbageCollected.
04277       llvm::Metadata *Ops[2] = {
04278           llvm::MDString::get(VMContext, "Objective-C Garbage Collection"),
04279           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
04280               llvm::Type::getInt32Ty(VMContext), eImageInfo_GarbageCollected))};
04281       Mod.addModuleFlag(llvm::Module::Require, "Objective-C GC Only",
04282                         llvm::MDNode::get(VMContext, Ops));
04283     }
04284   }
04285 
04286   // Indicate whether we're compiling this to run on a simulator.
04287   const llvm::Triple &Triple = CGM.getTarget().getTriple();
04288   if (Triple.isiOS() &&
04289       (Triple.getArch() == llvm::Triple::x86 ||
04290        Triple.getArch() == llvm::Triple::x86_64))
04291     Mod.addModuleFlag(llvm::Module::Error, "Objective-C Is Simulated",
04292                       eImageInfo_ImageIsSimulated);
04293 }
04294 
04295 // struct objc_module {
04296 //   unsigned long version;
04297 //   unsigned long size;
04298 //   const char *name;
04299 //   Symtab symtab;
04300 // };
04301 
04302 // FIXME: Get from somewhere
04303 static const int ModuleVersion = 7;
04304 
04305 void CGObjCMac::EmitModuleInfo() {
04306   uint64_t Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ModuleTy);
04307 
04308   llvm::Constant *Values[] = {
04309     llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion),
04310     llvm::ConstantInt::get(ObjCTypes.LongTy, Size),
04311     // This used to be the filename, now it is unused. <rdr://4327263>
04312     GetClassName(StringRef("")),
04313     EmitModuleSymbols()
04314   };
04315   CreateMetadataVar("OBJC_MODULES",
04316                     llvm::ConstantStruct::get(ObjCTypes.ModuleTy, Values),
04317                     "__OBJC,__module_info,regular,no_dead_strip", 4, true);
04318 }
04319 
04320 llvm::Constant *CGObjCMac::EmitModuleSymbols() {
04321   unsigned NumClasses = DefinedClasses.size();
04322   unsigned NumCategories = DefinedCategories.size();
04323 
04324   // Return null if no symbols were defined.
04325   if (!NumClasses && !NumCategories)
04326     return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
04327 
04328   llvm::Constant *Values[5];
04329   Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
04330   Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
04331   Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
04332   Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
04333 
04334   // The runtime expects exactly the list of defined classes followed
04335   // by the list of defined categories, in a single array.
04336   SmallVector<llvm::Constant*, 8> Symbols(NumClasses + NumCategories);
04337   for (unsigned i=0; i<NumClasses; i++) {
04338     const ObjCInterfaceDecl *ID = ImplementedClasses[i];
04339     assert(ID);
04340     if (ObjCImplementationDecl *IMP = ID->getImplementation())
04341       // We are implementing a weak imported interface. Give it external linkage
04342       if (ID->isWeakImported() && !IMP->isWeakImported())
04343         DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
04344     
04345     Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
04346                                                 ObjCTypes.Int8PtrTy);
04347   }
04348   for (unsigned i=0; i<NumCategories; i++)
04349     Symbols[NumClasses + i] =
04350       llvm::ConstantExpr::getBitCast(DefinedCategories[i],
04351                                      ObjCTypes.Int8PtrTy);
04352 
04353   Values[4] =
04354     llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
04355                                                   Symbols.size()),
04356                              Symbols);
04357 
04358   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
04359 
04360   llvm::GlobalVariable *GV = CreateMetadataVar(
04361       "OBJC_SYMBOLS", Init, "__OBJC,__symbols,regular,no_dead_strip", 4, true);
04362   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
04363 }
04364 
04365 llvm::Value *CGObjCMac::EmitClassRefFromId(CodeGenFunction &CGF,
04366                                            IdentifierInfo *II) {
04367   LazySymbols.insert(II);
04368   
04369   llvm::GlobalVariable *&Entry = ClassReferences[II];
04370   
04371   if (!Entry) {
04372     llvm::Constant *Casted =
04373     llvm::ConstantExpr::getBitCast(GetClassName(II->getName()),
04374                                    ObjCTypes.ClassPtrTy);
04375     Entry = CreateMetadataVar(
04376         "OBJC_CLASS_REFERENCES_", Casted,
04377         "__OBJC,__cls_refs,literal_pointers,no_dead_strip", 4, true);
04378   }
04379   
04380   return CGF.Builder.CreateLoad(Entry);
04381 }
04382 
04383 llvm::Value *CGObjCMac::EmitClassRef(CodeGenFunction &CGF,
04384                                      const ObjCInterfaceDecl *ID) {
04385   return EmitClassRefFromId(CGF, ID->getIdentifier());
04386 }
04387 
04388 llvm::Value *CGObjCMac::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
04389   IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
04390   return EmitClassRefFromId(CGF, II);
04391 }
04392 
04393 llvm::Value *CGObjCMac::EmitSelector(CodeGenFunction &CGF, Selector Sel,
04394                                      bool lvalue) {
04395   llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
04396 
04397   if (!Entry) {
04398     llvm::Constant *Casted =
04399       llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
04400                                      ObjCTypes.SelectorPtrTy);
04401     Entry = CreateMetadataVar(
04402         "OBJC_SELECTOR_REFERENCES_", Casted,
04403         "__OBJC,__message_refs,literal_pointers,no_dead_strip", 4, true);
04404     Entry->setExternallyInitialized(true);
04405   }
04406 
04407   if (lvalue)
04408     return Entry;
04409   return CGF.Builder.CreateLoad(Entry);
04410 }
04411 
04412 llvm::Constant *CGObjCCommonMac::GetClassName(StringRef RuntimeName) {
04413     llvm::GlobalVariable *&Entry = ClassNames[RuntimeName];
04414     if (!Entry)
04415       Entry = CreateMetadataVar(
04416           "OBJC_CLASS_NAME_",
04417           llvm::ConstantDataArray::getString(VMContext, RuntimeName),
04418           ((ObjCABI == 2) ? "__TEXT,__objc_classname,cstring_literals"
04419                           : "__TEXT,__cstring,cstring_literals"),
04420           1, true);
04421     return getConstantGEP(VMContext, Entry, 0, 0);
04422 }
04423 
04424 llvm::Function *CGObjCCommonMac::GetMethodDefinition(const ObjCMethodDecl *MD) {
04425   llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*>::iterator
04426       I = MethodDefinitions.find(MD);
04427   if (I != MethodDefinitions.end())
04428     return I->second;
04429 
04430   return nullptr;
04431 }
04432 
04433 /// GetIvarLayoutName - Returns a unique constant for the given
04434 /// ivar layout bitmap.
04435 llvm::Constant *CGObjCCommonMac::GetIvarLayoutName(IdentifierInfo *Ident,
04436                                        const ObjCCommonTypesHelper &ObjCTypes) {
04437   return llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
04438 }
04439 
04440 void CGObjCCommonMac::BuildAggrIvarRecordLayout(const RecordType *RT,
04441                                                 unsigned int BytePos,
04442                                                 bool ForStrongLayout,
04443                                                 bool &HasUnion) {
04444   const RecordDecl *RD = RT->getDecl();
04445   // FIXME - Use iterator.
04446   SmallVector<const FieldDecl*, 16> Fields(RD->fields());
04447   llvm::Type *Ty = CGM.getTypes().ConvertType(QualType(RT, 0));
04448   const llvm::StructLayout *RecLayout =
04449     CGM.getDataLayout().getStructLayout(cast<llvm::StructType>(Ty));
04450 
04451   BuildAggrIvarLayout(nullptr, RecLayout, RD, Fields, BytePos, ForStrongLayout,
04452                       HasUnion);
04453 }
04454 
04455 void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
04456                              const llvm::StructLayout *Layout,
04457                              const RecordDecl *RD,
04458                              ArrayRef<const FieldDecl*> RecFields,
04459                              unsigned int BytePos, bool ForStrongLayout,
04460                              bool &HasUnion) {
04461   bool IsUnion = (RD && RD->isUnion());
04462   uint64_t MaxUnionIvarSize = 0;
04463   uint64_t MaxSkippedUnionIvarSize = 0;
04464   const FieldDecl *MaxField = nullptr;
04465   const FieldDecl *MaxSkippedField = nullptr;
04466   const FieldDecl *LastFieldBitfieldOrUnnamed = nullptr;
04467   uint64_t MaxFieldOffset = 0;
04468   uint64_t MaxSkippedFieldOffset = 0;
04469   uint64_t LastBitfieldOrUnnamedOffset = 0;
04470   uint64_t FirstFieldDelta = 0;
04471 
04472   if (RecFields.empty())
04473     return;
04474   unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
04475   unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
04476   if (!RD && CGM.getLangOpts().ObjCAutoRefCount) {
04477     const FieldDecl *FirstField = RecFields[0];
04478     FirstFieldDelta = 
04479       ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(FirstField));
04480   }
04481   
04482   for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
04483     const FieldDecl *Field = RecFields[i];
04484     uint64_t FieldOffset;
04485     if (RD) {
04486       // Note that 'i' here is actually the field index inside RD of Field,
04487       // although this dependency is hidden.
04488       const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
04489       FieldOffset = (RL.getFieldOffset(i) / ByteSizeInBits) - FirstFieldDelta;
04490     } else
04491       FieldOffset = 
04492         ComputeIvarBaseOffset(CGM, OI, cast<ObjCIvarDecl>(Field)) - FirstFieldDelta;
04493 
04494     // Skip over unnamed or bitfields
04495     if (!Field->getIdentifier() || Field->isBitField()) {
04496       LastFieldBitfieldOrUnnamed = Field;
04497       LastBitfieldOrUnnamedOffset = FieldOffset;
04498       continue;
04499     }
04500 
04501     LastFieldBitfieldOrUnnamed = nullptr;
04502     QualType FQT = Field->getType();
04503     if (FQT->isRecordType() || FQT->isUnionType()) {
04504       if (FQT->isUnionType())
04505         HasUnion = true;
04506 
04507       BuildAggrIvarRecordLayout(FQT->getAs<RecordType>(),
04508                                 BytePos + FieldOffset,
04509                                 ForStrongLayout, HasUnion);
04510       continue;
04511     }
04512 
04513     if (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
04514       const ConstantArrayType *CArray =
04515         dyn_cast_or_null<ConstantArrayType>(Array);
04516       uint64_t ElCount = CArray->getSize().getZExtValue();
04517       assert(CArray && "only array with known element size is supported");
04518       FQT = CArray->getElementType();
04519       while (const ArrayType *Array = CGM.getContext().getAsArrayType(FQT)) {
04520         const ConstantArrayType *CArray =
04521           dyn_cast_or_null<ConstantArrayType>(Array);
04522         ElCount *= CArray->getSize().getZExtValue();
04523         FQT = CArray->getElementType();
04524       }
04525       if (FQT->isRecordType() && ElCount) {
04526         int OldIndex = IvarsInfo.size() - 1;
04527         int OldSkIndex = SkipIvars.size() -1;
04528 
04529         const RecordType *RT = FQT->getAs<RecordType>();
04530         BuildAggrIvarRecordLayout(RT, BytePos + FieldOffset,
04531                                   ForStrongLayout, HasUnion);
04532 
04533         // Replicate layout information for each array element. Note that
04534         // one element is already done.
04535         uint64_t ElIx = 1;
04536         for (int FirstIndex = IvarsInfo.size() - 1,
04537                FirstSkIndex = SkipIvars.size() - 1 ;ElIx < ElCount; ElIx++) {
04538           uint64_t Size = CGM.getContext().getTypeSize(RT)/ByteSizeInBits;
04539           for (int i = OldIndex+1; i <= FirstIndex; ++i)
04540             IvarsInfo.push_back(GC_IVAR(IvarsInfo[i].ivar_bytepos + Size*ElIx,
04541                                         IvarsInfo[i].ivar_size));
04542           for (int i = OldSkIndex+1; i <= FirstSkIndex; ++i)
04543             SkipIvars.push_back(GC_IVAR(SkipIvars[i].ivar_bytepos + Size*ElIx,
04544                                         SkipIvars[i].ivar_size));
04545         }
04546         continue;
04547       }
04548     }
04549     // At this point, we are done with Record/Union and array there of.
04550     // For other arrays we are down to its element type.
04551     Qualifiers::GC GCAttr = GetGCAttrTypeForType(CGM.getContext(), FQT);
04552 
04553     unsigned FieldSize = CGM.getContext().getTypeSize(Field->getType());
04554     if ((ForStrongLayout && GCAttr == Qualifiers::Strong)
04555         || (!ForStrongLayout && GCAttr == Qualifiers::Weak)) {
04556       if (IsUnion) {
04557         uint64_t UnionIvarSize = FieldSize / WordSizeInBits;
04558         if (UnionIvarSize > MaxUnionIvarSize) {
04559           MaxUnionIvarSize = UnionIvarSize;
04560           MaxField = Field;
04561           MaxFieldOffset = FieldOffset;
04562         }
04563       } else {
04564         IvarsInfo.push_back(GC_IVAR(BytePos + FieldOffset,
04565                                     FieldSize / WordSizeInBits));
04566       }
04567     } else if ((ForStrongLayout &&
04568                 (GCAttr == Qualifiers::GCNone || GCAttr == Qualifiers::Weak))
04569                || (!ForStrongLayout && GCAttr != Qualifiers::Weak)) {
04570       if (IsUnion) {
04571         // FIXME: Why the asymmetry? We divide by word size in bits on other
04572         // side.
04573         uint64_t UnionIvarSize = FieldSize / ByteSizeInBits;
04574         if (UnionIvarSize > MaxSkippedUnionIvarSize) {
04575           MaxSkippedUnionIvarSize = UnionIvarSize;
04576           MaxSkippedField = Field;
04577           MaxSkippedFieldOffset = FieldOffset;
04578         }
04579       } else {
04580         // FIXME: Why the asymmetry, we divide by byte size in bits here?
04581         SkipIvars.push_back(GC_IVAR(BytePos + FieldOffset,
04582                                     FieldSize / ByteSizeInBits));
04583       }
04584     }
04585   }
04586 
04587   if (LastFieldBitfieldOrUnnamed) {
04588     if (LastFieldBitfieldOrUnnamed->isBitField()) {
04589       // Last field was a bitfield. Must update skip info.
04590       uint64_t BitFieldSize
04591           = LastFieldBitfieldOrUnnamed->getBitWidthValue(CGM.getContext());
04592       GC_IVAR skivar;
04593       skivar.ivar_bytepos = BytePos + LastBitfieldOrUnnamedOffset;
04594       skivar.ivar_size = (BitFieldSize / ByteSizeInBits)
04595         + ((BitFieldSize % ByteSizeInBits) != 0);
04596       SkipIvars.push_back(skivar);
04597     } else {
04598       assert(!LastFieldBitfieldOrUnnamed->getIdentifier() &&"Expected unnamed");
04599       // Last field was unnamed. Must update skip info.
04600       unsigned FieldSize
04601           = CGM.getContext().getTypeSize(LastFieldBitfieldOrUnnamed->getType());
04602       SkipIvars.push_back(GC_IVAR(BytePos + LastBitfieldOrUnnamedOffset,
04603                                   FieldSize / ByteSizeInBits));
04604     }
04605   }
04606 
04607   if (MaxField)
04608     IvarsInfo.push_back(GC_IVAR(BytePos + MaxFieldOffset,
04609                                 MaxUnionIvarSize));
04610   if (MaxSkippedField)
04611     SkipIvars.push_back(GC_IVAR(BytePos + MaxSkippedFieldOffset,
04612                                 MaxSkippedUnionIvarSize));
04613 }
04614 
04615 /// BuildIvarLayoutBitmap - This routine is the horsework for doing all
04616 /// the computations and returning the layout bitmap (for ivar or blocks) in
04617 /// the given argument BitMap string container. Routine reads
04618 /// two containers, IvarsInfo and SkipIvars which are assumed to be
04619 /// filled already by the caller.
04620 llvm::Constant *CGObjCCommonMac::BuildIvarLayoutBitmap(std::string &BitMap) {
04621   unsigned int WordsToScan, WordsToSkip;
04622   llvm::Type *PtrTy = CGM.Int8PtrTy;
04623   
04624   // Build the string of skip/scan nibbles
04625   SmallVector<SKIP_SCAN, 32> SkipScanIvars;
04626   unsigned int WordSize =
04627   CGM.getTypes().getDataLayout().getTypeAllocSize(PtrTy);
04628   if (IvarsInfo[0].ivar_bytepos == 0) {
04629     WordsToSkip = 0;
04630     WordsToScan = IvarsInfo[0].ivar_size;
04631   } else {
04632     WordsToSkip = IvarsInfo[0].ivar_bytepos/WordSize;
04633     WordsToScan = IvarsInfo[0].ivar_size;
04634   }
04635   for (unsigned int i=1, Last=IvarsInfo.size(); i != Last; i++) {
04636     unsigned int TailPrevGCObjC =
04637     IvarsInfo[i-1].ivar_bytepos + IvarsInfo[i-1].ivar_size * WordSize;
04638     if (IvarsInfo[i].ivar_bytepos == TailPrevGCObjC) {
04639       // consecutive 'scanned' object pointers.
04640       WordsToScan += IvarsInfo[i].ivar_size;
04641     } else {
04642       // Skip over 'gc'able object pointer which lay over each other.
04643       if (TailPrevGCObjC > IvarsInfo[i].ivar_bytepos)
04644         continue;
04645       // Must skip over 1 or more words. We save current skip/scan values
04646       //  and start a new pair.
04647       SKIP_SCAN SkScan;
04648       SkScan.skip = WordsToSkip;
04649       SkScan.scan = WordsToScan;
04650       SkipScanIvars.push_back(SkScan);
04651       
04652       // Skip the hole.
04653       SkScan.skip = (IvarsInfo[i].ivar_bytepos - TailPrevGCObjC) / WordSize;
04654       SkScan.scan = 0;
04655       SkipScanIvars.push_back(SkScan);
04656       WordsToSkip = 0;
04657       WordsToScan = IvarsInfo[i].ivar_size;
04658     }
04659   }
04660   if (WordsToScan > 0) {
04661     SKIP_SCAN SkScan;
04662     SkScan.skip = WordsToSkip;
04663     SkScan.scan = WordsToScan;
04664     SkipScanIvars.push_back(SkScan);
04665   }
04666   
04667   if (!SkipIvars.empty()) {
04668     unsigned int LastIndex = SkipIvars.size()-1;
04669     int LastByteSkipped =
04670     SkipIvars[LastIndex].ivar_bytepos + SkipIvars[LastIndex].ivar_size;
04671     LastIndex = IvarsInfo.size()-1;
04672     int LastByteScanned =
04673     IvarsInfo[LastIndex].ivar_bytepos +
04674     IvarsInfo[LastIndex].ivar_size * WordSize;
04675     // Compute number of bytes to skip at the tail end of the last ivar scanned.
04676     if (LastByteSkipped > LastByteScanned) {
04677       unsigned int TotalWords = (LastByteSkipped + (WordSize -1)) / WordSize;
04678       SKIP_SCAN SkScan;
04679       SkScan.skip = TotalWords - (LastByteScanned/WordSize);
04680       SkScan.scan = 0;
04681       SkipScanIvars.push_back(SkScan);
04682     }
04683   }
04684   // Mini optimization of nibbles such that an 0xM0 followed by 0x0N is produced
04685   // as 0xMN.
04686   int SkipScan = SkipScanIvars.size()-1;
04687   for (int i = 0; i <= SkipScan; i++) {
04688     if ((i < SkipScan) && SkipScanIvars[i].skip && SkipScanIvars[i].scan == 0
04689         && SkipScanIvars[i+1].skip == 0 && SkipScanIvars[i+1].scan) {
04690       // 0xM0 followed by 0x0N detected.
04691       SkipScanIvars[i].scan = SkipScanIvars[i+1].scan;
04692       for (int j = i+1; j < SkipScan; j++)
04693         SkipScanIvars[j] = SkipScanIvars[j+1];
04694       --SkipScan;
04695     }
04696   }
04697   
04698   // Generate the string.
04699   for (int i = 0; i <= SkipScan; i++) {
04700     unsigned char byte;
04701     unsigned int skip_small = SkipScanIvars[i].skip % 0xf;
04702     unsigned int scan_small = SkipScanIvars[i].scan % 0xf;
04703     unsigned int skip_big  = SkipScanIvars[i].skip / 0xf;
04704     unsigned int scan_big  = SkipScanIvars[i].scan / 0xf;
04705     
04706     // first skip big.
04707     for (unsigned int ix = 0; ix < skip_big; ix++)
04708       BitMap += (unsigned char)(0xf0);
04709     
04710     // next (skip small, scan)
04711     if (skip_small) {
04712       byte = skip_small << 4;
04713       if (scan_big > 0) {
04714         byte |= 0xf;
04715         --scan_big;
04716       } else if (scan_small) {
04717         byte |= scan_small;
04718         scan_small = 0;
04719       }
04720       BitMap += byte;
04721     }
04722     // next scan big
04723     for (unsigned int ix = 0; ix < scan_big; ix++)
04724       BitMap += (unsigned char)(0x0f);
04725     // last scan small
04726     if (scan_small) {
04727       byte = scan_small;
04728       BitMap += byte;
04729     }
04730   }
04731   // null terminate string.
04732   unsigned char zero = 0;
04733   BitMap += zero;
04734 
04735   llvm::GlobalVariable *Entry = CreateMetadataVar(
04736       "OBJC_CLASS_NAME_",
04737       llvm::ConstantDataArray::getString(VMContext, BitMap, false),
04738       ((ObjCABI == 2) ? "__TEXT,__objc_classname,cstring_literals"
04739                       : "__TEXT,__cstring,cstring_literals"),
04740       1, true);
04741   return getConstantGEP(VMContext, Entry, 0, 0);
04742 }
04743 
04744 /// BuildIvarLayout - Builds ivar layout bitmap for the class
04745 /// implementation for the __strong or __weak case.
04746 /// The layout map displays which words in ivar list must be skipped
04747 /// and which must be scanned by GC (see below). String is built of bytes.
04748 /// Each byte is divided up in two nibbles (4-bit each). Left nibble is count
04749 /// of words to skip and right nibble is count of words to scan. So, each
04750 /// nibble represents up to 15 workds to skip or scan. Skipping the rest is
04751 /// represented by a 0x00 byte which also ends the string.
04752 /// 1. when ForStrongLayout is true, following ivars are scanned:
04753 /// - id, Class
04754 /// - object *
04755 /// - __strong anything
04756 ///
04757 /// 2. When ForStrongLayout is false, following ivars are scanned:
04758 /// - __weak anything
04759 ///
04760 llvm::Constant *CGObjCCommonMac::BuildIvarLayout(
04761   const ObjCImplementationDecl *OMD,
04762   bool ForStrongLayout) {
04763   bool hasUnion = false;
04764 
04765   llvm::Type *PtrTy = CGM.Int8PtrTy;
04766   if (CGM.getLangOpts().getGC() == LangOptions::NonGC &&
04767       !CGM.getLangOpts().ObjCAutoRefCount)
04768     return llvm::Constant::getNullValue(PtrTy);
04769 
04770   const ObjCInterfaceDecl *OI = OMD->getClassInterface();
04771   SmallVector<const FieldDecl*, 32> RecFields;
04772   if (CGM.getLangOpts().ObjCAutoRefCount) {
04773     for (const ObjCIvarDecl *IVD = OI->all_declared_ivar_begin(); 
04774          IVD; IVD = IVD->getNextIvar())
04775       RecFields.push_back(cast<FieldDecl>(IVD));
04776   }
04777   else {
04778     SmallVector<const ObjCIvarDecl*, 32> Ivars;
04779     CGM.getContext().DeepCollectObjCIvars(OI, true, Ivars);
04780 
04781     // FIXME: This is not ideal; we shouldn't have to do this copy.
04782     RecFields.append(Ivars.begin(), Ivars.end());
04783   }
04784 
04785   if (RecFields.empty())
04786     return llvm::Constant::getNullValue(PtrTy);
04787 
04788   SkipIvars.clear();
04789   IvarsInfo.clear();
04790 
04791   BuildAggrIvarLayout(OMD, nullptr, nullptr, RecFields, 0, ForStrongLayout,
04792                       hasUnion);
04793   if (IvarsInfo.empty())
04794     return llvm::Constant::getNullValue(PtrTy);
04795   // Sort on byte position in case we encounterred a union nested in
04796   // the ivar list.
04797   if (hasUnion && !IvarsInfo.empty())
04798     std::sort(IvarsInfo.begin(), IvarsInfo.end());
04799   if (hasUnion && !SkipIvars.empty())
04800     std::sort(SkipIvars.begin(), SkipIvars.end());
04801   
04802   std::string BitMap;
04803   llvm::Constant *C = BuildIvarLayoutBitmap(BitMap);
04804   
04805    if (CGM.getLangOpts().ObjCGCBitmapPrint) {
04806     printf("\n%s ivar layout for class '%s': ",
04807            ForStrongLayout ? "strong" : "weak",
04808            OMD->getClassInterface()->getName().str().c_str());
04809     const unsigned char *s = (const unsigned char*)BitMap.c_str();
04810     for (unsigned i = 0, e = BitMap.size(); i < e; i++)
04811       if (!(s[i] & 0xf0))
04812         printf("0x0%x%s", s[i], s[i] != 0 ? ", " : "");
04813       else
04814         printf("0x%x%s",  s[i], s[i] != 0 ? ", " : "");
04815     printf("\n");
04816   }
04817   return C;
04818 }
04819 
04820 llvm::Constant *CGObjCCommonMac::GetMethodVarName(Selector Sel) {
04821   llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
04822 
04823   // FIXME: Avoid std::string in "Sel.getAsString()"
04824   if (!Entry)
04825     Entry = CreateMetadataVar(
04826         "OBJC_METH_VAR_NAME_",
04827         llvm::ConstantDataArray::getString(VMContext, Sel.getAsString()),
04828         ((ObjCABI == 2) ? "__TEXT,__objc_methname,cstring_literals"
04829                         : "__TEXT,__cstring,cstring_literals"),
04830         1, true);
04831 
04832   return getConstantGEP(VMContext, Entry, 0, 0);
04833 }
04834 
04835 // FIXME: Merge into a single cstring creation function.
04836 llvm::Constant *CGObjCCommonMac::GetMethodVarName(IdentifierInfo *ID) {
04837   return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
04838 }
04839 
04840 llvm::Constant *CGObjCCommonMac::GetMethodVarType(const FieldDecl *Field) {
04841   std::string TypeStr;
04842   CGM.getContext().getObjCEncodingForType(Field->getType(), TypeStr, Field);
04843 
04844   llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
04845 
04846   if (!Entry)
04847     Entry = CreateMetadataVar(
04848         "OBJC_METH_VAR_TYPE_",
04849         llvm::ConstantDataArray::getString(VMContext, TypeStr),
04850         ((ObjCABI == 2) ? "__TEXT,__objc_methtype,cstring_literals"
04851                         : "__TEXT,__cstring,cstring_literals"),
04852         1, true);
04853 
04854   return getConstantGEP(VMContext, Entry, 0, 0);
04855 }
04856 
04857 llvm::Constant *CGObjCCommonMac::GetMethodVarType(const ObjCMethodDecl *D,
04858                                                   bool Extended) {
04859   std::string TypeStr;
04860   if (CGM.getContext().getObjCEncodingForMethodDecl(D, TypeStr, Extended))
04861     return nullptr;
04862 
04863   llvm::GlobalVariable *&Entry = MethodVarTypes[TypeStr];
04864 
04865   if (!Entry)
04866     Entry = CreateMetadataVar(
04867         "OBJC_METH_VAR_TYPE_",
04868         llvm::ConstantDataArray::getString(VMContext, TypeStr),
04869         ((ObjCABI == 2) ? "__TEXT,__objc_methtype,cstring_literals"
04870                         : "__TEXT,__cstring,cstring_literals"),
04871         1, true);
04872 
04873   return getConstantGEP(VMContext, Entry, 0, 0);
04874 }
04875 
04876 // FIXME: Merge into a single cstring creation function.
04877 llvm::Constant *CGObjCCommonMac::GetPropertyName(IdentifierInfo *Ident) {
04878   llvm::GlobalVariable *&Entry = PropertyNames[Ident];
04879 
04880   if (!Entry)
04881     Entry = CreateMetadataVar(
04882         "OBJC_PROP_NAME_ATTR_",
04883         llvm::ConstantDataArray::getString(VMContext, Ident->getName()),
04884         "__TEXT,__cstring,cstring_literals", 1, true);
04885 
04886   return getConstantGEP(VMContext, Entry, 0, 0);
04887 }
04888 
04889 // FIXME: Merge into a single cstring creation function.
04890 // FIXME: This Decl should be more precise.
04891 llvm::Constant *
04892 CGObjCCommonMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
04893                                        const Decl *Container) {
04894   std::string TypeStr;
04895   CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
04896   return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
04897 }
04898 
04899 void CGObjCCommonMac::GetNameForMethod(const ObjCMethodDecl *D,
04900                                        const ObjCContainerDecl *CD,
04901                                        SmallVectorImpl<char> &Name) {
04902   llvm::raw_svector_ostream OS(Name);
04903   assert (CD && "Missing container decl in GetNameForMethod");
04904   OS << '\01' << (D->isInstanceMethod() ? '-' : '+')
04905      << '[' << CD->getName();
04906   if (const ObjCCategoryImplDecl *CID =
04907       dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext()))
04908     OS << '(' << *CID << ')';
04909   OS << ' ' << D->getSelector().getAsString() << ']';
04910 }
04911 
04912 void CGObjCMac::FinishModule() {
04913   EmitModuleInfo();
04914 
04915   // Emit the dummy bodies for any protocols which were referenced but
04916   // never defined.
04917   for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
04918          I = Protocols.begin(), e = Protocols.end(); I != e; ++I) {
04919     if (I->second->hasInitializer())
04920       continue;
04921 
04922     llvm::Constant *Values[5];
04923     Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
04924     Values[1] = GetClassName(I->first->getName());
04925     Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
04926     Values[3] = Values[4] =
04927       llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
04928     I->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
04929                                                         Values));
04930     CGM.addCompilerUsedGlobal(I->second);
04931   }
04932 
04933   // Add assembler directives to add lazy undefined symbol references
04934   // for classes which are referenced but not defined. This is
04935   // important for correct linker interaction.
04936   //
04937   // FIXME: It would be nice if we had an LLVM construct for this.
04938   if (!LazySymbols.empty() || !DefinedSymbols.empty()) {
04939     SmallString<256> Asm;
04940     Asm += CGM.getModule().getModuleInlineAsm();
04941     if (!Asm.empty() && Asm.back() != '\n')
04942       Asm += '\n';
04943 
04944     llvm::raw_svector_ostream OS(Asm);
04945     for (llvm::SetVector<IdentifierInfo*>::iterator I = DefinedSymbols.begin(),
04946            e = DefinedSymbols.end(); I != e; ++I)
04947       OS << "\t.objc_class_name_" << (*I)->getName() << "=0\n"
04948          << "\t.globl .objc_class_name_" << (*I)->getName() << "\n";
04949     for (llvm::SetVector<IdentifierInfo*>::iterator I = LazySymbols.begin(),
04950          e = LazySymbols.end(); I != e; ++I) {
04951       OS << "\t.lazy_reference .objc_class_name_" << (*I)->getName() << "\n";
04952     }
04953 
04954     for (size_t i = 0, e = DefinedCategoryNames.size(); i < e; ++i) {
04955       OS << "\t.objc_category_name_" << DefinedCategoryNames[i] << "=0\n"
04956          << "\t.globl .objc_category_name_" << DefinedCategoryNames[i] << "\n";
04957     }
04958     
04959     CGM.getModule().setModuleInlineAsm(OS.str());
04960   }
04961 }
04962 
04963 CGObjCNonFragileABIMac::CGObjCNonFragileABIMac(CodeGen::CodeGenModule &cgm)
04964   : CGObjCCommonMac(cgm),
04965     ObjCTypes(cgm) {
04966   ObjCEmptyCacheVar = ObjCEmptyVtableVar = nullptr;
04967   ObjCABI = 2;
04968 }
04969 
04970 /* *** */
04971 
04972 ObjCCommonTypesHelper::ObjCCommonTypesHelper(CodeGen::CodeGenModule &cgm)
04973   : VMContext(cgm.getLLVMContext()), CGM(cgm), ExternalProtocolPtrTy(nullptr)
04974 {
04975   CodeGen::CodeGenTypes &Types = CGM.getTypes();
04976   ASTContext &Ctx = CGM.getContext();
04977 
04978   ShortTy = Types.ConvertType(Ctx.ShortTy);
04979   IntTy = Types.ConvertType(Ctx.IntTy);
04980   LongTy = Types.ConvertType(Ctx.LongTy);
04981   LongLongTy = Types.ConvertType(Ctx.LongLongTy);
04982   Int8PtrTy = CGM.Int8PtrTy;
04983   Int8PtrPtrTy = CGM.Int8PtrPtrTy;
04984 
04985   // arm64 targets use "int" ivar offset variables. All others,
04986   // including OS X x86_64 and Windows x86_64, use "long" ivar offsets.
04987   if (CGM.getTarget().getTriple().getArch() == llvm::Triple::aarch64)
04988     IvarOffsetVarTy = IntTy;
04989   else
04990     IvarOffsetVarTy = LongTy;
04991 
04992   ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
04993   PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
04994   SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
04995 
04996   // I'm not sure I like this. The implicit coordination is a bit
04997   // gross. We should solve this in a reasonable fashion because this
04998   // is a pretty common task (match some runtime data structure with
04999   // an LLVM data structure).
05000 
05001   // FIXME: This is leaked.
05002   // FIXME: Merge with rewriter code?
05003 
05004   // struct _objc_super {
05005   //   id self;
05006   //   Class cls;
05007   // }
05008   RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct,
05009                                       Ctx.getTranslationUnitDecl(),
05010                                       SourceLocation(), SourceLocation(),
05011                                       &Ctx.Idents.get("_objc_super"));
05012   RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
05013                                 nullptr, Ctx.getObjCIdType(), nullptr, nullptr,
05014                                 false, ICIS_NoInit));
05015   RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
05016                                 nullptr, Ctx.getObjCClassType(), nullptr,
05017                                 nullptr, false, ICIS_NoInit));
05018   RD->completeDefinition();
05019 
05020   SuperCTy = Ctx.getTagDeclType(RD);
05021   SuperPtrCTy = Ctx.getPointerType(SuperCTy);
05022 
05023   SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
05024   SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
05025 
05026   // struct _prop_t {
05027   //   char *name;
05028   //   char *attributes;
05029   // }
05030   PropertyTy = llvm::StructType::create("struct._prop_t",
05031                                         Int8PtrTy, Int8PtrTy, nullptr);
05032 
05033   // struct _prop_list_t {
05034   //   uint32_t entsize;      // sizeof(struct _prop_t)
05035   //   uint32_t count_of_properties;
05036   //   struct _prop_t prop_list[count_of_properties];
05037   // }
05038   PropertyListTy =
05039     llvm::StructType::create("struct._prop_list_t", IntTy, IntTy,
05040                              llvm::ArrayType::get(PropertyTy, 0), nullptr);
05041   // struct _prop_list_t *
05042   PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
05043 
05044   // struct _objc_method {
05045   //   SEL _cmd;
05046   //   char *method_type;
05047   //   char *_imp;
05048   // }
05049   MethodTy = llvm::StructType::create("struct._objc_method",
05050                                       SelectorPtrTy, Int8PtrTy, Int8PtrTy,
05051                                       nullptr);
05052 
05053   // struct _objc_cache *
05054   CacheTy = llvm::StructType::create(VMContext, "struct._objc_cache");
05055   CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
05056     
05057 }
05058 
05059 ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
05060   : ObjCCommonTypesHelper(cgm) {
05061   // struct _objc_method_description {
05062   //   SEL name;
05063   //   char *types;
05064   // }
05065   MethodDescriptionTy =
05066     llvm::StructType::create("struct._objc_method_description",
05067                              SelectorPtrTy, Int8PtrTy, nullptr);
05068 
05069   // struct _objc_method_description_list {
05070   //   int count;
05071   //   struct _objc_method_description[1];
05072   // }
05073   MethodDescriptionListTy = llvm::StructType::create(
05074       "struct._objc_method_description_list", IntTy,
05075       llvm::ArrayType::get(MethodDescriptionTy, 0), nullptr);
05076 
05077   // struct _objc_method_description_list *
05078   MethodDescriptionListPtrTy =
05079     llvm::PointerType::getUnqual(MethodDescriptionListTy);
05080 
05081   // Protocol description structures
05082 
05083   // struct _objc_protocol_extension {
05084   //   uint32_t size;  // sizeof(struct _objc_protocol_extension)
05085   //   struct _objc_method_description_list *optional_instance_methods;
05086   //   struct _objc_method_description_list *optional_class_methods;
05087   //   struct _objc_property_list *instance_properties;
05088   //   const char ** extendedMethodTypes;
05089   // }
05090   ProtocolExtensionTy =
05091     llvm::StructType::create("struct._objc_protocol_extension",
05092                              IntTy, MethodDescriptionListPtrTy,
05093                              MethodDescriptionListPtrTy, PropertyListPtrTy,
05094                              Int8PtrPtrTy, nullptr);
05095 
05096   // struct _objc_protocol_extension *
05097   ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
05098 
05099   // Handle recursive construction of Protocol and ProtocolList types
05100 
05101   ProtocolTy =
05102     llvm::StructType::create(VMContext, "struct._objc_protocol");
05103 
05104   ProtocolListTy =
05105     llvm::StructType::create(VMContext, "struct._objc_protocol_list");
05106   ProtocolListTy->setBody(llvm::PointerType::getUnqual(ProtocolListTy),
05107                           LongTy,
05108                           llvm::ArrayType::get(ProtocolTy, 0),
05109                           nullptr);
05110 
05111   // struct _objc_protocol {
05112   //   struct _objc_protocol_extension *isa;
05113   //   char *protocol_name;
05114   //   struct _objc_protocol **_objc_protocol_list;
05115   //   struct _objc_method_description_list *instance_methods;
05116   //   struct _objc_method_description_list *class_methods;
05117   // }
05118   ProtocolTy->setBody(ProtocolExtensionPtrTy, Int8PtrTy,
05119                       llvm::PointerType::getUnqual(ProtocolListTy),
05120                       MethodDescriptionListPtrTy,
05121                       MethodDescriptionListPtrTy,
05122                       nullptr);
05123 
05124   // struct _objc_protocol_list *
05125   ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
05126 
05127   ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
05128 
05129   // Class description structures
05130 
05131   // struct _objc_ivar {
05132   //   char *ivar_name;
05133   //   char *ivar_type;
05134   //   int  ivar_offset;
05135   // }
05136   IvarTy = llvm::StructType::create("struct._objc_ivar",
05137                                     Int8PtrTy, Int8PtrTy, IntTy, nullptr);
05138 
05139   // struct _objc_ivar_list *
05140   IvarListTy =
05141     llvm::StructType::create(VMContext, "struct._objc_ivar_list");
05142   IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
05143 
05144   // struct _objc_method_list *
05145   MethodListTy =
05146     llvm::StructType::create(VMContext, "struct._objc_method_list");
05147   MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
05148 
05149   // struct _objc_class_extension *
05150   ClassExtensionTy =
05151     llvm::StructType::create("struct._objc_class_extension",
05152                              IntTy, Int8PtrTy, PropertyListPtrTy, nullptr);
05153   ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
05154 
05155   ClassTy = llvm::StructType::create(VMContext, "struct._objc_class");
05156 
05157   // struct _objc_class {
05158   //   Class isa;
05159   //   Class super_class;
05160   //   char *name;
05161   //   long version;
05162   //   long info;
05163   //   long instance_size;
05164   //   struct _objc_ivar_list *ivars;
05165   //   struct _objc_method_list *methods;
05166   //   struct _objc_cache *cache;
05167   //   struct _objc_protocol_list *protocols;
05168   //   char *ivar_layout;
05169   //   struct _objc_class_ext *ext;
05170   // };
05171   ClassTy->setBody(llvm::PointerType::getUnqual(ClassTy),
05172                    llvm::PointerType::getUnqual(ClassTy),
05173                    Int8PtrTy,
05174                    LongTy,
05175                    LongTy,
05176                    LongTy,
05177                    IvarListPtrTy,
05178                    MethodListPtrTy,
05179                    CachePtrTy,
05180                    ProtocolListPtrTy,
05181                    Int8PtrTy,
05182                    ClassExtensionPtrTy,
05183                    nullptr);
05184 
05185   ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
05186 
05187   // struct _objc_category {
05188   //   char *category_name;
05189   //   char *class_name;
05190   //   struct _objc_method_list *instance_method;
05191   //   struct _objc_method_list *class_method;
05192   //   uint32_t size;  // sizeof(struct _objc_category)
05193   //   struct _objc_property_list *instance_properties;// category's @property
05194   // }
05195   CategoryTy =
05196     llvm::StructType::create("struct._objc_category",
05197                              Int8PtrTy, Int8PtrTy, MethodListPtrTy,
05198                              MethodListPtrTy, ProtocolListPtrTy,
05199                              IntTy, PropertyListPtrTy, nullptr);
05200 
05201   // Global metadata structures
05202 
05203   // struct _objc_symtab {
05204   //   long sel_ref_cnt;
05205   //   SEL *refs;
05206   //   short cls_def_cnt;
05207   //   short cat_def_cnt;
05208   //   char *defs[cls_def_cnt + cat_def_cnt];
05209   // }
05210   SymtabTy =
05211     llvm::StructType::create("struct._objc_symtab",
05212                              LongTy, SelectorPtrTy, ShortTy, ShortTy,
05213                              llvm::ArrayType::get(Int8PtrTy, 0), nullptr);
05214   SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
05215 
05216   // struct _objc_module {
05217   //   long version;
05218   //   long size;   // sizeof(struct _objc_module)
05219   //   char *name;
05220   //   struct _objc_symtab* symtab;
05221   //  }
05222   ModuleTy =
05223     llvm::StructType::create("struct._objc_module",
05224                              LongTy, LongTy, Int8PtrTy, SymtabPtrTy, nullptr);
05225 
05226 
05227   // FIXME: This is the size of the setjmp buffer and should be target
05228   // specific. 18 is what's used on 32-bit X86.
05229   uint64_t SetJmpBufferSize = 18;
05230 
05231   // Exceptions
05232   llvm::Type *StackPtrTy = llvm::ArrayType::get(CGM.Int8PtrTy, 4);
05233 
05234   ExceptionDataTy =
05235     llvm::StructType::create("struct._objc_exception_data",
05236                              llvm::ArrayType::get(CGM.Int32Ty,SetJmpBufferSize),
05237                              StackPtrTy, nullptr);
05238 
05239 }
05240 
05241 ObjCNonFragileABITypesHelper::ObjCNonFragileABITypesHelper(CodeGen::CodeGenModule &cgm)
05242   : ObjCCommonTypesHelper(cgm) {
05243   // struct _method_list_t {
05244   //   uint32_t entsize;  // sizeof(struct _objc_method)
05245   //   uint32_t method_count;
05246   //   struct _objc_method method_list[method_count];
05247   // }
05248   MethodListnfABITy =
05249     llvm::StructType::create("struct.__method_list_t", IntTy, IntTy,
05250                              llvm::ArrayType::get(MethodTy, 0), nullptr);
05251   // struct method_list_t *
05252   MethodListnfABIPtrTy = llvm::PointerType::getUnqual(MethodListnfABITy);
05253 
05254   // struct _protocol_t {
05255   //   id isa;  // NULL
05256   //   const char * const protocol_name;
05257   //   const struct _protocol_list_t * protocol_list; // super protocols
05258   //   const struct method_list_t * const instance_methods;
05259   //   const struct method_list_t * const class_methods;
05260   //   const struct method_list_t *optionalInstanceMethods;
05261   //   const struct method_list_t *optionalClassMethods;
05262   //   const struct _prop_list_t * properties;
05263   //   const uint32_t size;  // sizeof(struct _protocol_t)
05264   //   const uint32_t flags;  // = 0
05265   //   const char ** extendedMethodTypes;
05266   // }
05267 
05268   // Holder for struct _protocol_list_t *
05269   ProtocolListnfABITy =
05270     llvm::StructType::create(VMContext, "struct._objc_protocol_list");
05271 
05272   ProtocolnfABITy =
05273     llvm::StructType::create("struct._protocol_t", ObjectPtrTy, Int8PtrTy,
05274                              llvm::PointerType::getUnqual(ProtocolListnfABITy),
05275                              MethodListnfABIPtrTy, MethodListnfABIPtrTy,
05276                              MethodListnfABIPtrTy, MethodListnfABIPtrTy,
05277                              PropertyListPtrTy, IntTy, IntTy, Int8PtrPtrTy,
05278                              nullptr);
05279 
05280   // struct _protocol_t*
05281   ProtocolnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolnfABITy);
05282 
05283   // struct _protocol_list_t {
05284   //   long protocol_count;   // Note, this is 32/64 bit
05285   //   struct _protocol_t *[protocol_count];
05286   // }
05287   ProtocolListnfABITy->setBody(LongTy,
05288                                llvm::ArrayType::get(ProtocolnfABIPtrTy, 0),
05289                                nullptr);
05290 
05291   // struct _objc_protocol_list*
05292   ProtocolListnfABIPtrTy = llvm::PointerType::getUnqual(ProtocolListnfABITy);
05293 
05294   // struct _ivar_t {
05295   //   unsigned [long] int *offset;  // pointer to ivar offset location
05296   //   char *name;
05297   //   char *type;
05298   //   uint32_t alignment;
05299   //   uint32_t size;
05300   // }
05301   IvarnfABITy = llvm::StructType::create(
05302       "struct._ivar_t", llvm::PointerType::getUnqual(IvarOffsetVarTy),
05303       Int8PtrTy, Int8PtrTy, IntTy, IntTy, nullptr);
05304 
05305   // struct _ivar_list_t {
05306   //   uint32 entsize;  // sizeof(struct _ivar_t)
05307   //   uint32 count;
05308   //   struct _iver_t list[count];
05309   // }
05310   IvarListnfABITy =
05311     llvm::StructType::create("struct._ivar_list_t", IntTy, IntTy,
05312                              llvm::ArrayType::get(IvarnfABITy, 0), nullptr);
05313 
05314   IvarListnfABIPtrTy = llvm::PointerType::getUnqual(IvarListnfABITy);
05315 
05316   // struct _class_ro_t {
05317   //   uint32_t const flags;
05318   //   uint32_t const instanceStart;
05319   //   uint32_t const instanceSize;
05320   //   uint32_t const reserved;  // only when building for 64bit targets
05321   //   const uint8_t * const ivarLayout;
05322   //   const char *const name;
05323   //   const struct _method_list_t * const baseMethods;
05324   //   const struct _objc_protocol_list *const baseProtocols;
05325   //   const struct _ivar_list_t *const ivars;
05326   //   const uint8_t * const weakIvarLayout;
05327   //   const struct _prop_list_t * const properties;
05328   // }
05329 
05330   // FIXME. Add 'reserved' field in 64bit abi mode!
05331   ClassRonfABITy = llvm::StructType::create("struct._class_ro_t",
05332                                             IntTy, IntTy, IntTy, Int8PtrTy,
05333                                             Int8PtrTy, MethodListnfABIPtrTy,
05334                                             ProtocolListnfABIPtrTy,
05335                                             IvarListnfABIPtrTy,
05336                                             Int8PtrTy, PropertyListPtrTy,
05337                                             nullptr);
05338 
05339   // ImpnfABITy - LLVM for id (*)(id, SEL, ...)
05340   llvm::Type *params[] = { ObjectPtrTy, SelectorPtrTy };
05341   ImpnfABITy = llvm::FunctionType::get(ObjectPtrTy, params, false)
05342                  ->getPointerTo();
05343 
05344   // struct _class_t {
05345   //   struct _class_t *isa;
05346   //   struct _class_t * const superclass;
05347   //   void *cache;
05348   //   IMP *vtable;
05349   //   struct class_ro_t *ro;
05350   // }
05351 
05352   ClassnfABITy = llvm::StructType::create(VMContext, "struct._class_t");
05353   ClassnfABITy->setBody(llvm::PointerType::getUnqual(ClassnfABITy),
05354                         llvm::PointerType::getUnqual(ClassnfABITy),
05355                         CachePtrTy,
05356                         llvm::PointerType::getUnqual(ImpnfABITy),
05357                         llvm::PointerType::getUnqual(ClassRonfABITy),
05358                         nullptr);
05359 
05360   // LLVM for struct _class_t *
05361   ClassnfABIPtrTy = llvm::PointerType::getUnqual(ClassnfABITy);
05362 
05363   // struct _category_t {
05364   //   const char * const name;
05365   //   struct _class_t *const cls;
05366   //   const struct _method_list_t * const instance_methods;
05367   //   const struct _method_list_t * const class_methods;
05368   //   const struct _protocol_list_t * const protocols;
05369   //   const struct _prop_list_t * const properties;
05370   // }
05371   CategorynfABITy = llvm::StructType::create("struct._category_t",
05372                                              Int8PtrTy, ClassnfABIPtrTy,
05373                                              MethodListnfABIPtrTy,
05374                                              MethodListnfABIPtrTy,
05375                                              ProtocolListnfABIPtrTy,
05376                                              PropertyListPtrTy,
05377                                              nullptr);
05378 
05379   // New types for nonfragile abi messaging.
05380   CodeGen::CodeGenTypes &Types = CGM.getTypes();
05381   ASTContext &Ctx = CGM.getContext();
05382 
05383   // MessageRefTy - LLVM for:
05384   // struct _message_ref_t {
05385   //   IMP messenger;
05386   //   SEL name;
05387   // };
05388 
05389   // First the clang type for struct _message_ref_t
05390   RecordDecl *RD = RecordDecl::Create(Ctx, TTK_Struct,
05391                                       Ctx.getTranslationUnitDecl(),
05392                                       SourceLocation(), SourceLocation(),
05393                                       &Ctx.Idents.get("_message_ref_t"));
05394   RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
05395                                 nullptr, Ctx.VoidPtrTy, nullptr, nullptr, false,
05396                                 ICIS_NoInit));
05397   RD->addDecl(FieldDecl::Create(Ctx, RD, SourceLocation(), SourceLocation(),
05398                                 nullptr, Ctx.getObjCSelType(), nullptr, nullptr,
05399                                 false, ICIS_NoInit));
05400   RD->completeDefinition();
05401 
05402   MessageRefCTy = Ctx.getTagDeclType(RD);
05403   MessageRefCPtrTy = Ctx.getPointerType(MessageRefCTy);
05404   MessageRefTy = cast<llvm::StructType>(Types.ConvertType(MessageRefCTy));
05405 
05406   // MessageRefPtrTy - LLVM for struct _message_ref_t*
05407   MessageRefPtrTy = llvm::PointerType::getUnqual(MessageRefTy);
05408 
05409   // SuperMessageRefTy - LLVM for:
05410   // struct _super_message_ref_t {
05411   //   SUPER_IMP messenger;
05412   //   SEL name;
05413   // };
05414   SuperMessageRefTy =
05415     llvm::StructType::create("struct._super_message_ref_t",
05416                              ImpnfABITy, SelectorPtrTy, nullptr);
05417 
05418   // SuperMessageRefPtrTy - LLVM for struct _super_message_ref_t*
05419   SuperMessageRefPtrTy = llvm::PointerType::getUnqual(SuperMessageRefTy);
05420     
05421 
05422   // struct objc_typeinfo {
05423   //   const void** vtable; // objc_ehtype_vtable + 2
05424   //   const char*  name;    // c++ typeinfo string
05425   //   Class        cls;
05426   // };
05427   EHTypeTy =
05428     llvm::StructType::create("struct._objc_typeinfo",
05429                              llvm::PointerType::getUnqual(Int8PtrTy),
05430                              Int8PtrTy, ClassnfABIPtrTy, nullptr);
05431   EHTypePtrTy = llvm::PointerType::getUnqual(EHTypeTy);
05432 }
05433 
05434 llvm::Function *CGObjCNonFragileABIMac::ModuleInitFunction() {
05435   FinishNonFragileABIModule();
05436 
05437   return nullptr;
05438 }
05439 
05440 void CGObjCNonFragileABIMac::
05441 AddModuleClassList(ArrayRef<llvm::GlobalValue*> Container,
05442                    const char *SymbolName,
05443                    const char *SectionName) {
05444   unsigned NumClasses = Container.size();
05445 
05446   if (!NumClasses)
05447     return;
05448 
05449   SmallVector<llvm::Constant*, 8> Symbols(NumClasses);
05450   for (unsigned i=0; i<NumClasses; i++)
05451     Symbols[i] = llvm::ConstantExpr::getBitCast(Container[i],
05452                                                 ObjCTypes.Int8PtrTy);
05453   llvm::Constant *Init =
05454     llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
05455                                                   Symbols.size()),
05456                              Symbols);
05457 
05458   llvm::GlobalVariable *GV =
05459     new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
05460                              llvm::GlobalValue::PrivateLinkage,
05461                              Init,
05462                              SymbolName);
05463   GV->setAlignment(CGM.getDataLayout().getABITypeAlignment(Init->getType()));
05464   GV->setSection(SectionName);
05465   CGM.addCompilerUsedGlobal(GV);
05466 }
05467 
05468 void CGObjCNonFragileABIMac::FinishNonFragileABIModule() {
05469   // nonfragile abi has no module definition.
05470 
05471   // Build list of all implemented class addresses in array
05472   // L_OBJC_LABEL_CLASS_$.
05473 
05474   for (unsigned i=0, NumClasses=ImplementedClasses.size(); i<NumClasses; i++) {
05475     const ObjCInterfaceDecl *ID = ImplementedClasses[i];
05476     assert(ID);
05477     if (ObjCImplementationDecl *IMP = ID->getImplementation())
05478       // We are implementing a weak imported interface. Give it external linkage
05479       if (ID->isWeakImported() && !IMP->isWeakImported()) {
05480         DefinedClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
05481         DefinedMetaClasses[i]->setLinkage(llvm::GlobalVariable::ExternalLinkage);
05482       }
05483   }
05484 
05485   AddModuleClassList(DefinedClasses, "OBJC_LABEL_CLASS_$",
05486                      "__DATA, __objc_classlist, regular, no_dead_strip");
05487 
05488   AddModuleClassList(DefinedNonLazyClasses, "OBJC_LABEL_NONLAZY_CLASS_$",
05489                      "__DATA, __objc_nlclslist, regular, no_dead_strip");
05490 
05491   // Build list of all implemented category addresses in array
05492   // L_OBJC_LABEL_CATEGORY_$.
05493   AddModuleClassList(DefinedCategories, "OBJC_LABEL_CATEGORY_$",
05494                      "__DATA, __objc_catlist, regular, no_dead_strip");
05495   AddModuleClassList(DefinedNonLazyCategories, "OBJC_LABEL_NONLAZY_CATEGORY_$",
05496                      "__DATA, __objc_nlcatlist, regular, no_dead_strip");
05497 
05498   EmitImageInfo();
05499 }
05500 
05501 /// isVTableDispatchedSelector - Returns true if SEL is not in the list of
05502 /// VTableDispatchMethods; false otherwise. What this means is that
05503 /// except for the 19 selectors in the list, we generate 32bit-style
05504 /// message dispatch call for all the rest.
05505 bool CGObjCNonFragileABIMac::isVTableDispatchedSelector(Selector Sel) {
05506   // At various points we've experimented with using vtable-based
05507   // dispatch for all methods.
05508   switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
05509   case CodeGenOptions::Legacy:
05510     return false;
05511   case CodeGenOptions::NonLegacy:
05512     return true;
05513   case CodeGenOptions::Mixed:
05514     break;
05515   }
05516 
05517   // If so, see whether this selector is in the white-list of things which must
05518   // use the new dispatch convention. We lazily build a dense set for this.
05519   if (VTableDispatchMethods.empty()) {
05520     VTableDispatchMethods.insert(GetNullarySelector("alloc"));
05521     VTableDispatchMethods.insert(GetNullarySelector("class"));
05522     VTableDispatchMethods.insert(GetNullarySelector("self"));
05523     VTableDispatchMethods.insert(GetNullarySelector("isFlipped"));
05524     VTableDispatchMethods.insert(GetNullarySelector("length"));
05525     VTableDispatchMethods.insert(GetNullarySelector("count"));
05526 
05527     // These are vtable-based if GC is disabled.
05528     // Optimistically use vtable dispatch for hybrid compiles.
05529     if (CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
05530       VTableDispatchMethods.insert(GetNullarySelector("retain"));
05531       VTableDispatchMethods.insert(GetNullarySelector("release"));
05532       VTableDispatchMethods.insert(GetNullarySelector("autorelease"));
05533     }
05534 
05535     VTableDispatchMethods.insert(GetUnarySelector("allocWithZone"));
05536     VTableDispatchMethods.insert(GetUnarySelector("isKindOfClass"));
05537     VTableDispatchMethods.insert(GetUnarySelector("respondsToSelector"));
05538     VTableDispatchMethods.insert(GetUnarySelector("objectForKey"));
05539     VTableDispatchMethods.insert(GetUnarySelector("objectAtIndex"));
05540     VTableDispatchMethods.insert(GetUnarySelector("isEqualToString"));
05541     VTableDispatchMethods.insert(GetUnarySelector("isEqual"));
05542 
05543     // These are vtable-based if GC is enabled.
05544     // Optimistically use vtable dispatch for hybrid compiles.
05545     if (CGM.getLangOpts().getGC() != LangOptions::NonGC) {
05546       VTableDispatchMethods.insert(GetNullarySelector("hash"));
05547       VTableDispatchMethods.insert(GetUnarySelector("addObject"));
05548     
05549       // "countByEnumeratingWithState:objects:count"
05550       IdentifierInfo *KeyIdents[] = {
05551         &CGM.getContext().Idents.get("countByEnumeratingWithState"),
05552         &CGM.getContext().Idents.get("objects"),
05553         &CGM.getContext().Idents.get("count")
05554       };
05555       VTableDispatchMethods.insert(
05556         CGM.getContext().Selectors.getSelector(3, KeyIdents));
05557     }
05558   }
05559 
05560   return VTableDispatchMethods.count(Sel);
05561 }
05562 
05563 /// BuildClassRoTInitializer - generate meta-data for:
05564 /// struct _class_ro_t {
05565 ///   uint32_t const flags;
05566 ///   uint32_t const instanceStart;
05567 ///   uint32_t const instanceSize;
05568 ///   uint32_t const reserved;  // only when building for 64bit targets
05569 ///   const uint8_t * const ivarLayout;
05570 ///   const char *const name;
05571 ///   const struct _method_list_t * const baseMethods;
05572 ///   const struct _protocol_list_t *const baseProtocols;
05573 ///   const struct _ivar_list_t *const ivars;
05574 ///   const uint8_t * const weakIvarLayout;
05575 ///   const struct _prop_list_t * const properties;
05576 /// }
05577 ///
05578 llvm::GlobalVariable * CGObjCNonFragileABIMac::BuildClassRoTInitializer(
05579   unsigned flags,
05580   unsigned InstanceStart,
05581   unsigned InstanceSize,
05582   const ObjCImplementationDecl *ID) {
05583   std::string ClassName = ID->getObjCRuntimeNameAsString();
05584   llvm::Constant *Values[10]; // 11 for 64bit targets!
05585 
05586   if (CGM.getLangOpts().ObjCAutoRefCount)
05587     flags |= NonFragileABI_Class_CompiledByARC;
05588 
05589   Values[ 0] = llvm::ConstantInt::get(ObjCTypes.IntTy, flags);
05590   Values[ 1] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceStart);
05591   Values[ 2] = llvm::ConstantInt::get(ObjCTypes.IntTy, InstanceSize);
05592   // FIXME. For 64bit targets add 0 here.
05593   Values[ 3] = (flags & NonFragileABI_Class_Meta)
05594     ? GetIvarLayoutName(nullptr, ObjCTypes)
05595     : BuildIvarLayout(ID, true);
05596   Values[ 4] = GetClassName(ID->getObjCRuntimeNameAsString());
05597   // const struct _method_list_t * const baseMethods;
05598   std::vector<llvm::Constant*> Methods;
05599   std::string MethodListName("\01l_OBJC_$_");
05600   if (flags & NonFragileABI_Class_Meta) {
05601     MethodListName += "CLASS_METHODS_";
05602     MethodListName += ID->getObjCRuntimeNameAsString();
05603     for (const auto *I : ID->class_methods())
05604       // Class methods should always be defined.
05605       Methods.push_back(GetMethodConstant(I));
05606   } else {
05607     MethodListName += "INSTANCE_METHODS_";
05608     MethodListName += ID->getObjCRuntimeNameAsString();
05609     for (const auto *I : ID->instance_methods())
05610       // Instance methods should always be defined.
05611       Methods.push_back(GetMethodConstant(I));
05612 
05613     for (const auto *PID : ID->property_impls()) {
05614       if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize){
05615         ObjCPropertyDecl *PD = PID->getPropertyDecl();
05616 
05617         if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
05618           if (llvm::Constant *C = GetMethodConstant(MD))
05619             Methods.push_back(C);
05620         if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
05621           if (llvm::Constant *C = GetMethodConstant(MD))
05622             Methods.push_back(C);
05623       }
05624     }
05625   }
05626   Values[ 5] = EmitMethodList(MethodListName,
05627                               "__DATA, __objc_const", Methods);
05628 
05629   const ObjCInterfaceDecl *OID = ID->getClassInterface();
05630   assert(OID && "CGObjCNonFragileABIMac::BuildClassRoTInitializer");
05631   Values[ 6] = EmitProtocolList("\01l_OBJC_CLASS_PROTOCOLS_$_"
05632                                 + OID->getObjCRuntimeNameAsString(),
05633                                 OID->all_referenced_protocol_begin(),
05634                                 OID->all_referenced_protocol_end());
05635 
05636   if (flags & NonFragileABI_Class_Meta) {
05637     Values[ 7] = llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
05638     Values[ 8] = GetIvarLayoutName(nullptr, ObjCTypes);
05639     Values[ 9] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
05640   } else {
05641     Values[ 7] = EmitIvarList(ID);
05642     Values[ 8] = BuildIvarLayout(ID, false);
05643     Values[ 9] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ID->getObjCRuntimeNameAsString(),
05644                                   ID, ID->getClassInterface(), ObjCTypes);
05645   }
05646   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassRonfABITy,
05647                                                    Values);
05648   llvm::GlobalVariable *CLASS_RO_GV =
05649     new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassRonfABITy, false,
05650                              llvm::GlobalValue::PrivateLinkage,
05651                              Init,
05652                              (flags & NonFragileABI_Class_Meta) ?
05653                              std::string("\01l_OBJC_METACLASS_RO_$_")+ClassName :
05654                              std::string("\01l_OBJC_CLASS_RO_$_")+ClassName);
05655   CLASS_RO_GV->setAlignment(
05656     CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ClassRonfABITy));
05657   CLASS_RO_GV->setSection("__DATA, __objc_const");
05658   return CLASS_RO_GV;
05659 
05660 }
05661 
05662 /// BuildClassMetaData - This routine defines that to-level meta-data
05663 /// for the given ClassName for:
05664 /// struct _class_t {
05665 ///   struct _class_t *isa;
05666 ///   struct _class_t * const superclass;
05667 ///   void *cache;
05668 ///   IMP *vtable;
05669 ///   struct class_ro_t *ro;
05670 /// }
05671 ///
05672 llvm::GlobalVariable *CGObjCNonFragileABIMac::BuildClassMetaData(
05673     const std::string &ClassName, llvm::Constant *IsAGV, llvm::Constant *SuperClassGV,
05674     llvm::Constant *ClassRoGV, bool HiddenVisibility, bool Weak) {
05675   llvm::Constant *Values[] = {
05676     IsAGV,
05677     SuperClassGV,
05678     ObjCEmptyCacheVar,  // &ObjCEmptyCacheVar
05679     ObjCEmptyVtableVar, // &ObjCEmptyVtableVar
05680     ClassRoGV           // &CLASS_RO_GV
05681   };
05682   if (!Values[1])
05683     Values[1] = llvm::Constant::getNullValue(ObjCTypes.ClassnfABIPtrTy);
05684   if (!Values[3])
05685     Values[3] = llvm::Constant::getNullValue(
05686                   llvm::PointerType::getUnqual(ObjCTypes.ImpnfABITy));
05687   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassnfABITy,
05688                                                    Values);
05689   llvm::GlobalVariable *GV = GetClassGlobal(ClassName, Weak);
05690   GV->setInitializer(Init);
05691   GV->setSection("__DATA, __objc_data");
05692   GV->setAlignment(
05693     CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ClassnfABITy));
05694   if (HiddenVisibility)
05695     GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
05696   return GV;
05697 }
05698 
05699 bool
05700 CGObjCNonFragileABIMac::ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
05701   return OD->getClassMethod(GetNullarySelector("load")) != nullptr;
05702 }
05703 
05704 void CGObjCNonFragileABIMac::GetClassSizeInfo(const ObjCImplementationDecl *OID,
05705                                               uint32_t &InstanceStart,
05706                                               uint32_t &InstanceSize) {
05707   const ASTRecordLayout &RL =
05708     CGM.getContext().getASTObjCImplementationLayout(OID);
05709 
05710   // InstanceSize is really instance end.
05711   InstanceSize = RL.getDataSize().getQuantity();
05712 
05713   // If there are no fields, the start is the same as the end.
05714   if (!RL.getFieldCount())
05715     InstanceStart = InstanceSize;
05716   else
05717     InstanceStart = RL.getFieldOffset(0) / CGM.getContext().getCharWidth();
05718 }
05719 
05720 void CGObjCNonFragileABIMac::GenerateClass(const ObjCImplementationDecl *ID) {
05721   std::string ClassName = ID->getObjCRuntimeNameAsString();
05722   if (!ObjCEmptyCacheVar) {
05723     ObjCEmptyCacheVar = new llvm::GlobalVariable(
05724       CGM.getModule(),
05725       ObjCTypes.CacheTy,
05726       false,
05727       llvm::GlobalValue::ExternalLinkage,
05728       nullptr,
05729       "_objc_empty_cache");
05730 
05731     // Make this entry NULL for any iOS device target, any iOS simulator target,
05732     // OS X with deployment target 10.9 or later.
05733     const llvm::Triple &Triple = CGM.getTarget().getTriple();
05734     if (Triple.isiOS() || (Triple.isMacOSX() && !Triple.isMacOSXVersionLT(10, 9)))
05735       // This entry will be null.
05736       ObjCEmptyVtableVar = nullptr;
05737     else
05738       ObjCEmptyVtableVar = new llvm::GlobalVariable(
05739                                                     CGM.getModule(),
05740                                                     ObjCTypes.ImpnfABITy,
05741                                                     false,
05742                                                     llvm::GlobalValue::ExternalLinkage,
05743                                                     nullptr,
05744                                                     "_objc_empty_vtable");
05745   }
05746   assert(ID->getClassInterface() &&
05747          "CGObjCNonFragileABIMac::GenerateClass - class is 0");
05748   // FIXME: Is this correct (that meta class size is never computed)?
05749   uint32_t InstanceStart =
05750     CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ClassnfABITy);
05751   uint32_t InstanceSize = InstanceStart;
05752   uint32_t flags = NonFragileABI_Class_Meta;
05753   llvm::SmallString<64> ObjCMetaClassName(getMetaclassSymbolPrefix());
05754   llvm::SmallString<64> ObjCClassName(getClassSymbolPrefix());
05755   llvm::SmallString<64> TClassName;
05756 
05757   llvm::GlobalVariable *SuperClassGV, *IsAGV;
05758 
05759   // Build the flags for the metaclass.
05760   bool classIsHidden =
05761     ID->getClassInterface()->getVisibility() == HiddenVisibility;
05762   if (classIsHidden)
05763     flags |= NonFragileABI_Class_Hidden;
05764 
05765   // FIXME: why is this flag set on the metaclass?
05766   // ObjC metaclasses have no fields and don't really get constructed.
05767   if (ID->hasNonZeroConstructors() || ID->hasDestructors()) {
05768     flags |= NonFragileABI_Class_HasCXXStructors;
05769     if (!ID->hasNonZeroConstructors())
05770       flags |= NonFragileABI_Class_HasCXXDestructorOnly;  
05771   }
05772 
05773   if (!ID->getClassInterface()->getSuperClass()) {
05774     // class is root
05775     flags |= NonFragileABI_Class_Root;
05776     TClassName = ObjCClassName;
05777     TClassName += ClassName;
05778     SuperClassGV = GetClassGlobal(TClassName.str(),
05779                                   ID->getClassInterface()->isWeakImported());
05780     TClassName = ObjCMetaClassName;
05781     TClassName += ClassName;
05782     IsAGV = GetClassGlobal(TClassName.str(),
05783                            ID->getClassInterface()->isWeakImported());
05784   } else {
05785     // Has a root. Current class is not a root.
05786     const ObjCInterfaceDecl *Root = ID->getClassInterface();
05787     while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
05788       Root = Super;
05789     TClassName = ObjCMetaClassName ;
05790     TClassName += Root->getObjCRuntimeNameAsString();
05791     IsAGV = GetClassGlobal(TClassName.str(),
05792                            Root->isWeakImported());
05793 
05794     // work on super class metadata symbol.
05795     TClassName = ObjCMetaClassName;
05796     TClassName += ID->getClassInterface()->getSuperClass()->getObjCRuntimeNameAsString();
05797     SuperClassGV = GetClassGlobal(
05798                                   TClassName.str(),
05799                                   ID->getClassInterface()->getSuperClass()->isWeakImported());
05800   }
05801   llvm::GlobalVariable *CLASS_RO_GV = BuildClassRoTInitializer(flags,
05802                                                                InstanceStart,
05803                                                                InstanceSize,ID);
05804   TClassName = ObjCMetaClassName;
05805   TClassName += ClassName;
05806   llvm::GlobalVariable *MetaTClass = BuildClassMetaData(
05807       TClassName.str(), IsAGV, SuperClassGV, CLASS_RO_GV, classIsHidden,
05808       ID->getClassInterface()->isWeakImported());
05809   DefinedMetaClasses.push_back(MetaTClass);
05810 
05811   // Metadata for the class
05812   flags = 0;
05813   if (classIsHidden)
05814     flags |= NonFragileABI_Class_Hidden;
05815 
05816   if (ID->hasNonZeroConstructors() || ID->hasDestructors()) {
05817     flags |= NonFragileABI_Class_HasCXXStructors;
05818 
05819     // Set a flag to enable a runtime optimization when a class has
05820     // fields that require destruction but which don't require
05821     // anything except zero-initialization during construction.  This
05822     // is most notably true of __strong and __weak types, but you can
05823     // also imagine there being C++ types with non-trivial default
05824     // constructors that merely set all fields to null.
05825     if (!ID->hasNonZeroConstructors())
05826       flags |= NonFragileABI_Class_HasCXXDestructorOnly;
05827   }
05828 
05829   if (hasObjCExceptionAttribute(CGM.getContext(), ID->getClassInterface()))
05830     flags |= NonFragileABI_Class_Exception;
05831 
05832   if (!ID->getClassInterface()->getSuperClass()) {
05833     flags |= NonFragileABI_Class_Root;
05834     SuperClassGV = nullptr;
05835   } else {
05836     // Has a root. Current class is not a root.
05837     TClassName = ObjCClassName;
05838     TClassName += ID->getClassInterface()->getSuperClass()->getObjCRuntimeNameAsString();
05839     SuperClassGV = GetClassGlobal(
05840                                   TClassName.str(),
05841                                   ID->getClassInterface()->getSuperClass()->isWeakImported());
05842   }
05843   GetClassSizeInfo(ID, InstanceStart, InstanceSize);
05844   CLASS_RO_GV = BuildClassRoTInitializer(flags,
05845                                          InstanceStart,
05846                                          InstanceSize,
05847                                          ID);
05848 
05849   TClassName = ObjCClassName;
05850   TClassName += ClassName;
05851   llvm::GlobalVariable *ClassMD =
05852     BuildClassMetaData(TClassName.str(), MetaTClass, SuperClassGV, CLASS_RO_GV,
05853                        classIsHidden,
05854                        ID->getClassInterface()->isWeakImported());
05855   DefinedClasses.push_back(ClassMD);
05856   ImplementedClasses.push_back(ID->getClassInterface());
05857 
05858   // Determine if this class is also "non-lazy".
05859   if (ImplementationIsNonLazy(ID))
05860     DefinedNonLazyClasses.push_back(ClassMD);
05861 
05862   // Force the definition of the EHType if necessary.
05863   if (flags & NonFragileABI_Class_Exception)
05864     GetInterfaceEHType(ID->getClassInterface(), true);
05865   // Make sure method definition entries are all clear for next implementation.
05866   MethodDefinitions.clear();
05867 }
05868 
05869 /// GenerateProtocolRef - This routine is called to generate code for
05870 /// a protocol reference expression; as in:
05871 /// @code
05872 ///   @protocol(Proto1);
05873 /// @endcode
05874 /// It generates a weak reference to l_OBJC_PROTOCOL_REFERENCE_$_Proto1
05875 /// which will hold address of the protocol meta-data.
05876 ///
05877 llvm::Value *CGObjCNonFragileABIMac::GenerateProtocolRef(CodeGenFunction &CGF,
05878                                                          const ObjCProtocolDecl *PD) {
05879 
05880   // This routine is called for @protocol only. So, we must build definition
05881   // of protocol's meta-data (not a reference to it!)
05882   //
05883   llvm::Constant *Init =
05884     llvm::ConstantExpr::getBitCast(GetOrEmitProtocol(PD),
05885                                    ObjCTypes.getExternalProtocolPtrTy());
05886 
05887   std::string ProtocolName("\01l_OBJC_PROTOCOL_REFERENCE_$_");
05888   ProtocolName += PD->getObjCRuntimeNameAsString();
05889 
05890   llvm::GlobalVariable *PTGV = CGM.getModule().getGlobalVariable(ProtocolName);
05891   if (PTGV)
05892     return CGF.Builder.CreateLoad(PTGV);
05893   PTGV = new llvm::GlobalVariable(
05894     CGM.getModule(),
05895     Init->getType(), false,
05896     llvm::GlobalValue::WeakAnyLinkage,
05897     Init,
05898     ProtocolName);
05899   PTGV->setSection("__DATA, __objc_protorefs, coalesced, no_dead_strip");
05900   PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
05901   CGM.addCompilerUsedGlobal(PTGV);
05902   return CGF.Builder.CreateLoad(PTGV);
05903 }
05904 
05905 /// GenerateCategory - Build metadata for a category implementation.
05906 /// struct _category_t {
05907 ///   const char * const name;
05908 ///   struct _class_t *const cls;
05909 ///   const struct _method_list_t * const instance_methods;
05910 ///   const struct _method_list_t * const class_methods;
05911 ///   const struct _protocol_list_t * const protocols;
05912 ///   const struct _prop_list_t * const properties;
05913 /// }
05914 ///
05915 void CGObjCNonFragileABIMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
05916   const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
05917   const char *Prefix = "\01l_OBJC_$_CATEGORY_";
05918     
05919   llvm::SmallString<64> ExtCatName(Prefix);
05920   ExtCatName += Interface->getObjCRuntimeNameAsString();
05921   ExtCatName += "_$_";
05922   ExtCatName += OCD->getNameAsString();
05923     
05924   llvm::SmallString<64> ExtClassName(getClassSymbolPrefix());
05925   ExtClassName += Interface->getObjCRuntimeNameAsString();
05926 
05927   llvm::Constant *Values[6];
05928   Values[0] = GetClassName(OCD->getIdentifier()->getName());
05929   // meta-class entry symbol
05930   llvm::GlobalVariable *ClassGV =
05931       GetClassGlobal(ExtClassName.str(), Interface->isWeakImported());
05932 
05933   Values[1] = ClassGV;
05934   std::vector<llvm::Constant*> Methods;
05935   llvm::SmallString<64> MethodListName(Prefix);
05936     
05937   MethodListName += "INSTANCE_METHODS_";
05938   MethodListName += Interface->getObjCRuntimeNameAsString();
05939   MethodListName += "_$_";
05940   MethodListName += OCD->getName();
05941 
05942   for (const auto *I : OCD->instance_methods())
05943     // Instance methods should always be defined.
05944     Methods.push_back(GetMethodConstant(I));
05945 
05946   Values[2] = EmitMethodList(MethodListName.str(),
05947                              "__DATA, __objc_const",
05948                              Methods);
05949 
05950   MethodListName = Prefix;
05951   MethodListName += "CLASS_METHODS_";
05952   MethodListName += Interface->getObjCRuntimeNameAsString();
05953   MethodListName += "_$_";
05954   MethodListName += OCD->getNameAsString();
05955     
05956   Methods.clear();
05957   for (const auto *I : OCD->class_methods())
05958     // Class methods should always be defined.
05959     Methods.push_back(GetMethodConstant(I));
05960 
05961   Values[3] = EmitMethodList(MethodListName.str(),
05962                              "__DATA, __objc_const",
05963                              Methods);
05964   const ObjCCategoryDecl *Category =
05965     Interface->FindCategoryDeclaration(OCD->getIdentifier());
05966   if (Category) {
05967     SmallString<256> ExtName;
05968     llvm::raw_svector_ostream(ExtName) << Interface->getObjCRuntimeNameAsString() << "_$_"
05969                                        << OCD->getName();
05970     Values[4] = EmitProtocolList("\01l_OBJC_CATEGORY_PROTOCOLS_$_"
05971                                    + Interface->getObjCRuntimeNameAsString() + "_$_"
05972                                    + Category->getName(),
05973                                    Category->protocol_begin(),
05974                                    Category->protocol_end());
05975     Values[5] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + ExtName.str(),
05976                                  OCD, Category, ObjCTypes);
05977   } else {
05978     Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
05979     Values[5] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
05980   }
05981 
05982   llvm::Constant *Init =
05983     llvm::ConstantStruct::get(ObjCTypes.CategorynfABITy,
05984                               Values);
05985   llvm::GlobalVariable *GCATV
05986     = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.CategorynfABITy,
05987                                false,
05988                                llvm::GlobalValue::PrivateLinkage,
05989                                Init,
05990                                ExtCatName.str());
05991   GCATV->setAlignment(
05992     CGM.getDataLayout().getABITypeAlignment(ObjCTypes.CategorynfABITy));
05993   GCATV->setSection("__DATA, __objc_const");
05994   CGM.addCompilerUsedGlobal(GCATV);
05995   DefinedCategories.push_back(GCATV);
05996 
05997   // Determine if this category is also "non-lazy".
05998   if (ImplementationIsNonLazy(OCD))
05999     DefinedNonLazyCategories.push_back(GCATV);
06000   // method definition entries must be clear for next implementation.
06001   MethodDefinitions.clear();
06002 }
06003 
06004 /// GetMethodConstant - Return a struct objc_method constant for the
06005 /// given method if it has been defined. The result is null if the
06006 /// method has not been defined. The return value has type MethodPtrTy.
06007 llvm::Constant *CGObjCNonFragileABIMac::GetMethodConstant(
06008   const ObjCMethodDecl *MD) {
06009   llvm::Function *Fn = GetMethodDefinition(MD);
06010   if (!Fn)
06011     return nullptr;
06012 
06013   llvm::Constant *Method[] = {
06014     llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
06015                                    ObjCTypes.SelectorPtrTy),
06016     GetMethodVarType(MD),
06017     llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy)
06018   };
06019   return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
06020 }
06021 
06022 /// EmitMethodList - Build meta-data for method declarations
06023 /// struct _method_list_t {
06024 ///   uint32_t entsize;  // sizeof(struct _objc_method)
06025 ///   uint32_t method_count;
06026 ///   struct _objc_method method_list[method_count];
06027 /// }
06028 ///
06029 llvm::Constant *
06030 CGObjCNonFragileABIMac::EmitMethodList(Twine Name,
06031                                        const char *Section,
06032                                        ArrayRef<llvm::Constant*> Methods) {
06033   // Return null for empty list.
06034   if (Methods.empty())
06035     return llvm::Constant::getNullValue(ObjCTypes.MethodListnfABIPtrTy);
06036 
06037   llvm::Constant *Values[3];
06038   // sizeof(struct _objc_method)
06039   unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.MethodTy);
06040   Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
06041   // method_count
06042   Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
06043   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
06044                                              Methods.size());
06045   Values[2] = llvm::ConstantArray::get(AT, Methods);
06046   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
06047 
06048   llvm::GlobalVariable *GV =
06049     new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
06050                              llvm::GlobalValue::PrivateLinkage, Init, Name);
06051   GV->setAlignment(CGM.getDataLayout().getABITypeAlignment(Init->getType()));
06052   GV->setSection(Section);
06053   CGM.addCompilerUsedGlobal(GV);
06054   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.MethodListnfABIPtrTy);
06055 }
06056 
06057 /// ObjCIvarOffsetVariable - Returns the ivar offset variable for
06058 /// the given ivar.
06059 llvm::GlobalVariable *
06060 CGObjCNonFragileABIMac::ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
06061                                                const ObjCIvarDecl *Ivar) {
06062     
06063   const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();
06064   llvm::SmallString<64> Name("OBJC_IVAR_$_");
06065   Name += Container->getObjCRuntimeNameAsString();
06066   Name += ".";
06067   Name += Ivar->getName();
06068   llvm::GlobalVariable *IvarOffsetGV =
06069     CGM.getModule().getGlobalVariable(Name);
06070   if (!IvarOffsetGV)
06071     IvarOffsetGV = new llvm::GlobalVariable(
06072       CGM.getModule(), ObjCTypes.IvarOffsetVarTy, false,
06073       llvm::GlobalValue::ExternalLinkage, nullptr, Name.str());
06074   return IvarOffsetGV;
06075 }
06076 
06077 llvm::Constant *
06078 CGObjCNonFragileABIMac::EmitIvarOffsetVar(const ObjCInterfaceDecl *ID,
06079                                           const ObjCIvarDecl *Ivar,
06080                                           unsigned long int Offset) {
06081   llvm::GlobalVariable *IvarOffsetGV = ObjCIvarOffsetVariable(ID, Ivar);
06082   IvarOffsetGV->setInitializer(
06083       llvm::ConstantInt::get(ObjCTypes.IvarOffsetVarTy, Offset));
06084   IvarOffsetGV->setAlignment(
06085       CGM.getDataLayout().getABITypeAlignment(ObjCTypes.IvarOffsetVarTy));
06086 
06087   // FIXME: This matches gcc, but shouldn't the visibility be set on the use as
06088   // well (i.e., in ObjCIvarOffsetVariable).
06089   if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
06090       Ivar->getAccessControl() == ObjCIvarDecl::Package ||
06091       ID->getVisibility() == HiddenVisibility)
06092     IvarOffsetGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
06093   else
06094     IvarOffsetGV->setVisibility(llvm::GlobalValue::DefaultVisibility);
06095   IvarOffsetGV->setSection("__DATA, __objc_ivar");
06096   return IvarOffsetGV;
06097 }
06098 
06099 /// EmitIvarList - Emit the ivar list for the given
06100 /// implementation. The return value has type
06101 /// IvarListnfABIPtrTy.
06102 ///  struct _ivar_t {
06103 ///   unsigned [long] int *offset;  // pointer to ivar offset location
06104 ///   char *name;
06105 ///   char *type;
06106 ///   uint32_t alignment;
06107 ///   uint32_t size;
06108 /// }
06109 /// struct _ivar_list_t {
06110 ///   uint32 entsize;  // sizeof(struct _ivar_t)
06111 ///   uint32 count;
06112 ///   struct _iver_t list[count];
06113 /// }
06114 ///
06115 
06116 llvm::Constant *CGObjCNonFragileABIMac::EmitIvarList(
06117   const ObjCImplementationDecl *ID) {
06118 
06119   std::vector<llvm::Constant*> Ivars;
06120 
06121   const ObjCInterfaceDecl *OID = ID->getClassInterface();
06122   assert(OID && "CGObjCNonFragileABIMac::EmitIvarList - null interface");
06123 
06124   // FIXME. Consolidate this with similar code in GenerateClass.
06125 
06126   for (const ObjCIvarDecl *IVD = OID->all_declared_ivar_begin(); 
06127        IVD; IVD = IVD->getNextIvar()) {
06128     // Ignore unnamed bit-fields.
06129     if (!IVD->getDeclName())
06130       continue;
06131     llvm::Constant *Ivar[5];
06132     Ivar[0] = EmitIvarOffsetVar(ID->getClassInterface(), IVD,
06133                                 ComputeIvarBaseOffset(CGM, ID, IVD));
06134     Ivar[1] = GetMethodVarName(IVD->getIdentifier());
06135     Ivar[2] = GetMethodVarType(IVD);
06136     llvm::Type *FieldTy =
06137       CGM.getTypes().ConvertTypeForMem(IVD->getType());
06138     unsigned Size = CGM.getDataLayout().getTypeAllocSize(FieldTy);
06139     unsigned Align = CGM.getContext().getPreferredTypeAlign(
06140       IVD->getType().getTypePtr()) >> 3;
06141     Align = llvm::Log2_32(Align);
06142     Ivar[3] = llvm::ConstantInt::get(ObjCTypes.IntTy, Align);
06143     // NOTE. Size of a bitfield does not match gcc's, because of the
06144     // way bitfields are treated special in each. But I am told that
06145     // 'size' for bitfield ivars is ignored by the runtime so it does
06146     // not matter.  If it matters, there is enough info to get the
06147     // bitfield right!
06148     Ivar[4] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
06149     Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarnfABITy, Ivar));
06150   }
06151   // Return null for empty list.
06152   if (Ivars.empty())
06153     return llvm::Constant::getNullValue(ObjCTypes.IvarListnfABIPtrTy);
06154 
06155   llvm::Constant *Values[3];
06156   unsigned Size = CGM.getDataLayout().getTypeAllocSize(ObjCTypes.IvarnfABITy);
06157   Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
06158   Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
06159   llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarnfABITy,
06160                                              Ivars.size());
06161   Values[2] = llvm::ConstantArray::get(AT, Ivars);
06162   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
06163   const char *Prefix = "\01l_OBJC_$_INSTANCE_VARIABLES_";
06164   llvm::GlobalVariable *GV =
06165     new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
06166                              llvm::GlobalValue::PrivateLinkage,
06167                              Init,
06168                              Prefix + OID->getObjCRuntimeNameAsString());
06169   GV->setAlignment(
06170     CGM.getDataLayout().getABITypeAlignment(Init->getType()));
06171   GV->setSection("__DATA, __objc_const");
06172 
06173   CGM.addCompilerUsedGlobal(GV);
06174   return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.IvarListnfABIPtrTy);
06175 }
06176 
06177 llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocolRef(
06178   const ObjCProtocolDecl *PD) {
06179   llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
06180 
06181   if (!Entry) {
06182     // We use the initializer as a marker of whether this is a forward
06183     // reference or not. At module finalization we add the empty
06184     // contents for protocols which were referenced but never defined.
06185     Entry =
06186         new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy,
06187                                  false, llvm::GlobalValue::ExternalLinkage,
06188                                  nullptr,
06189                                  "\01l_OBJC_PROTOCOL_$_" + PD->getObjCRuntimeNameAsString());
06190     Entry->setSection("__DATA,__datacoal_nt,coalesced");
06191   }
06192 
06193   return Entry;
06194 }
06195 
06196 /// GetOrEmitProtocol - Generate the protocol meta-data:
06197 /// @code
06198 /// struct _protocol_t {
06199 ///   id isa;  // NULL
06200 ///   const char * const protocol_name;
06201 ///   const struct _protocol_list_t * protocol_list; // super protocols
06202 ///   const struct method_list_t * const instance_methods;
06203 ///   const struct method_list_t * const class_methods;
06204 ///   const struct method_list_t *optionalInstanceMethods;
06205 ///   const struct method_list_t *optionalClassMethods;
06206 ///   const struct _prop_list_t * properties;
06207 ///   const uint32_t size;  // sizeof(struct _protocol_t)
06208 ///   const uint32_t flags;  // = 0
06209 ///   const char ** extendedMethodTypes;
06210 /// }
06211 /// @endcode
06212 ///
06213 
06214 llvm::Constant *CGObjCNonFragileABIMac::GetOrEmitProtocol(
06215   const ObjCProtocolDecl *PD) {
06216   llvm::GlobalVariable *Entry = Protocols[PD->getIdentifier()];
06217 
06218   // Early exit if a defining object has already been generated.
06219   if (Entry && Entry->hasInitializer())
06220     return Entry;
06221 
06222   // Use the protocol definition, if there is one.
06223   if (const ObjCProtocolDecl *Def = PD->getDefinition())
06224     PD = Def;
06225   
06226   // Construct method lists.
06227   std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
06228   std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
06229   std::vector<llvm::Constant*> MethodTypesExt, OptMethodTypesExt;
06230   for (const auto *MD : PD->instance_methods()) {
06231     llvm::Constant *C = GetMethodDescriptionConstant(MD);
06232     if (!C)
06233       return GetOrEmitProtocolRef(PD);
06234     
06235     if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
06236       OptInstanceMethods.push_back(C);
06237       OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
06238     } else {
06239       InstanceMethods.push_back(C);
06240       MethodTypesExt.push_back(GetMethodVarType(MD, true));
06241     }
06242   }
06243 
06244   for (const auto *MD : PD->class_methods()) {
06245     llvm::Constant *C = GetMethodDescriptionConstant(MD);
06246     if (!C)
06247       return GetOrEmitProtocolRef(PD);
06248 
06249     if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
06250       OptClassMethods.push_back(C);
06251       OptMethodTypesExt.push_back(GetMethodVarType(MD, true));
06252     } else {
06253       ClassMethods.push_back(C);
06254       MethodTypesExt.push_back(GetMethodVarType(MD, true));
06255     }
06256   }
06257 
06258   MethodTypesExt.insert(MethodTypesExt.end(),
06259                         OptMethodTypesExt.begin(), OptMethodTypesExt.end());
06260 
06261   llvm::Constant *Values[11];
06262   // isa is NULL
06263   Values[0] = llvm::Constant::getNullValue(ObjCTypes.ObjectPtrTy);
06264   Values[1] = GetClassName(PD->getObjCRuntimeNameAsString());
06265   Values[2] = EmitProtocolList("\01l_OBJC_$_PROTOCOL_REFS_" + PD->getObjCRuntimeNameAsString(),
06266                                PD->protocol_begin(),
06267                                PD->protocol_end());
06268 
06269   Values[3] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_"
06270                              + PD->getObjCRuntimeNameAsString(),
06271                              "__DATA, __objc_const",
06272                              InstanceMethods);
06273   Values[4] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_"
06274                              + PD->getObjCRuntimeNameAsString(),
06275                              "__DATA, __objc_const",
06276                              ClassMethods);
06277   Values[5] = EmitMethodList("\01l_OBJC_$_PROTOCOL_INSTANCE_METHODS_OPT_"
06278                              + PD->getObjCRuntimeNameAsString(),
06279                              "__DATA, __objc_const",
06280                              OptInstanceMethods);
06281   Values[6] = EmitMethodList("\01l_OBJC_$_PROTOCOL_CLASS_METHODS_OPT_"
06282                              + PD->getObjCRuntimeNameAsString(),
06283                              "__DATA, __objc_const",
06284                              OptClassMethods);
06285   Values[7] = EmitPropertyList("\01l_OBJC_$_PROP_LIST_" + PD->getObjCRuntimeNameAsString(),
06286                                nullptr, PD, ObjCTypes);
06287   uint32_t Size =
06288     CGM.getDataLayout().getTypeAllocSize(ObjCTypes.ProtocolnfABITy);
06289   Values[8] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
06290   Values[9] = llvm::Constant::getNullValue(ObjCTypes.IntTy);
06291   Values[10] = EmitProtocolMethodTypes("\01l_OBJC_$_PROTOCOL_METHOD_TYPES_"
06292                                        + PD->getObjCRuntimeNameAsString(),
06293                                        MethodTypesExt, ObjCTypes);
06294   llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolnfABITy,
06295                                                    Values);
06296 
06297   if (Entry) {
06298     // Already created, fix the linkage and update the initializer.
06299     Entry->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
06300     Entry->setInitializer(Init);
06301   } else {
06302     Entry =
06303       new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABITy,
06304                                false, llvm::GlobalValue::WeakAnyLinkage, Init,
06305                                "\01l_OBJC_PROTOCOL_$_" + PD->getObjCRuntimeNameAsString());
06306     Entry->setAlignment(
06307       CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ProtocolnfABITy));
06308     Entry->setSection("__DATA,__datacoal_nt,coalesced");
06309 
06310     Protocols[PD->getIdentifier()] = Entry;
06311   }
06312   Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
06313   CGM.addCompilerUsedGlobal(Entry);
06314 
06315   // Use this protocol meta-data to build protocol list table in section
06316   // __DATA, __objc_protolist
06317   llvm::GlobalVariable *PTGV =
06318     new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ProtocolnfABIPtrTy,
06319                              false, llvm::GlobalValue::WeakAnyLinkage, Entry,
06320                              "\01l_OBJC_LABEL_PROTOCOL_$_" + PD->getObjCRuntimeNameAsString());
06321   PTGV->setAlignment(
06322     CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ProtocolnfABIPtrTy));
06323   PTGV->setSection("__DATA, __objc_protolist, coalesced, no_dead_strip");
06324   PTGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
06325   CGM.addCompilerUsedGlobal(PTGV);
06326   return Entry;
06327 }
06328 
06329 /// EmitProtocolList - Generate protocol list meta-data:
06330 /// @code
06331 /// struct _protocol_list_t {
06332 ///   long protocol_count;   // Note, this is 32/64 bit
06333 ///   struct _protocol_t[protocol_count];
06334 /// }
06335 /// @endcode
06336 ///
06337 llvm::Constant *
06338 CGObjCNonFragileABIMac::EmitProtocolList(Twine Name,
06339                                       ObjCProtocolDecl::protocol_iterator begin,
06340                                       ObjCProtocolDecl::protocol_iterator end) {
06341   SmallVector<llvm::Constant *, 16> ProtocolRefs;
06342 
06343   // Just return null for empty protocol lists
06344   if (begin == end)
06345     return llvm::Constant::getNullValue(ObjCTypes.ProtocolListnfABIPtrTy);
06346 
06347   // FIXME: We shouldn't need to do this lookup here, should we?
06348   SmallString<256> TmpName;
06349   Name.toVector(TmpName);
06350   llvm::GlobalVariable *GV =
06351     CGM.getModule().getGlobalVariable(TmpName.str(), true);
06352   if (GV)
06353     return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListnfABIPtrTy);
06354 
06355   for (; begin != end; ++begin)
06356     ProtocolRefs.push_back(GetProtocolRef(*begin));  // Implemented???
06357 
06358   // This list is null terminated.
06359   ProtocolRefs.push_back(llvm::Constant::getNullValue(
06360                            ObjCTypes.ProtocolnfABIPtrTy));
06361 
06362   llvm::Constant *Values[2];
06363   Values[0] =
06364     llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
06365   Values[1] =
06366     llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolnfABIPtrTy,
06367                                                   ProtocolRefs.size()),
06368                              ProtocolRefs);
06369 
06370   llvm::Constant *Init = llvm::ConstantStruct::getAnon(Values);
06371   GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), false,
06372                                 llvm::GlobalValue::PrivateLinkage,
06373                                 Init, Name);
06374   GV->setSection("__DATA, __objc_const");
06375   GV->setAlignment(
06376     CGM.getDataLayout().getABITypeAlignment(Init->getType()));
06377   CGM.addCompilerUsedGlobal(GV);
06378   return llvm::ConstantExpr::getBitCast(GV,
06379                                         ObjCTypes.ProtocolListnfABIPtrTy);
06380 }
06381 
06382 /// GetMethodDescriptionConstant - This routine build following meta-data:
06383 /// struct _objc_method {
06384 ///   SEL _cmd;
06385 ///   char *method_type;
06386 ///   char *_imp;
06387 /// }
06388 
06389 llvm::Constant *
06390 CGObjCNonFragileABIMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
06391   llvm::Constant *Desc[3];
06392   Desc[0] =
06393     llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
06394                                    ObjCTypes.SelectorPtrTy);
06395   Desc[1] = GetMethodVarType(MD);
06396   if (!Desc[1])
06397     return nullptr;
06398 
06399   // Protocol methods have no implementation. So, this entry is always NULL.
06400   Desc[2] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
06401   return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Desc);
06402 }
06403 
06404 /// EmitObjCValueForIvar - Code Gen for nonfragile ivar reference.
06405 /// This code gen. amounts to generating code for:
06406 /// @code
06407 /// (type *)((char *)base + _OBJC_IVAR_$_.ivar;
06408 /// @encode
06409 ///
06410 LValue CGObjCNonFragileABIMac::EmitObjCValueForIvar(
06411                                                CodeGen::CodeGenFunction &CGF,
06412                                                QualType ObjectTy,
06413                                                llvm::Value *BaseValue,
06414                                                const ObjCIvarDecl *Ivar,
06415                                                unsigned CVRQualifiers) {
06416   ObjCInterfaceDecl *ID = ObjectTy->getAs<ObjCObjectType>()->getInterface();
06417   llvm::Value *Offset = EmitIvarOffset(CGF, ID, Ivar);
06418   return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
06419                                   Offset);
06420 }
06421 
06422 llvm::Value *CGObjCNonFragileABIMac::EmitIvarOffset(
06423   CodeGen::CodeGenFunction &CGF,
06424   const ObjCInterfaceDecl *Interface,
06425   const ObjCIvarDecl *Ivar) {
06426   llvm::Value *IvarOffsetValue = ObjCIvarOffsetVariable(Interface, Ivar);
06427   IvarOffsetValue = CGF.Builder.CreateLoad(IvarOffsetValue, "ivar");
06428   if (IsIvarOffsetKnownIdempotent(CGF, Ivar))
06429     cast<llvm::LoadInst>(IvarOffsetValue)
06430         ->setMetadata(CGM.getModule().getMDKindID("invariant.load"),
06431                       llvm::MDNode::get(VMContext, None));
06432 
06433   // This could be 32bit int or 64bit integer depending on the architecture.
06434   // Cast it to 64bit integer value, if it is a 32bit integer ivar offset value
06435   //  as this is what caller always expectes.
06436   if (ObjCTypes.IvarOffsetVarTy == ObjCTypes.IntTy)
06437     IvarOffsetValue = CGF.Builder.CreateIntCast(
06438         IvarOffsetValue, ObjCTypes.LongTy, true, "ivar.conv");
06439   return IvarOffsetValue;
06440 }
06441 
06442 static void appendSelectorForMessageRefTable(std::string &buffer,
06443                                              Selector selector) {
06444   if (selector.isUnarySelector()) {
06445     buffer += selector.getNameForSlot(0);
06446     return;
06447   }
06448 
06449   for (unsigned i = 0, e = selector.getNumArgs(); i != e; ++i) {
06450     buffer += selector.getNameForSlot(i);
06451     buffer += '_';
06452   }
06453 }
06454 
06455 /// Emit a "v-table" message send.  We emit a weak hidden-visibility
06456 /// struct, initially containing the selector pointer and a pointer to
06457 /// a "fixup" variant of the appropriate objc_msgSend.  To call, we
06458 /// load and call the function pointer, passing the address of the
06459 /// struct as the second parameter.  The runtime determines whether
06460 /// the selector is currently emitted using vtable dispatch; if so, it
06461 /// substitutes a stub function which simply tail-calls through the
06462 /// appropriate vtable slot, and if not, it substitues a stub function
06463 /// which tail-calls objc_msgSend.  Both stubs adjust the selector
06464 /// argument to correctly point to the selector.
06465 RValue
06466 CGObjCNonFragileABIMac::EmitVTableMessageSend(CodeGenFunction &CGF,
06467                                               ReturnValueSlot returnSlot,
06468                                               QualType resultType,
06469                                               Selector selector,
06470                                               llvm::Value *arg0,
06471                                               QualType arg0Type,
06472                                               bool isSuper,
06473                                               const CallArgList &formalArgs,
06474                                               const ObjCMethodDecl *method) {
06475   // Compute the actual arguments.
06476   CallArgList args;
06477 
06478   // First argument: the receiver / super-call structure.
06479   if (!isSuper)
06480     arg0 = CGF.Builder.CreateBitCast(arg0, ObjCTypes.ObjectPtrTy);
06481   args.add(RValue::get(arg0), arg0Type);
06482 
06483   // Second argument: a pointer to the message ref structure.  Leave
06484   // the actual argument value blank for now.
06485   args.add(RValue::get(nullptr), ObjCTypes.MessageRefCPtrTy);
06486 
06487   args.insert(args.end(), formalArgs.begin(), formalArgs.end());
06488 
06489   MessageSendInfo MSI = getMessageSendInfo(method, resultType, args);
06490 
06491   NullReturnState nullReturn;
06492 
06493   // Find the function to call and the mangled name for the message
06494   // ref structure.  Using a different mangled name wouldn't actually
06495   // be a problem; it would just be a waste.
06496   //
06497   // The runtime currently never uses vtable dispatch for anything
06498   // except normal, non-super message-sends.
06499   // FIXME: don't use this for that.
06500   llvm::Constant *fn = nullptr;
06501   std::string messageRefName("\01l_");
06502   if (CGM.ReturnSlotInterferesWithArgs(MSI.CallInfo)) {
06503     if (isSuper) {
06504       fn = ObjCTypes.getMessageSendSuper2StretFixupFn();
06505       messageRefName += "objc_msgSendSuper2_stret_fixup";
06506     } else {
06507       nullReturn.init(CGF, arg0);
06508       fn = ObjCTypes.getMessageSendStretFixupFn();
06509       messageRefName += "objc_msgSend_stret_fixup";
06510     }
06511   } else if (!isSuper && CGM.ReturnTypeUsesFPRet(resultType)) {
06512     fn = ObjCTypes.getMessageSendFpretFixupFn();
06513     messageRefName += "objc_msgSend_fpret_fixup";
06514   } else {
06515     if (isSuper) {
06516       fn = ObjCTypes.getMessageSendSuper2FixupFn();
06517       messageRefName += "objc_msgSendSuper2_fixup";
06518     } else {
06519       fn = ObjCTypes.getMessageSendFixupFn();
06520       messageRefName += "objc_msgSend_fixup";
06521     }
06522   }
06523   assert(fn && "CGObjCNonFragileABIMac::EmitMessageSend");
06524   messageRefName += '_';
06525 
06526   // Append the selector name, except use underscores anywhere we
06527   // would have used colons.
06528   appendSelectorForMessageRefTable(messageRefName, selector);
06529 
06530   llvm::GlobalVariable *messageRef
06531     = CGM.getModule().getGlobalVariable(messageRefName);
06532   if (!messageRef) {
06533     // Build the message ref structure.
06534     llvm::Constant *values[] = { fn, GetMethodVarName(selector) };
06535     llvm::Constant *init = llvm::ConstantStruct::getAnon(values);
06536     messageRef = new llvm::GlobalVariable(CGM.getModule(),
06537                                           init->getType(),
06538                                           /*constant*/ false,
06539                                           llvm::GlobalValue::WeakAnyLinkage,
06540                                           init,
06541                                           messageRefName);
06542     messageRef->setVisibility(llvm::GlobalValue::HiddenVisibility);
06543     messageRef->setAlignment(16);
06544     messageRef->setSection("__DATA, __objc_msgrefs, coalesced");
06545   }
06546   
06547   bool requiresnullCheck = false;
06548   if (CGM.getLangOpts().ObjCAutoRefCount && method)
06549     for (const auto *ParamDecl : method->params()) {
06550       if (ParamDecl->hasAttr<NSConsumedAttr>()) {
06551         if (!nullReturn.NullBB)
06552           nullReturn.init(CGF, arg0);
06553         requiresnullCheck = true;
06554         break;
06555       }
06556     }
06557   
06558   llvm::Value *mref =
06559     CGF.Builder.CreateBitCast(messageRef, ObjCTypes.MessageRefPtrTy);
06560 
06561   // Update the message ref argument.
06562   args[1].RV = RValue::get(mref);
06563 
06564   // Load the function to call from the message ref table.
06565   llvm::Value *callee = CGF.Builder.CreateStructGEP(mref, 0);
06566   callee = CGF.Builder.CreateLoad(callee, "msgSend_fn");
06567 
06568   callee = CGF.Builder.CreateBitCast(callee, MSI.MessengerType);
06569 
06570   RValue result = CGF.EmitCall(MSI.CallInfo, callee, returnSlot, args);
06571   return nullReturn.complete(CGF, result, resultType, formalArgs,
06572                              requiresnullCheck ? method : nullptr);
06573 }
06574 
06575 /// Generate code for a message send expression in the nonfragile abi.
06576 CodeGen::RValue
06577 CGObjCNonFragileABIMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
06578                                             ReturnValueSlot Return,
06579                                             QualType ResultType,
06580                                             Selector Sel,
06581                                             llvm::Value *Receiver,
06582                                             const CallArgList &CallArgs,
06583                                             const ObjCInterfaceDecl *Class,
06584                                             const ObjCMethodDecl *Method) {
06585   return isVTableDispatchedSelector(Sel)
06586     ? EmitVTableMessageSend(CGF, Return, ResultType, Sel,
06587                             Receiver, CGF.getContext().getObjCIdType(),
06588                             false, CallArgs, Method)
06589     : EmitMessageSend(CGF, Return, ResultType,
06590                       EmitSelector(CGF, Sel),
06591                       Receiver, CGF.getContext().getObjCIdType(),
06592                       false, CallArgs, Method, ObjCTypes);
06593 }
06594 
06595 llvm::GlobalVariable *
06596 CGObjCNonFragileABIMac::GetClassGlobal(const std::string &Name, bool Weak) {
06597   llvm::GlobalValue::LinkageTypes L =
06598       Weak ? llvm::GlobalValue::ExternalWeakLinkage
06599            : llvm::GlobalValue::ExternalLinkage;
06600 
06601   llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
06602 
06603   if (!GV)
06604     GV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABITy,
06605                                   false, L, nullptr, Name);
06606 
06607   assert(GV->getLinkage() == L);
06608   return GV;
06609 }
06610 
06611 llvm::Value *CGObjCNonFragileABIMac::EmitClassRefFromId(CodeGenFunction &CGF,
06612                                                         IdentifierInfo *II,
06613                                                         bool Weak,
06614                                                         const ObjCInterfaceDecl *ID) {
06615   llvm::GlobalVariable *&Entry = ClassReferences[II];
06616   
06617   if (!Entry) {
06618     std::string ClassName(
06619       getClassSymbolPrefix() +
06620       (ID ? ID->getObjCRuntimeNameAsString() : II->getName()).str());
06621     llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName, Weak);
06622     Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
06623                                      false, llvm::GlobalValue::PrivateLinkage,
06624                                      ClassGV, "OBJC_CLASSLIST_REFERENCES_$_");
06625     Entry->setAlignment(
06626                         CGM.getDataLayout().getABITypeAlignment(
06627                                                                 ObjCTypes.ClassnfABIPtrTy));
06628     Entry->setSection("__DATA, __objc_classrefs, regular, no_dead_strip");
06629     CGM.addCompilerUsedGlobal(Entry);
06630   }
06631   return CGF.Builder.CreateLoad(Entry);
06632 }
06633 
06634 llvm::Value *CGObjCNonFragileABIMac::EmitClassRef(CodeGenFunction &CGF,
06635                                                   const ObjCInterfaceDecl *ID) {
06636   return EmitClassRefFromId(CGF, ID->getIdentifier(), ID->isWeakImported(), ID);
06637 }
06638 
06639 llvm::Value *CGObjCNonFragileABIMac::EmitNSAutoreleasePoolClassRef(
06640                                                     CodeGenFunction &CGF) {
06641   IdentifierInfo *II = &CGM.getContext().Idents.get("NSAutoreleasePool");
06642   return EmitClassRefFromId(CGF, II, false, 0);
06643 }
06644 
06645 llvm::Value *
06646 CGObjCNonFragileABIMac::EmitSuperClassRef(CodeGenFunction &CGF,
06647                                           const ObjCInterfaceDecl *ID) {
06648   llvm::GlobalVariable *&Entry = SuperClassReferences[ID->getIdentifier()];
06649 
06650   if (!Entry) {
06651     llvm::SmallString<64> ClassName(getClassSymbolPrefix());
06652     ClassName += ID->getObjCRuntimeNameAsString();
06653     llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName.str(),
06654                                                    ID->isWeakImported());
06655     Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
06656                                      false, llvm::GlobalValue::PrivateLinkage,
06657                                      ClassGV, "OBJC_CLASSLIST_SUP_REFS_$_");
06658     Entry->setAlignment(
06659       CGM.getDataLayout().getABITypeAlignment(
06660         ObjCTypes.ClassnfABIPtrTy));
06661     Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
06662     CGM.addCompilerUsedGlobal(Entry);
06663   }
06664   return CGF.Builder.CreateLoad(Entry);
06665 }
06666 
06667 /// EmitMetaClassRef - Return a Value * of the address of _class_t
06668 /// meta-data
06669 ///
06670 llvm::Value *CGObjCNonFragileABIMac::EmitMetaClassRef(CodeGenFunction &CGF,
06671                                                       const ObjCInterfaceDecl *ID,
06672                                                       bool Weak) {
06673   llvm::GlobalVariable * &Entry = MetaClassReferences[ID->getIdentifier()];
06674   if (!Entry) {
06675     llvm::SmallString<64> MetaClassName(getMetaclassSymbolPrefix());
06676     MetaClassName += ID->getObjCRuntimeNameAsString();
06677     llvm::GlobalVariable *MetaClassGV =
06678       GetClassGlobal(MetaClassName.str(), Weak);
06679 
06680     Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.ClassnfABIPtrTy,
06681                                      false, llvm::GlobalValue::PrivateLinkage,
06682                                      MetaClassGV, "OBJC_CLASSLIST_SUP_REFS_$_");
06683     Entry->setAlignment(
06684         CGM.getDataLayout().getABITypeAlignment(ObjCTypes.ClassnfABIPtrTy));
06685 
06686     Entry->setSection("__DATA, __objc_superrefs, regular, no_dead_strip");
06687     CGM.addCompilerUsedGlobal(Entry);
06688   }
06689 
06690   return CGF.Builder.CreateLoad(Entry);
06691 }
06692 
06693 /// GetClass - Return a reference to the class for the given interface
06694 /// decl.
06695 llvm::Value *CGObjCNonFragileABIMac::GetClass(CodeGenFunction &CGF,
06696                                               const ObjCInterfaceDecl *ID) {
06697   if (ID->isWeakImported()) {
06698     llvm::SmallString<64> ClassName(getClassSymbolPrefix());
06699     ClassName += ID->getObjCRuntimeNameAsString();
06700     llvm::GlobalVariable *ClassGV = GetClassGlobal(ClassName.str(), true);
06701     (void)ClassGV;
06702     assert(ClassGV->hasExternalWeakLinkage());
06703   }
06704   
06705   return EmitClassRef(CGF, ID);
06706 }
06707 
06708 /// Generates a message send where the super is the receiver.  This is
06709 /// a message send to self with special delivery semantics indicating
06710 /// which class's method should be called.
06711 CodeGen::RValue
06712 CGObjCNonFragileABIMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
06713                                                  ReturnValueSlot Return,
06714                                                  QualType ResultType,
06715                                                  Selector Sel,
06716                                                  const ObjCInterfaceDecl *Class,
06717                                                  bool isCategoryImpl,
06718                                                  llvm::Value *Receiver,
06719                                                  bool IsClassMessage,
06720                                                  const CodeGen::CallArgList &CallArgs,
06721                                                  const ObjCMethodDecl *Method) {
06722   // ...
06723   // Create and init a super structure; this is a (receiver, class)
06724   // pair we will pass to objc_msgSendSuper.
06725   llvm::Value *ObjCSuper =
06726     CGF.CreateTempAlloca(ObjCTypes.SuperTy, "objc_super");
06727 
06728   llvm::Value *ReceiverAsObject =
06729     CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
06730   CGF.Builder.CreateStore(ReceiverAsObject,
06731                           CGF.Builder.CreateStructGEP(ObjCSuper, 0));
06732 
06733   // If this is a class message the metaclass is passed as the target.
06734   llvm::Value *Target;
06735   if (IsClassMessage)
06736       Target = EmitMetaClassRef(CGF, Class, Class->isWeakImported());
06737   else
06738     Target = EmitSuperClassRef(CGF, Class);
06739 
06740   // FIXME: We shouldn't need to do this cast, rectify the ASTContext and
06741   // ObjCTypes types.
06742   llvm::Type *ClassTy =
06743     CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
06744   Target = CGF.Builder.CreateBitCast(Target, ClassTy);
06745   CGF.Builder.CreateStore(Target,
06746                           CGF.Builder.CreateStructGEP(ObjCSuper, 1));
06747 
06748   return (isVTableDispatchedSelector(Sel))
06749     ? EmitVTableMessageSend(CGF, Return, ResultType, Sel,
06750                             ObjCSuper, ObjCTypes.SuperPtrCTy,
06751                             true, CallArgs, Method)
06752     : EmitMessageSend(CGF, Return, ResultType,
06753                       EmitSelector(CGF, Sel),
06754                       ObjCSuper, ObjCTypes.SuperPtrCTy,
06755                       true, CallArgs, Method, ObjCTypes);
06756 }
06757 
06758 llvm::Value *CGObjCNonFragileABIMac::EmitSelector(CodeGenFunction &CGF,
06759                                                   Selector Sel, bool lval) {
06760   llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
06761 
06762   if (!Entry) {
06763     llvm::Constant *Casted =
06764       llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
06765                                      ObjCTypes.SelectorPtrTy);
06766     Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.SelectorPtrTy,
06767                                      false, llvm::GlobalValue::PrivateLinkage,
06768                                      Casted, "OBJC_SELECTOR_REFERENCES_");
06769     Entry->setExternallyInitialized(true);
06770     Entry->setSection("__DATA, __objc_selrefs, literal_pointers, no_dead_strip");
06771     CGM.addCompilerUsedGlobal(Entry);
06772   }
06773 
06774   if (lval)
06775     return Entry;
06776   llvm::LoadInst* LI = CGF.Builder.CreateLoad(Entry);
06777   
06778   LI->setMetadata(CGM.getModule().getMDKindID("invariant.load"), 
06779                   llvm::MDNode::get(VMContext, None));
06780   return LI;
06781 }
06782 /// EmitObjCIvarAssign - Code gen for assigning to a __strong object.
06783 /// objc_assign_ivar (id src, id *dst, ptrdiff_t)
06784 ///
06785 void CGObjCNonFragileABIMac::EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
06786                                                 llvm::Value *src,
06787                                                 llvm::Value *dst,
06788                                                 llvm::Value *ivarOffset) {
06789   llvm::Type * SrcTy = src->getType();
06790   if (!isa<llvm::PointerType>(SrcTy)) {
06791     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
06792     assert(Size <= 8 && "does not support size > 8");
06793     src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
06794            : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
06795     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
06796   }
06797   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
06798   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
06799   llvm::Value *args[] = { src, dst, ivarOffset };
06800   CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignIvarFn(), args);
06801 }
06802 
06803 /// EmitObjCStrongCastAssign - Code gen for assigning to a __strong cast object.
06804 /// objc_assign_strongCast (id src, id *dst)
06805 ///
06806 void CGObjCNonFragileABIMac::EmitObjCStrongCastAssign(
06807   CodeGen::CodeGenFunction &CGF,
06808   llvm::Value *src, llvm::Value *dst) {
06809   llvm::Type * SrcTy = src->getType();
06810   if (!isa<llvm::PointerType>(SrcTy)) {
06811     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
06812     assert(Size <= 8 && "does not support size > 8");
06813     src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
06814            : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
06815     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
06816   }
06817   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
06818   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
06819   llvm::Value *args[] = { src, dst };
06820   CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignStrongCastFn(),
06821                               args, "weakassign");
06822 }
06823 
06824 void CGObjCNonFragileABIMac::EmitGCMemmoveCollectable(
06825   CodeGen::CodeGenFunction &CGF,
06826   llvm::Value *DestPtr,
06827   llvm::Value *SrcPtr,
06828   llvm::Value *Size) {
06829   SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, ObjCTypes.Int8PtrTy);
06830   DestPtr = CGF.Builder.CreateBitCast(DestPtr, ObjCTypes.Int8PtrTy);
06831   llvm::Value *args[] = { DestPtr, SrcPtr, Size };
06832   CGF.EmitNounwindRuntimeCall(ObjCTypes.GcMemmoveCollectableFn(), args);
06833 }
06834 
06835 /// EmitObjCWeakRead - Code gen for loading value of a __weak
06836 /// object: objc_read_weak (id *src)
06837 ///
06838 llvm::Value * CGObjCNonFragileABIMac::EmitObjCWeakRead(
06839   CodeGen::CodeGenFunction &CGF,
06840   llvm::Value *AddrWeakObj) {
06841   llvm::Type* DestTy =
06842     cast<llvm::PointerType>(AddrWeakObj->getType())->getElementType();
06843   AddrWeakObj = CGF.Builder.CreateBitCast(AddrWeakObj, ObjCTypes.PtrObjectPtrTy);
06844   llvm::Value *read_weak =
06845     CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcReadWeakFn(),
06846                                 AddrWeakObj, "weakread");
06847   read_weak = CGF.Builder.CreateBitCast(read_weak, DestTy);
06848   return read_weak;
06849 }
06850 
06851 /// EmitObjCWeakAssign - Code gen for assigning to a __weak object.
06852 /// objc_assign_weak (id src, id *dst)
06853 ///
06854 void CGObjCNonFragileABIMac::EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
06855                                                 llvm::Value *src, llvm::Value *dst) {
06856   llvm::Type * SrcTy = src->getType();
06857   if (!isa<llvm::PointerType>(SrcTy)) {
06858     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
06859     assert(Size <= 8 && "does not support size > 8");
06860     src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
06861            : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
06862     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
06863   }
06864   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
06865   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
06866   llvm::Value *args[] = { src, dst };
06867   CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignWeakFn(),
06868                               args, "weakassign");
06869 }
06870 
06871 /// EmitObjCGlobalAssign - Code gen for assigning to a __strong object.
06872 /// objc_assign_global (id src, id *dst)
06873 ///
06874 void CGObjCNonFragileABIMac::EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
06875                                           llvm::Value *src, llvm::Value *dst,
06876                                           bool threadlocal) {
06877   llvm::Type * SrcTy = src->getType();
06878   if (!isa<llvm::PointerType>(SrcTy)) {
06879     unsigned Size = CGM.getDataLayout().getTypeAllocSize(SrcTy);
06880     assert(Size <= 8 && "does not support size > 8");
06881     src = (Size == 4 ? CGF.Builder.CreateBitCast(src, ObjCTypes.IntTy)
06882            : CGF.Builder.CreateBitCast(src, ObjCTypes.LongTy));
06883     src = CGF.Builder.CreateIntToPtr(src, ObjCTypes.Int8PtrTy);
06884   }
06885   src = CGF.Builder.CreateBitCast(src, ObjCTypes.ObjectPtrTy);
06886   dst = CGF.Builder.CreateBitCast(dst, ObjCTypes.PtrObjectPtrTy);
06887   llvm::Value *args[] = { src, dst };
06888   if (!threadlocal)
06889     CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignGlobalFn(),
06890                                 args, "globalassign");
06891   else
06892     CGF.EmitNounwindRuntimeCall(ObjCTypes.getGcAssignThreadLocalFn(),
06893                                 args, "threadlocalassign");
06894 }
06895 
06896 void
06897 CGObjCNonFragileABIMac::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
06898                                              const ObjCAtSynchronizedStmt &S) {
06899   EmitAtSynchronizedStmt(CGF, S,
06900       cast<llvm::Function>(ObjCTypes.getSyncEnterFn()),
06901       cast<llvm::Function>(ObjCTypes.getSyncExitFn()));
06902 }
06903 
06904 llvm::Constant *
06905 CGObjCNonFragileABIMac::GetEHType(QualType T) {
06906   // There's a particular fixed type info for 'id'.
06907   if (T->isObjCIdType() ||
06908       T->isObjCQualifiedIdType()) {
06909     llvm::Constant *IDEHType =
06910       CGM.getModule().getGlobalVariable("OBJC_EHTYPE_id");
06911     if (!IDEHType)
06912       IDEHType =
06913         new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy,
06914                                  false,
06915                                  llvm::GlobalValue::ExternalLinkage,
06916                                  nullptr, "OBJC_EHTYPE_id");
06917     return IDEHType;
06918   }
06919 
06920   // All other types should be Objective-C interface pointer types.
06921   const ObjCObjectPointerType *PT =
06922     T->getAs<ObjCObjectPointerType>();
06923   assert(PT && "Invalid @catch type.");
06924   const ObjCInterfaceType *IT = PT->getInterfaceType();
06925   assert(IT && "Invalid @catch type.");
06926   return GetInterfaceEHType(IT->getDecl(), false);
06927 }                                                  
06928 
06929 void CGObjCNonFragileABIMac::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
06930                                          const ObjCAtTryStmt &S) {
06931   EmitTryCatchStmt(CGF, S,
06932       cast<llvm::Function>(ObjCTypes.getObjCBeginCatchFn()),
06933       cast<llvm::Function>(ObjCTypes.getObjCEndCatchFn()),
06934       cast<llvm::Function>(ObjCTypes.getExceptionRethrowFn()));
06935 }
06936 
06937 /// EmitThrowStmt - Generate code for a throw statement.
06938 void CGObjCNonFragileABIMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
06939                                            const ObjCAtThrowStmt &S,
06940                                            bool ClearInsertionPoint) {
06941   if (const Expr *ThrowExpr = S.getThrowExpr()) {
06942     llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
06943     Exception = CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy);
06944     CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionThrowFn(), Exception)
06945       .setDoesNotReturn();
06946   } else {
06947     CGF.EmitRuntimeCallOrInvoke(ObjCTypes.getExceptionRethrowFn())
06948       .setDoesNotReturn();
06949   }
06950 
06951   CGF.Builder.CreateUnreachable();
06952   if (ClearInsertionPoint)
06953     CGF.Builder.ClearInsertionPoint();
06954 }
06955 
06956 llvm::Constant *
06957 CGObjCNonFragileABIMac::GetInterfaceEHType(const ObjCInterfaceDecl *ID,
06958                                            bool ForDefinition) {
06959   llvm::GlobalVariable * &Entry = EHTypeReferences[ID->getIdentifier()];
06960 
06961   // If we don't need a definition, return the entry if found or check
06962   // if we use an external reference.
06963   if (!ForDefinition) {
06964     if (Entry)
06965       return Entry;
06966 
06967     // If this type (or a super class) has the __objc_exception__
06968     // attribute, emit an external reference.
06969     if (hasObjCExceptionAttribute(CGM.getContext(), ID))
06970       return Entry =
06971           new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false,
06972                                    llvm::GlobalValue::ExternalLinkage,
06973                                    nullptr,
06974                                    ("OBJC_EHTYPE_$_" +
06975                                     ID->getObjCRuntimeNameAsString()));
06976   }
06977 
06978   // Otherwise we need to either make a new entry or fill in the
06979   // initializer.
06980   assert((!Entry || !Entry->hasInitializer()) && "Duplicate EHType definition");
06981   llvm::SmallString<64> ClassName(getClassSymbolPrefix());
06982   ClassName += ID->getObjCRuntimeNameAsString();
06983   std::string VTableName = "objc_ehtype_vtable";
06984   llvm::GlobalVariable *VTableGV =
06985     CGM.getModule().getGlobalVariable(VTableName);
06986   if (!VTableGV)
06987     VTableGV = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.Int8PtrTy,
06988                                         false,
06989                                         llvm::GlobalValue::ExternalLinkage,
06990                                         nullptr, VTableName);
06991 
06992   llvm::Value *VTableIdx = llvm::ConstantInt::get(CGM.Int32Ty, 2);
06993 
06994   llvm::Constant *Values[] = {
06995     llvm::ConstantExpr::getGetElementPtr(VTableGV, VTableIdx),
06996     GetClassName(ID->getObjCRuntimeNameAsString()),
06997     GetClassGlobal(ClassName.str())
06998   };
06999   llvm::Constant *Init =
07000     llvm::ConstantStruct::get(ObjCTypes.EHTypeTy, Values);
07001 
07002   llvm::GlobalValue::LinkageTypes L = ForDefinition
07003                                           ? llvm::GlobalValue::ExternalLinkage
07004                                           : llvm::GlobalValue::WeakAnyLinkage;
07005   if (Entry) {
07006     Entry->setInitializer(Init);
07007   } else {
07008     llvm::SmallString<64> EHTYPEName("OBJC_EHTYPE_$_");
07009     EHTYPEName += ID->getObjCRuntimeNameAsString();
07010     Entry = new llvm::GlobalVariable(CGM.getModule(), ObjCTypes.EHTypeTy, false,
07011                                      L,
07012                                      Init,
07013                                      EHTYPEName.str());
07014   }
07015   assert(Entry->getLinkage() == L);
07016 
07017   if (ID->getVisibility() == HiddenVisibility)
07018     Entry->setVisibility(llvm::GlobalValue::HiddenVisibility);
07019   Entry->setAlignment(CGM.getDataLayout().getABITypeAlignment(
07020       ObjCTypes.EHTypeTy));
07021 
07022   if (ForDefinition)
07023     Entry->setSection("__DATA,__objc_const");
07024   else
07025     Entry->setSection("__DATA,__datacoal_nt,coalesced");
07026 
07027   return Entry;
07028 }
07029 
07030 /* *** */
07031 
07032 CodeGen::CGObjCRuntime *
07033 CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
07034   switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
07035   case ObjCRuntime::FragileMacOSX:
07036   return new CGObjCMac(CGM);
07037 
07038   case ObjCRuntime::MacOSX:
07039   case ObjCRuntime::iOS:
07040     return new CGObjCNonFragileABIMac(CGM);
07041 
07042   case ObjCRuntime::GNUstep:
07043   case ObjCRuntime::GCC:
07044   case ObjCRuntime::ObjFW:
07045     llvm_unreachable("these runtimes are not Mac runtimes");
07046   }
07047   llvm_unreachable("bad runtime");
07048 }