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