1 //===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This provides Objective-C code generation targeting the GNU runtime.  The
10 // class in this file generates structures used by the GNU Objective-C runtime
11 // library.  These structures are defined in objc/objc.h and objc/objc-api.h in
12 // the GNU runtime distribution.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "CGCXXABI.h"
17 #include "CGCleanup.h"
18 #include "CGObjCRuntime.h"
19 #include "CodeGenFunction.h"
20 #include "CodeGenModule.h"
21 #include "CodeGenTypes.h"
22 #include "SanitizerMetadata.h"
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/Attr.h"
25 #include "clang/AST/Decl.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/RecordLayout.h"
28 #include "clang/AST/StmtObjC.h"
29 #include "clang/Basic/FileManager.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/CodeGen/ConstantInitBuilder.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/StringMap.h"
34 #include "llvm/IR/DataLayout.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Support/ConvertUTF.h"
40 #include <cctype>
41 
42 using namespace clang;
43 using namespace CodeGen;
44 
45 namespace {
46 
47 /// Class that lazily initialises the runtime function.  Avoids inserting the
48 /// types and the function declaration into a module if they're not used, and
49 /// avoids constructing the type more than once if it's used more than once.
50 class LazyRuntimeFunction {
51   CodeGenModule *CGM = nullptr;
52   llvm::FunctionType *FTy = nullptr;
53   const char *FunctionName = nullptr;
54   llvm::FunctionCallee Function = nullptr;
55 
56 public:
57   LazyRuntimeFunction() = default;
58 
59   /// Initialises the lazy function with the name, return type, and the types
60   /// of the arguments.
61   template <typename... Tys>
init(CodeGenModule * Mod,const char * name,llvm::Type * RetTy,Tys * ...Types)62   void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy,
63             Tys *... Types) {
64     CGM = Mod;
65     FunctionName = name;
66     Function = nullptr;
67     if(sizeof...(Tys)) {
68       SmallVector<llvm::Type *, 8> ArgTys({Types...});
69       FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
70     }
71     else {
72       FTy = llvm::FunctionType::get(RetTy, std::nullopt, false);
73     }
74   }
75 
getType()76   llvm::FunctionType *getType() { return FTy; }
77 
78   /// Overloaded cast operator, allows the class to be implicitly cast to an
79   /// LLVM constant.
operator llvm::FunctionCallee()80   operator llvm::FunctionCallee() {
81     if (!Function) {
82       if (!FunctionName)
83         return nullptr;
84       Function = CGM->CreateRuntimeFunction(FTy, FunctionName);
85     }
86     return Function;
87   }
88 };
89 
90 
91 /// GNU Objective-C runtime code generation.  This class implements the parts of
92 /// Objective-C support that are specific to the GNU family of runtimes (GCC,
93 /// GNUstep and ObjFW).
94 class CGObjCGNU : public CGObjCRuntime {
95 protected:
96   /// The LLVM module into which output is inserted
97   llvm::Module &TheModule;
98   /// strut objc_super.  Used for sending messages to super.  This structure
99   /// contains the receiver (object) and the expected class.
100   llvm::StructType *ObjCSuperTy;
101   /// struct objc_super*.  The type of the argument to the superclass message
102   /// lookup functions.
103   llvm::PointerType *PtrToObjCSuperTy;
104   /// LLVM type for selectors.  Opaque pointer (i8*) unless a header declaring
105   /// SEL is included in a header somewhere, in which case it will be whatever
106   /// type is declared in that header, most likely {i8*, i8*}.
107   llvm::PointerType *SelectorTy;
108   /// Element type of SelectorTy.
109   llvm::Type *SelectorElemTy;
110   /// LLVM i8 type.  Cached here to avoid repeatedly getting it in all of the
111   /// places where it's used
112   llvm::IntegerType *Int8Ty;
113   /// Pointer to i8 - LLVM type of char*, for all of the places where the
114   /// runtime needs to deal with C strings.
115   llvm::PointerType *PtrToInt8Ty;
116   /// struct objc_protocol type
117   llvm::StructType *ProtocolTy;
118   /// Protocol * type.
119   llvm::PointerType *ProtocolPtrTy;
120   /// Instance Method Pointer type.  This is a pointer to a function that takes,
121   /// at a minimum, an object and a selector, and is the generic type for
122   /// Objective-C methods.  Due to differences between variadic / non-variadic
123   /// calling conventions, it must always be cast to the correct type before
124   /// actually being used.
125   llvm::PointerType *IMPTy;
126   /// Type of an untyped Objective-C object.  Clang treats id as a built-in type
127   /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
128   /// but if the runtime header declaring it is included then it may be a
129   /// pointer to a structure.
130   llvm::PointerType *IdTy;
131   /// Element type of IdTy.
132   llvm::Type *IdElemTy;
133   /// Pointer to a pointer to an Objective-C object.  Used in the new ABI
134   /// message lookup function and some GC-related functions.
135   llvm::PointerType *PtrToIdTy;
136   /// The clang type of id.  Used when using the clang CGCall infrastructure to
137   /// call Objective-C methods.
138   CanQualType ASTIdTy;
139   /// LLVM type for C int type.
140   llvm::IntegerType *IntTy;
141   /// LLVM type for an opaque pointer.  This is identical to PtrToInt8Ty, but is
142   /// used in the code to document the difference between i8* meaning a pointer
143   /// to a C string and i8* meaning a pointer to some opaque type.
144   llvm::PointerType *PtrTy;
145   /// LLVM type for C long type.  The runtime uses this in a lot of places where
146   /// it should be using intptr_t, but we can't fix this without breaking
147   /// compatibility with GCC...
148   llvm::IntegerType *LongTy;
149   /// LLVM type for C size_t.  Used in various runtime data structures.
150   llvm::IntegerType *SizeTy;
151   /// LLVM type for C intptr_t.
152   llvm::IntegerType *IntPtrTy;
153   /// LLVM type for C ptrdiff_t.  Mainly used in property accessor functions.
154   llvm::IntegerType *PtrDiffTy;
155   /// LLVM type for C int*.  Used for GCC-ABI-compatible non-fragile instance
156   /// variables.
157   llvm::PointerType *PtrToIntTy;
158   /// LLVM type for Objective-C BOOL type.
159   llvm::Type *BoolTy;
160   /// 32-bit integer type, to save us needing to look it up every time it's used.
161   llvm::IntegerType *Int32Ty;
162   /// 64-bit integer type, to save us needing to look it up every time it's used.
163   llvm::IntegerType *Int64Ty;
164   /// The type of struct objc_property.
165   llvm::StructType *PropertyMetadataTy;
166   /// Metadata kind used to tie method lookups to message sends.  The GNUstep
167   /// runtime provides some LLVM passes that can use this to do things like
168   /// automatic IMP caching and speculative inlining.
169   unsigned msgSendMDKind;
170   /// Does the current target use SEH-based exceptions? False implies
171   /// Itanium-style DWARF unwinding.
172   bool usesSEHExceptions;
173   /// Does the current target uses C++-based exceptions?
174   bool usesCxxExceptions;
175 
176   /// Helper to check if we are targeting a specific runtime version or later.
isRuntime(ObjCRuntime::Kind kind,unsigned major,unsigned minor=0)177   bool isRuntime(ObjCRuntime::Kind kind, unsigned major, unsigned minor=0) {
178     const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
179     return (R.getKind() == kind) &&
180       (R.getVersion() >= VersionTuple(major, minor));
181   }
182 
ManglePublicSymbol(StringRef Name)183   std::string ManglePublicSymbol(StringRef Name) {
184     return (StringRef(CGM.getTriple().isOSBinFormatCOFF() ? "$_" : "._") + Name).str();
185   }
186 
SymbolForProtocol(Twine Name)187   std::string SymbolForProtocol(Twine Name) {
188     return (ManglePublicSymbol("OBJC_PROTOCOL_") + Name).str();
189   }
190 
SymbolForProtocolRef(StringRef Name)191   std::string SymbolForProtocolRef(StringRef Name) {
192     return (ManglePublicSymbol("OBJC_REF_PROTOCOL_") + Name).str();
193   }
194 
195 
196   /// Helper function that generates a constant string and returns a pointer to
197   /// the start of the string.  The result of this function can be used anywhere
198   /// where the C code specifies const char*.
MakeConstantString(StringRef Str,const char * Name="")199   llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") {
200     ConstantAddress Array =
201         CGM.GetAddrOfConstantCString(std::string(Str), Name);
202     return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
203                                                 Array.getPointer(), Zeros);
204   }
205 
206   /// Emits a linkonce_odr string, whose name is the prefix followed by the
207   /// string value.  This allows the linker to combine the strings between
208   /// different modules.  Used for EH typeinfo names, selector strings, and a
209   /// few other things.
ExportUniqueString(const std::string & Str,const std::string & prefix,bool Private=false)210   llvm::Constant *ExportUniqueString(const std::string &Str,
211                                      const std::string &prefix,
212                                      bool Private=false) {
213     std::string name = prefix + Str;
214     auto *ConstStr = TheModule.getGlobalVariable(name);
215     if (!ConstStr) {
216       llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
217       auto *GV = new llvm::GlobalVariable(TheModule, value->getType(), true,
218               llvm::GlobalValue::LinkOnceODRLinkage, value, name);
219       GV->setComdat(TheModule.getOrInsertComdat(name));
220       if (Private)
221         GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
222       ConstStr = GV;
223     }
224     return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
225                                                 ConstStr, Zeros);
226   }
227 
228   /// Returns a property name and encoding string.
MakePropertyEncodingString(const ObjCPropertyDecl * PD,const Decl * Container)229   llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
230                                              const Decl *Container) {
231     assert(!isRuntime(ObjCRuntime::GNUstep, 2));
232     if (isRuntime(ObjCRuntime::GNUstep, 1, 6)) {
233       std::string NameAndAttributes;
234       std::string TypeStr =
235         CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);
236       NameAndAttributes += '\0';
237       NameAndAttributes += TypeStr.length() + 3;
238       NameAndAttributes += TypeStr;
239       NameAndAttributes += '\0';
240       NameAndAttributes += PD->getNameAsString();
241       return MakeConstantString(NameAndAttributes);
242     }
243     return MakeConstantString(PD->getNameAsString());
244   }
245 
246   /// Push the property attributes into two structure fields.
PushPropertyAttributes(ConstantStructBuilder & Fields,const ObjCPropertyDecl * property,bool isSynthesized=true,bool isDynamic=true)247   void PushPropertyAttributes(ConstantStructBuilder &Fields,
248       const ObjCPropertyDecl *property, bool isSynthesized=true, bool
249       isDynamic=true) {
250     int attrs = property->getPropertyAttributes();
251     // For read-only properties, clear the copy and retain flags
252     if (attrs & ObjCPropertyAttribute::kind_readonly) {
253       attrs &= ~ObjCPropertyAttribute::kind_copy;
254       attrs &= ~ObjCPropertyAttribute::kind_retain;
255       attrs &= ~ObjCPropertyAttribute::kind_weak;
256       attrs &= ~ObjCPropertyAttribute::kind_strong;
257     }
258     // The first flags field has the same attribute values as clang uses internally
259     Fields.addInt(Int8Ty, attrs & 0xff);
260     attrs >>= 8;
261     attrs <<= 2;
262     // For protocol properties, synthesized and dynamic have no meaning, so we
263     // reuse these flags to indicate that this is a protocol property (both set
264     // has no meaning, as a property can't be both synthesized and dynamic)
265     attrs |= isSynthesized ? (1<<0) : 0;
266     attrs |= isDynamic ? (1<<1) : 0;
267     // The second field is the next four fields left shifted by two, with the
268     // low bit set to indicate whether the field is synthesized or dynamic.
269     Fields.addInt(Int8Ty, attrs & 0xff);
270     // Two padding fields
271     Fields.addInt(Int8Ty, 0);
272     Fields.addInt(Int8Ty, 0);
273   }
274 
275   virtual llvm::Constant *GenerateCategoryProtocolList(const
276       ObjCCategoryDecl *OCD);
PushPropertyListHeader(ConstantStructBuilder & Fields,int count)277   virtual ConstantArrayBuilder PushPropertyListHeader(ConstantStructBuilder &Fields,
278       int count) {
279       // int count;
280       Fields.addInt(IntTy, count);
281       // int size; (only in GNUstep v2 ABI.
282       if (isRuntime(ObjCRuntime::GNUstep, 2)) {
283         llvm::DataLayout td(&TheModule);
284         Fields.addInt(IntTy, td.getTypeSizeInBits(PropertyMetadataTy) /
285             CGM.getContext().getCharWidth());
286       }
287       // struct objc_property_list *next;
288       Fields.add(NULLPtr);
289       // struct objc_property properties[]
290       return Fields.beginArray(PropertyMetadataTy);
291   }
PushProperty(ConstantArrayBuilder & PropertiesArray,const ObjCPropertyDecl * property,const Decl * OCD,bool isSynthesized=true,bool isDynamic=true)292   virtual void PushProperty(ConstantArrayBuilder &PropertiesArray,
293             const ObjCPropertyDecl *property,
294             const Decl *OCD,
295             bool isSynthesized=true, bool
296             isDynamic=true) {
297     auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
298     ASTContext &Context = CGM.getContext();
299     Fields.add(MakePropertyEncodingString(property, OCD));
300     PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
301     auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
302       if (accessor) {
303         std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
304         llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
305         Fields.add(MakeConstantString(accessor->getSelector().getAsString()));
306         Fields.add(TypeEncoding);
307       } else {
308         Fields.add(NULLPtr);
309         Fields.add(NULLPtr);
310       }
311     };
312     addPropertyMethod(property->getGetterMethodDecl());
313     addPropertyMethod(property->getSetterMethodDecl());
314     Fields.finishAndAddTo(PropertiesArray);
315   }
316 
317   /// Ensures that the value has the required type, by inserting a bitcast if
318   /// required.  This function lets us avoid inserting bitcasts that are
319   /// redundant.
EnforceType(CGBuilderTy & B,llvm::Value * V,llvm::Type * Ty)320   llvm::Value *EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
321     if (V->getType() == Ty)
322       return V;
323     return B.CreateBitCast(V, Ty);
324   }
325 
326   // Some zeros used for GEPs in lots of places.
327   llvm::Constant *Zeros[2];
328   /// Null pointer value.  Mainly used as a terminator in various arrays.
329   llvm::Constant *NULLPtr;
330   /// LLVM context.
331   llvm::LLVMContext &VMContext;
332 
333 protected:
334 
335   /// Placeholder for the class.  Lots of things refer to the class before we've
336   /// actually emitted it.  We use this alias as a placeholder, and then replace
337   /// it with a pointer to the class structure before finally emitting the
338   /// module.
339   llvm::GlobalAlias *ClassPtrAlias;
340   /// Placeholder for the metaclass.  Lots of things refer to the class before
341   /// we've / actually emitted it.  We use this alias as a placeholder, and then
342   /// replace / it with a pointer to the metaclass structure before finally
343   /// emitting the / module.
344   llvm::GlobalAlias *MetaClassPtrAlias;
345   /// All of the classes that have been generated for this compilation units.
346   std::vector<llvm::Constant*> Classes;
347   /// All of the categories that have been generated for this compilation units.
348   std::vector<llvm::Constant*> Categories;
349   /// All of the Objective-C constant strings that have been generated for this
350   /// compilation units.
351   std::vector<llvm::Constant*> ConstantStrings;
352   /// Map from string values to Objective-C constant strings in the output.
353   /// Used to prevent emitting Objective-C strings more than once.  This should
354   /// not be required at all - CodeGenModule should manage this list.
355   llvm::StringMap<llvm::Constant*> ObjCStrings;
356   /// All of the protocols that have been declared.
357   llvm::StringMap<llvm::Constant*> ExistingProtocols;
358   /// For each variant of a selector, we store the type encoding and a
359   /// placeholder value.  For an untyped selector, the type will be the empty
360   /// string.  Selector references are all done via the module's selector table,
361   /// so we create an alias as a placeholder and then replace it with the real
362   /// value later.
363   typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
364   /// Type of the selector map.  This is roughly equivalent to the structure
365   /// used in the GNUstep runtime, which maintains a list of all of the valid
366   /// types for a selector in a table.
367   typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
368     SelectorMap;
369   /// A map from selectors to selector types.  This allows us to emit all
370   /// selectors of the same name and type together.
371   SelectorMap SelectorTable;
372 
373   /// Selectors related to memory management.  When compiling in GC mode, we
374   /// omit these.
375   Selector RetainSel, ReleaseSel, AutoreleaseSel;
376   /// Runtime functions used for memory management in GC mode.  Note that clang
377   /// supports code generation for calling these functions, but neither GNU
378   /// runtime actually supports this API properly yet.
379   LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
380     WeakAssignFn, GlobalAssignFn;
381 
382   typedef std::pair<std::string, std::string> ClassAliasPair;
383   /// All classes that have aliases set for them.
384   std::vector<ClassAliasPair> ClassAliases;
385 
386 protected:
387   /// Function used for throwing Objective-C exceptions.
388   LazyRuntimeFunction ExceptionThrowFn;
389   /// Function used for rethrowing exceptions, used at the end of \@finally or
390   /// \@synchronize blocks.
391   LazyRuntimeFunction ExceptionReThrowFn;
392   /// Function called when entering a catch function.  This is required for
393   /// differentiating Objective-C exceptions and foreign exceptions.
394   LazyRuntimeFunction EnterCatchFn;
395   /// Function called when exiting from a catch block.  Used to do exception
396   /// cleanup.
397   LazyRuntimeFunction ExitCatchFn;
398   /// Function called when entering an \@synchronize block.  Acquires the lock.
399   LazyRuntimeFunction SyncEnterFn;
400   /// Function called when exiting an \@synchronize block.  Releases the lock.
401   LazyRuntimeFunction SyncExitFn;
402 
403 private:
404   /// Function called if fast enumeration detects that the collection is
405   /// modified during the update.
406   LazyRuntimeFunction EnumerationMutationFn;
407   /// Function for implementing synthesized property getters that return an
408   /// object.
409   LazyRuntimeFunction GetPropertyFn;
410   /// Function for implementing synthesized property setters that return an
411   /// object.
412   LazyRuntimeFunction SetPropertyFn;
413   /// Function used for non-object declared property getters.
414   LazyRuntimeFunction GetStructPropertyFn;
415   /// Function used for non-object declared property setters.
416   LazyRuntimeFunction SetStructPropertyFn;
417 
418 protected:
419   /// The version of the runtime that this class targets.  Must match the
420   /// version in the runtime.
421   int RuntimeVersion;
422   /// The version of the protocol class.  Used to differentiate between ObjC1
423   /// and ObjC2 protocols.  Objective-C 1 protocols can not contain optional
424   /// components and can not contain declared properties.  We always emit
425   /// Objective-C 2 property structures, but we have to pretend that they're
426   /// Objective-C 1 property structures when targeting the GCC runtime or it
427   /// will abort.
428   const int ProtocolVersion;
429   /// The version of the class ABI.  This value is used in the class structure
430   /// and indicates how various fields should be interpreted.
431   const int ClassABIVersion;
432   /// Generates an instance variable list structure.  This is a structure
433   /// containing a size and an array of structures containing instance variable
434   /// metadata.  This is used purely for introspection in the fragile ABI.  In
435   /// the non-fragile ABI, it's used for instance variable fixup.
436   virtual llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
437                              ArrayRef<llvm::Constant *> IvarTypes,
438                              ArrayRef<llvm::Constant *> IvarOffsets,
439                              ArrayRef<llvm::Constant *> IvarAlign,
440                              ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership);
441 
442   /// Generates a method list structure.  This is a structure containing a size
443   /// and an array of structures containing method metadata.
444   ///
445   /// This structure is used by both classes and categories, and contains a next
446   /// pointer allowing them to be chained together in a linked list.
447   llvm::Constant *GenerateMethodList(StringRef ClassName,
448       StringRef CategoryName,
449       ArrayRef<const ObjCMethodDecl*> Methods,
450       bool isClassMethodList);
451 
452   /// Emits an empty protocol.  This is used for \@protocol() where no protocol
453   /// is found.  The runtime will (hopefully) fix up the pointer to refer to the
454   /// real protocol.
455   virtual llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName);
456 
457   /// Generates a list of property metadata structures.  This follows the same
458   /// pattern as method and instance variable metadata lists.
459   llvm::Constant *GeneratePropertyList(const Decl *Container,
460       const ObjCContainerDecl *OCD,
461       bool isClassProperty=false,
462       bool protocolOptionalProperties=false);
463 
464   /// Generates a list of referenced protocols.  Classes, categories, and
465   /// protocols all use this structure.
466   llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
467 
468   /// To ensure that all protocols are seen by the runtime, we add a category on
469   /// a class defined in the runtime, declaring no methods, but adopting the
470   /// protocols.  This is a horribly ugly hack, but it allows us to collect all
471   /// of the protocols without changing the ABI.
472   void GenerateProtocolHolderCategory();
473 
474   /// Generates a class structure.
475   llvm::Constant *GenerateClassStructure(
476       llvm::Constant *MetaClass,
477       llvm::Constant *SuperClass,
478       unsigned info,
479       const char *Name,
480       llvm::Constant *Version,
481       llvm::Constant *InstanceSize,
482       llvm::Constant *IVars,
483       llvm::Constant *Methods,
484       llvm::Constant *Protocols,
485       llvm::Constant *IvarOffsets,
486       llvm::Constant *Properties,
487       llvm::Constant *StrongIvarBitmap,
488       llvm::Constant *WeakIvarBitmap,
489       bool isMeta=false);
490 
491   /// Generates a method list.  This is used by protocols to define the required
492   /// and optional methods.
493   virtual llvm::Constant *GenerateProtocolMethodList(
494       ArrayRef<const ObjCMethodDecl*> Methods);
495   /// Emits optional and required method lists.
496   template<class T>
EmitProtocolMethodList(T && Methods,llvm::Constant * & Required,llvm::Constant * & Optional)497   void EmitProtocolMethodList(T &&Methods, llvm::Constant *&Required,
498       llvm::Constant *&Optional) {
499     SmallVector<const ObjCMethodDecl*, 16> RequiredMethods;
500     SmallVector<const ObjCMethodDecl*, 16> OptionalMethods;
501     for (const auto *I : Methods)
502       if (I->isOptional())
503         OptionalMethods.push_back(I);
504       else
505         RequiredMethods.push_back(I);
506     Required = GenerateProtocolMethodList(RequiredMethods);
507     Optional = GenerateProtocolMethodList(OptionalMethods);
508   }
509 
510   /// Returns a selector with the specified type encoding.  An empty string is
511   /// used to return an untyped selector (with the types field set to NULL).
512   virtual llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
513                                         const std::string &TypeEncoding);
514 
515   /// Returns the name of ivar offset variables.  In the GNUstep v1 ABI, this
516   /// contains the class and ivar names, in the v2 ABI this contains the type
517   /// encoding as well.
GetIVarOffsetVariableName(const ObjCInterfaceDecl * ID,const ObjCIvarDecl * Ivar)518   virtual std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
519                                                 const ObjCIvarDecl *Ivar) {
520     const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
521       + '.' + Ivar->getNameAsString();
522     return Name;
523   }
524   /// Returns the variable used to store the offset of an instance variable.
525   llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
526       const ObjCIvarDecl *Ivar);
527   /// Emits a reference to a class.  This allows the linker to object if there
528   /// is no class of the matching name.
529   void EmitClassRef(const std::string &className);
530 
531   /// Emits a pointer to the named class
532   virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
533                                      const std::string &Name, bool isWeak);
534 
535   /// Looks up the method for sending a message to the specified object.  This
536   /// mechanism differs between the GCC and GNU runtimes, so this method must be
537   /// overridden in subclasses.
538   virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
539                                  llvm::Value *&Receiver,
540                                  llvm::Value *cmd,
541                                  llvm::MDNode *node,
542                                  MessageSendInfo &MSI) = 0;
543 
544   /// Looks up the method for sending a message to a superclass.  This
545   /// mechanism differs between the GCC and GNU runtimes, so this method must
546   /// be overridden in subclasses.
547   virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
548                                       Address ObjCSuper,
549                                       llvm::Value *cmd,
550                                       MessageSendInfo &MSI) = 0;
551 
552   /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
553   /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
554   /// bits set to their values, LSB first, while larger ones are stored in a
555   /// structure of this / form:
556   ///
557   /// struct { int32_t length; int32_t values[length]; };
558   ///
559   /// The values in the array are stored in host-endian format, with the least
560   /// significant bit being assumed to come first in the bitfield.  Therefore,
561   /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
562   /// while a bitfield / with the 63rd bit set will be 1<<64.
563   llvm::Constant *MakeBitField(ArrayRef<bool> bits);
564 
565 public:
566   CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
567       unsigned protocolClassVersion, unsigned classABI=1);
568 
569   ConstantAddress GenerateConstantString(const StringLiteral *) override;
570 
571   RValue
572   GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
573                       QualType ResultType, Selector Sel,
574                       llvm::Value *Receiver, const CallArgList &CallArgs,
575                       const ObjCInterfaceDecl *Class,
576                       const ObjCMethodDecl *Method) override;
577   RValue
578   GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
579                            QualType ResultType, Selector Sel,
580                            const ObjCInterfaceDecl *Class,
581                            bool isCategoryImpl, llvm::Value *Receiver,
582                            bool IsClassMessage, const CallArgList &CallArgs,
583                            const ObjCMethodDecl *Method) override;
584   llvm::Value *GetClass(CodeGenFunction &CGF,
585                         const ObjCInterfaceDecl *OID) override;
586   llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
587   Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
588   llvm::Value *GetSelector(CodeGenFunction &CGF,
589                            const ObjCMethodDecl *Method) override;
GetConstantSelector(Selector Sel,const std::string & TypeEncoding)590   virtual llvm::Constant *GetConstantSelector(Selector Sel,
591                                               const std::string &TypeEncoding) {
592     llvm_unreachable("Runtime unable to generate constant selector");
593   }
GetConstantSelector(const ObjCMethodDecl * M)594   llvm::Constant *GetConstantSelector(const ObjCMethodDecl *M) {
595     return GetConstantSelector(M->getSelector(),
596         CGM.getContext().getObjCEncodingForMethodDecl(M));
597   }
598   llvm::Constant *GetEHType(QualType T) override;
599 
600   llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
601                                  const ObjCContainerDecl *CD) override;
602 
603   // Map to unify direct method definitions.
604   llvm::DenseMap<const ObjCMethodDecl *, llvm::Function *>
605       DirectMethodDefinitions;
606   void GenerateDirectMethodPrologue(CodeGenFunction &CGF, llvm::Function *Fn,
607                                     const ObjCMethodDecl *OMD,
608                                     const ObjCContainerDecl *CD) override;
609   void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
610   void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
611   void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
612   llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
613                                    const ObjCProtocolDecl *PD) override;
614   void GenerateProtocol(const ObjCProtocolDecl *PD) override;
615 
616   virtual llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD);
617 
GetOrEmitProtocol(const ObjCProtocolDecl * PD)618   llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override {
619     return GenerateProtocolRef(PD);
620   }
621 
622   llvm::Function *ModuleInitFunction() override;
623   llvm::FunctionCallee GetPropertyGetFunction() override;
624   llvm::FunctionCallee GetPropertySetFunction() override;
625   llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
626                                                        bool copy) override;
627   llvm::FunctionCallee GetSetStructFunction() override;
628   llvm::FunctionCallee GetGetStructFunction() override;
629   llvm::FunctionCallee GetCppAtomicObjectGetFunction() override;
630   llvm::FunctionCallee GetCppAtomicObjectSetFunction() override;
631   llvm::FunctionCallee EnumerationMutationFunction() override;
632 
633   void EmitTryStmt(CodeGenFunction &CGF,
634                    const ObjCAtTryStmt &S) override;
635   void EmitSynchronizedStmt(CodeGenFunction &CGF,
636                             const ObjCAtSynchronizedStmt &S) override;
637   void EmitThrowStmt(CodeGenFunction &CGF,
638                      const ObjCAtThrowStmt &S,
639                      bool ClearInsertionPoint=true) override;
640   llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
641                                  Address AddrWeakObj) override;
642   void EmitObjCWeakAssign(CodeGenFunction &CGF,
643                           llvm::Value *src, Address dst) override;
644   void EmitObjCGlobalAssign(CodeGenFunction &CGF,
645                             llvm::Value *src, Address dest,
646                             bool threadlocal=false) override;
647   void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
648                           Address dest, llvm::Value *ivarOffset) override;
649   void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
650                                 llvm::Value *src, Address dest) override;
651   void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
652                                 Address SrcPtr,
653                                 llvm::Value *Size) override;
654   LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
655                               llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
656                               unsigned CVRQualifiers) override;
657   llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
658                               const ObjCInterfaceDecl *Interface,
659                               const ObjCIvarDecl *Ivar) override;
660   llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
BuildGCBlockLayout(CodeGenModule & CGM,const CGBlockInfo & blockInfo)661   llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
662                                      const CGBlockInfo &blockInfo) override {
663     return NULLPtr;
664   }
BuildRCBlockLayout(CodeGenModule & CGM,const CGBlockInfo & blockInfo)665   llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
666                                      const CGBlockInfo &blockInfo) override {
667     return NULLPtr;
668   }
669 
BuildByrefLayout(CodeGenModule & CGM,QualType T)670   llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
671     return NULLPtr;
672   }
673 };
674 
675 /// Class representing the legacy GCC Objective-C ABI.  This is the default when
676 /// -fobjc-nonfragile-abi is not specified.
677 ///
678 /// The GCC ABI target actually generates code that is approximately compatible
679 /// with the new GNUstep runtime ABI, but refrains from using any features that
680 /// would not work with the GCC runtime.  For example, clang always generates
681 /// the extended form of the class structure, and the extra fields are simply
682 /// ignored by GCC libobjc.
683 class CGObjCGCC : public CGObjCGNU {
684   /// The GCC ABI message lookup function.  Returns an IMP pointing to the
685   /// method implementation for this message.
686   LazyRuntimeFunction MsgLookupFn;
687   /// The GCC ABI superclass message lookup function.  Takes a pointer to a
688   /// structure describing the receiver and the class, and a selector as
689   /// arguments.  Returns the IMP for the corresponding method.
690   LazyRuntimeFunction MsgLookupSuperFn;
691 
692 protected:
LookupIMP(CodeGenFunction & CGF,llvm::Value * & Receiver,llvm::Value * cmd,llvm::MDNode * node,MessageSendInfo & MSI)693   llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
694                          llvm::Value *cmd, llvm::MDNode *node,
695                          MessageSendInfo &MSI) override {
696     CGBuilderTy &Builder = CGF.Builder;
697     llvm::Value *args[] = {
698             EnforceType(Builder, Receiver, IdTy),
699             EnforceType(Builder, cmd, SelectorTy) };
700     llvm::CallBase *imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
701     imp->setMetadata(msgSendMDKind, node);
702     return imp;
703   }
704 
LookupIMPSuper(CodeGenFunction & CGF,Address ObjCSuper,llvm::Value * cmd,MessageSendInfo & MSI)705   llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
706                               llvm::Value *cmd, MessageSendInfo &MSI) override {
707     CGBuilderTy &Builder = CGF.Builder;
708     llvm::Value *lookupArgs[] = {
709         EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd};
710     return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
711   }
712 
713 public:
CGObjCGCC(CodeGenModule & Mod)714   CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
715     // IMP objc_msg_lookup(id, SEL);
716     MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
717     // IMP objc_msg_lookup_super(struct objc_super*, SEL);
718     MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
719                           PtrToObjCSuperTy, SelectorTy);
720   }
721 };
722 
723 /// Class used when targeting the new GNUstep runtime ABI.
724 class CGObjCGNUstep : public CGObjCGNU {
725     /// The slot lookup function.  Returns a pointer to a cacheable structure
726     /// that contains (among other things) the IMP.
727     LazyRuntimeFunction SlotLookupFn;
728     /// The GNUstep ABI superclass message lookup function.  Takes a pointer to
729     /// a structure describing the receiver and the class, and a selector as
730     /// arguments.  Returns the slot for the corresponding method.  Superclass
731     /// message lookup rarely changes, so this is a good caching opportunity.
732     LazyRuntimeFunction SlotLookupSuperFn;
733     /// Specialised function for setting atomic retain properties
734     LazyRuntimeFunction SetPropertyAtomic;
735     /// Specialised function for setting atomic copy properties
736     LazyRuntimeFunction SetPropertyAtomicCopy;
737     /// Specialised function for setting nonatomic retain properties
738     LazyRuntimeFunction SetPropertyNonAtomic;
739     /// Specialised function for setting nonatomic copy properties
740     LazyRuntimeFunction SetPropertyNonAtomicCopy;
741     /// Function to perform atomic copies of C++ objects with nontrivial copy
742     /// constructors from Objective-C ivars.
743     LazyRuntimeFunction CxxAtomicObjectGetFn;
744     /// Function to perform atomic copies of C++ objects with nontrivial copy
745     /// constructors to Objective-C ivars.
746     LazyRuntimeFunction CxxAtomicObjectSetFn;
747     /// Type of a slot structure pointer.  This is returned by the various
748     /// lookup functions.
749     llvm::Type *SlotTy;
750     /// Type of a slot structure.
751     llvm::Type *SlotStructTy;
752 
753   public:
754     llvm::Constant *GetEHType(QualType T) override;
755 
756   protected:
LookupIMP(CodeGenFunction & CGF,llvm::Value * & Receiver,llvm::Value * cmd,llvm::MDNode * node,MessageSendInfo & MSI)757     llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
758                            llvm::Value *cmd, llvm::MDNode *node,
759                            MessageSendInfo &MSI) override {
760       CGBuilderTy &Builder = CGF.Builder;
761       llvm::FunctionCallee LookupFn = SlotLookupFn;
762 
763       // Store the receiver on the stack so that we can reload it later
764       Address ReceiverPtr =
765         CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
766       Builder.CreateStore(Receiver, ReceiverPtr);
767 
768       llvm::Value *self;
769 
770       if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
771         self = CGF.LoadObjCSelf();
772       } else {
773         self = llvm::ConstantPointerNull::get(IdTy);
774       }
775 
776       // The lookup function is guaranteed not to capture the receiver pointer.
777       if (auto *LookupFn2 = dyn_cast<llvm::Function>(LookupFn.getCallee()))
778         LookupFn2->addParamAttr(0, llvm::Attribute::NoCapture);
779 
780       llvm::Value *args[] = {
781               EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
782               EnforceType(Builder, cmd, SelectorTy),
783               EnforceType(Builder, self, IdTy) };
784       llvm::CallBase *slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
785       slot->setOnlyReadsMemory();
786       slot->setMetadata(msgSendMDKind, node);
787 
788       // Load the imp from the slot
789       llvm::Value *imp = Builder.CreateAlignedLoad(
790           IMPTy, Builder.CreateStructGEP(SlotStructTy, slot, 4),
791           CGF.getPointerAlign());
792 
793       // The lookup function may have changed the receiver, so make sure we use
794       // the new one.
795       Receiver = Builder.CreateLoad(ReceiverPtr, true);
796       return imp;
797     }
798 
LookupIMPSuper(CodeGenFunction & CGF,Address ObjCSuper,llvm::Value * cmd,MessageSendInfo & MSI)799     llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
800                                 llvm::Value *cmd,
801                                 MessageSendInfo &MSI) override {
802       CGBuilderTy &Builder = CGF.Builder;
803       llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
804 
805       llvm::CallInst *slot =
806         CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
807       slot->setOnlyReadsMemory();
808 
809       return Builder.CreateAlignedLoad(
810           IMPTy, Builder.CreateStructGEP(SlotStructTy, slot, 4),
811           CGF.getPointerAlign());
812     }
813 
814   public:
CGObjCGNUstep(CodeGenModule & Mod)815     CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 9, 3, 1) {}
CGObjCGNUstep(CodeGenModule & Mod,unsigned ABI,unsigned ProtocolABI,unsigned ClassABI)816     CGObjCGNUstep(CodeGenModule &Mod, unsigned ABI, unsigned ProtocolABI,
817         unsigned ClassABI) :
818       CGObjCGNU(Mod, ABI, ProtocolABI, ClassABI) {
819       const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
820 
821       SlotStructTy = llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);
822       SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
823       // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
824       SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
825                         SelectorTy, IdTy);
826       // Slot_t objc_slot_lookup_super(struct objc_super*, SEL);
827       SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
828                              PtrToObjCSuperTy, SelectorTy);
829       // If we're in ObjC++ mode, then we want to make
830       llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
831       if (usesCxxExceptions) {
832         // void *__cxa_begin_catch(void *e)
833         EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
834         // void __cxa_end_catch(void)
835         ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
836         // void objc_exception_rethrow(void*)
837         ExceptionReThrowFn.init(&CGM, "__cxa_rethrow", PtrTy);
838       } else if (usesSEHExceptions) {
839         // void objc_exception_rethrow(void)
840         ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
841       } else if (CGM.getLangOpts().CPlusPlus) {
842         // void *__cxa_begin_catch(void *e)
843         EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
844         // void __cxa_end_catch(void)
845         ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
846         // void _Unwind_Resume_or_Rethrow(void*)
847         ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
848                                 PtrTy);
849       } else if (R.getVersion() >= VersionTuple(1, 7)) {
850         // id objc_begin_catch(void *e)
851         EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy);
852         // void objc_end_catch(void)
853         ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy);
854         // void _Unwind_Resume_or_Rethrow(void*)
855         ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy);
856       }
857       SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
858                              SelectorTy, IdTy, PtrDiffTy);
859       SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
860                                  IdTy, SelectorTy, IdTy, PtrDiffTy);
861       SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
862                                 IdTy, SelectorTy, IdTy, PtrDiffTy);
863       SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
864                                     VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy);
865       // void objc_setCppObjectAtomic(void *dest, const void *src, void
866       // *helper);
867       CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
868                                 PtrTy, PtrTy);
869       // void objc_getCppObjectAtomic(void *dest, const void *src, void
870       // *helper);
871       CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
872                                 PtrTy, PtrTy);
873     }
874 
GetCppAtomicObjectGetFunction()875     llvm::FunctionCallee GetCppAtomicObjectGetFunction() override {
876       // The optimised functions were added in version 1.7 of the GNUstep
877       // runtime.
878       assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
879           VersionTuple(1, 7));
880       return CxxAtomicObjectGetFn;
881     }
882 
GetCppAtomicObjectSetFunction()883     llvm::FunctionCallee GetCppAtomicObjectSetFunction() override {
884       // The optimised functions were added in version 1.7 of the GNUstep
885       // runtime.
886       assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
887           VersionTuple(1, 7));
888       return CxxAtomicObjectSetFn;
889     }
890 
GetOptimizedPropertySetFunction(bool atomic,bool copy)891     llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
892                                                          bool copy) override {
893       // The optimised property functions omit the GC check, and so are not
894       // safe to use in GC mode.  The standard functions are fast in GC mode,
895       // so there is less advantage in using them.
896       assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
897       // The optimised functions were added in version 1.7 of the GNUstep
898       // runtime.
899       assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
900           VersionTuple(1, 7));
901 
902       if (atomic) {
903         if (copy) return SetPropertyAtomicCopy;
904         return SetPropertyAtomic;
905       }
906 
907       return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
908     }
909 };
910 
911 /// GNUstep Objective-C ABI version 2 implementation.
912 /// This is the ABI that provides a clean break with the legacy GCC ABI and
913 /// cleans up a number of things that were added to work around 1980s linkers.
914 class CGObjCGNUstep2 : public CGObjCGNUstep {
915   enum SectionKind
916   {
917     SelectorSection = 0,
918     ClassSection,
919     ClassReferenceSection,
920     CategorySection,
921     ProtocolSection,
922     ProtocolReferenceSection,
923     ClassAliasSection,
924     ConstantStringSection
925   };
926   /// The subset of `objc_class_flags` used at compile time.
927   enum ClassFlags {
928     /// This is a metaclass
929     ClassFlagMeta = (1 << 0),
930     /// This class has been initialised by the runtime (+initialize has been
931     /// sent if necessary).
932     ClassFlagInitialized = (1 << 8),
933   };
934   static const char *const SectionsBaseNames[8];
935   static const char *const PECOFFSectionsBaseNames[8];
936   template<SectionKind K>
sectionName()937   std::string sectionName() {
938     if (CGM.getTriple().isOSBinFormatCOFF()) {
939       std::string name(PECOFFSectionsBaseNames[K]);
940       name += "$m";
941       return name;
942     }
943     return SectionsBaseNames[K];
944   }
945   /// The GCC ABI superclass message lookup function.  Takes a pointer to a
946   /// structure describing the receiver and the class, and a selector as
947   /// arguments.  Returns the IMP for the corresponding method.
948   LazyRuntimeFunction MsgLookupSuperFn;
949   /// Function to ensure that +initialize is sent to a class.
950   LazyRuntimeFunction SentInitializeFn;
951   /// A flag indicating if we've emitted at least one protocol.
952   /// If we haven't, then we need to emit an empty protocol, to ensure that the
953   /// __start__objc_protocols and __stop__objc_protocols sections exist.
954   bool EmittedProtocol = false;
955   /// A flag indicating if we've emitted at least one protocol reference.
956   /// If we haven't, then we need to emit an empty protocol, to ensure that the
957   /// __start__objc_protocol_refs and __stop__objc_protocol_refs sections
958   /// exist.
959   bool EmittedProtocolRef = false;
960   /// A flag indicating if we've emitted at least one class.
961   /// If we haven't, then we need to emit an empty protocol, to ensure that the
962   /// __start__objc_classes and __stop__objc_classes sections / exist.
963   bool EmittedClass = false;
964   /// Generate the name of a symbol for a reference to a class.  Accesses to
965   /// classes should be indirected via this.
966 
967   typedef std::pair<std::string, std::pair<llvm::GlobalVariable*, int>>
968       EarlyInitPair;
969   std::vector<EarlyInitPair> EarlyInitList;
970 
SymbolForClassRef(StringRef Name,bool isWeak)971   std::string SymbolForClassRef(StringRef Name, bool isWeak) {
972     if (isWeak)
973       return (ManglePublicSymbol("OBJC_WEAK_REF_CLASS_") + Name).str();
974     else
975       return (ManglePublicSymbol("OBJC_REF_CLASS_") + Name).str();
976   }
977   /// Generate the name of a class symbol.
SymbolForClass(StringRef Name)978   std::string SymbolForClass(StringRef Name) {
979     return (ManglePublicSymbol("OBJC_CLASS_") + Name).str();
980   }
CallRuntimeFunction(CGBuilderTy & B,StringRef FunctionName,ArrayRef<llvm::Value * > Args)981   void CallRuntimeFunction(CGBuilderTy &B, StringRef FunctionName,
982       ArrayRef<llvm::Value*> Args) {
983     SmallVector<llvm::Type *,8> Types;
984     for (auto *Arg : Args)
985       Types.push_back(Arg->getType());
986     llvm::FunctionType *FT = llvm::FunctionType::get(B.getVoidTy(), Types,
987         false);
988     llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FT, FunctionName);
989     B.CreateCall(Fn, Args);
990   }
991 
GenerateConstantString(const StringLiteral * SL)992   ConstantAddress GenerateConstantString(const StringLiteral *SL) override {
993 
994     auto Str = SL->getString();
995     CharUnits Align = CGM.getPointerAlign();
996 
997     // Look for an existing one
998     llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
999     if (old != ObjCStrings.end())
1000       return ConstantAddress(old->getValue(), IdElemTy, Align);
1001 
1002     bool isNonASCII = SL->containsNonAscii();
1003 
1004     auto LiteralLength = SL->getLength();
1005 
1006     if ((CGM.getTarget().getPointerWidth(LangAS::Default) == 64) &&
1007         (LiteralLength < 9) && !isNonASCII) {
1008       // Tiny strings are only used on 64-bit platforms.  They store 8 7-bit
1009       // ASCII characters in the high 56 bits, followed by a 4-bit length and a
1010       // 3-bit tag (which is always 4).
1011       uint64_t str = 0;
1012       // Fill in the characters
1013       for (unsigned i=0 ; i<LiteralLength ; i++)
1014         str |= ((uint64_t)SL->getCodeUnit(i)) << ((64 - 4 - 3) - (i*7));
1015       // Fill in the length
1016       str |= LiteralLength << 3;
1017       // Set the tag
1018       str |= 4;
1019       auto *ObjCStr = llvm::ConstantExpr::getIntToPtr(
1020           llvm::ConstantInt::get(Int64Ty, str), IdTy);
1021       ObjCStrings[Str] = ObjCStr;
1022       return ConstantAddress(ObjCStr, IdElemTy, Align);
1023     }
1024 
1025     StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
1026 
1027     if (StringClass.empty()) StringClass = "NSConstantString";
1028 
1029     std::string Sym = SymbolForClass(StringClass);
1030 
1031     llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1032 
1033     if (!isa) {
1034       isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1035               llvm::GlobalValue::ExternalLinkage, nullptr, Sym);
1036       if (CGM.getTriple().isOSBinFormatCOFF()) {
1037         cast<llvm::GlobalValue>(isa)->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1038       }
1039     }
1040 
1041     //  struct
1042     //  {
1043     //    Class isa;
1044     //    uint32_t flags;
1045     //    uint32_t length; // Number of codepoints
1046     //    uint32_t size; // Number of bytes
1047     //    uint32_t hash;
1048     //    const char *data;
1049     //  };
1050 
1051     ConstantInitBuilder Builder(CGM);
1052     auto Fields = Builder.beginStruct();
1053     if (!CGM.getTriple().isOSBinFormatCOFF()) {
1054       Fields.add(isa);
1055     } else {
1056       Fields.addNullPointer(PtrTy);
1057     }
1058     // For now, all non-ASCII strings are represented as UTF-16.  As such, the
1059     // number of bytes is simply double the number of UTF-16 codepoints.  In
1060     // ASCII strings, the number of bytes is equal to the number of non-ASCII
1061     // codepoints.
1062     if (isNonASCII) {
1063       unsigned NumU8CodeUnits = Str.size();
1064       // A UTF-16 representation of a unicode string contains at most the same
1065       // number of code units as a UTF-8 representation.  Allocate that much
1066       // space, plus one for the final null character.
1067       SmallVector<llvm::UTF16, 128> ToBuf(NumU8CodeUnits + 1);
1068       const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)Str.data();
1069       llvm::UTF16 *ToPtr = &ToBuf[0];
1070       (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumU8CodeUnits,
1071           &ToPtr, ToPtr + NumU8CodeUnits, llvm::strictConversion);
1072       uint32_t StringLength = ToPtr - &ToBuf[0];
1073       // Add null terminator
1074       *ToPtr = 0;
1075       // Flags: 2 indicates UTF-16 encoding
1076       Fields.addInt(Int32Ty, 2);
1077       // Number of UTF-16 codepoints
1078       Fields.addInt(Int32Ty, StringLength);
1079       // Number of bytes
1080       Fields.addInt(Int32Ty, StringLength * 2);
1081       // Hash.  Not currently initialised by the compiler.
1082       Fields.addInt(Int32Ty, 0);
1083       // pointer to the data string.
1084       auto Arr = llvm::ArrayRef(&ToBuf[0], ToPtr + 1);
1085       auto *C = llvm::ConstantDataArray::get(VMContext, Arr);
1086       auto *Buffer = new llvm::GlobalVariable(TheModule, C->getType(),
1087           /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, C, ".str");
1088       Buffer->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1089       Fields.add(Buffer);
1090     } else {
1091       // Flags: 0 indicates ASCII encoding
1092       Fields.addInt(Int32Ty, 0);
1093       // Number of UTF-16 codepoints, each ASCII byte is a UTF-16 codepoint
1094       Fields.addInt(Int32Ty, Str.size());
1095       // Number of bytes
1096       Fields.addInt(Int32Ty, Str.size());
1097       // Hash.  Not currently initialised by the compiler.
1098       Fields.addInt(Int32Ty, 0);
1099       // Data pointer
1100       Fields.add(MakeConstantString(Str));
1101     }
1102     std::string StringName;
1103     bool isNamed = !isNonASCII;
1104     if (isNamed) {
1105       StringName = ".objc_str_";
1106       for (int i=0,e=Str.size() ; i<e ; ++i) {
1107         unsigned char c = Str[i];
1108         if (isalnum(c))
1109           StringName += c;
1110         else if (c == ' ')
1111           StringName += '_';
1112         else {
1113           isNamed = false;
1114           break;
1115         }
1116       }
1117     }
1118     llvm::GlobalVariable *ObjCStrGV =
1119       Fields.finishAndCreateGlobal(
1120           isNamed ? StringRef(StringName) : ".objc_string",
1121           Align, false, isNamed ? llvm::GlobalValue::LinkOnceODRLinkage
1122                                 : llvm::GlobalValue::PrivateLinkage);
1123     ObjCStrGV->setSection(sectionName<ConstantStringSection>());
1124     if (isNamed) {
1125       ObjCStrGV->setComdat(TheModule.getOrInsertComdat(StringName));
1126       ObjCStrGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1127     }
1128     if (CGM.getTriple().isOSBinFormatCOFF()) {
1129       std::pair<llvm::GlobalVariable*, int> v{ObjCStrGV, 0};
1130       EarlyInitList.emplace_back(Sym, v);
1131     }
1132     ObjCStrings[Str] = ObjCStrGV;
1133     ConstantStrings.push_back(ObjCStrGV);
1134     return ConstantAddress(ObjCStrGV, IdElemTy, Align);
1135   }
1136 
PushProperty(ConstantArrayBuilder & PropertiesArray,const ObjCPropertyDecl * property,const Decl * OCD,bool isSynthesized=true,bool isDynamic=true)1137   void PushProperty(ConstantArrayBuilder &PropertiesArray,
1138             const ObjCPropertyDecl *property,
1139             const Decl *OCD,
1140             bool isSynthesized=true, bool
1141             isDynamic=true) override {
1142     // struct objc_property
1143     // {
1144     //   const char *name;
1145     //   const char *attributes;
1146     //   const char *type;
1147     //   SEL getter;
1148     //   SEL setter;
1149     // };
1150     auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
1151     ASTContext &Context = CGM.getContext();
1152     Fields.add(MakeConstantString(property->getNameAsString()));
1153     std::string TypeStr =
1154       CGM.getContext().getObjCEncodingForPropertyDecl(property, OCD);
1155     Fields.add(MakeConstantString(TypeStr));
1156     std::string typeStr;
1157     Context.getObjCEncodingForType(property->getType(), typeStr);
1158     Fields.add(MakeConstantString(typeStr));
1159     auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
1160       if (accessor) {
1161         std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
1162         Fields.add(GetConstantSelector(accessor->getSelector(), TypeStr));
1163       } else {
1164         Fields.add(NULLPtr);
1165       }
1166     };
1167     addPropertyMethod(property->getGetterMethodDecl());
1168     addPropertyMethod(property->getSetterMethodDecl());
1169     Fields.finishAndAddTo(PropertiesArray);
1170   }
1171 
1172   llvm::Constant *
GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl * > Methods)1173   GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) override {
1174     // struct objc_protocol_method_description
1175     // {
1176     //   SEL selector;
1177     //   const char *types;
1178     // };
1179     llvm::StructType *ObjCMethodDescTy =
1180       llvm::StructType::get(CGM.getLLVMContext(),
1181           { PtrToInt8Ty, PtrToInt8Ty });
1182     ASTContext &Context = CGM.getContext();
1183     ConstantInitBuilder Builder(CGM);
1184     // struct objc_protocol_method_description_list
1185     // {
1186     //   int count;
1187     //   int size;
1188     //   struct objc_protocol_method_description methods[];
1189     // };
1190     auto MethodList = Builder.beginStruct();
1191     // int count;
1192     MethodList.addInt(IntTy, Methods.size());
1193     // int size; // sizeof(struct objc_method_description)
1194     llvm::DataLayout td(&TheModule);
1195     MethodList.addInt(IntTy, td.getTypeSizeInBits(ObjCMethodDescTy) /
1196         CGM.getContext().getCharWidth());
1197     // struct objc_method_description[]
1198     auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
1199     for (auto *M : Methods) {
1200       auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
1201       Method.add(CGObjCGNU::GetConstantSelector(M));
1202       Method.add(GetTypeString(Context.getObjCEncodingForMethodDecl(M, true)));
1203       Method.finishAndAddTo(MethodArray);
1204     }
1205     MethodArray.finishAndAddTo(MethodList);
1206     return MethodList.finishAndCreateGlobal(".objc_protocol_method_list",
1207                                             CGM.getPointerAlign());
1208   }
GenerateCategoryProtocolList(const ObjCCategoryDecl * OCD)1209   llvm::Constant *GenerateCategoryProtocolList(const ObjCCategoryDecl *OCD)
1210     override {
1211     const auto &ReferencedProtocols = OCD->getReferencedProtocols();
1212     auto RuntimeProtocols = GetRuntimeProtocolList(ReferencedProtocols.begin(),
1213                                                    ReferencedProtocols.end());
1214     SmallVector<llvm::Constant *, 16> Protocols;
1215     for (const auto *PI : RuntimeProtocols)
1216       Protocols.push_back(GenerateProtocolRef(PI));
1217     return GenerateProtocolList(Protocols);
1218   }
1219 
LookupIMPSuper(CodeGenFunction & CGF,Address ObjCSuper,llvm::Value * cmd,MessageSendInfo & MSI)1220   llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
1221                               llvm::Value *cmd, MessageSendInfo &MSI) override {
1222     // Don't access the slot unless we're trying to cache the result.
1223     CGBuilderTy &Builder = CGF.Builder;
1224     llvm::Value *lookupArgs[] = {CGObjCGNU::EnforceType(Builder,
1225                                                         ObjCSuper.getPointer(),
1226                                                         PtrToObjCSuperTy),
1227                                  cmd};
1228     return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
1229   }
1230 
GetClassVar(StringRef Name,bool isWeak=false)1231   llvm::GlobalVariable *GetClassVar(StringRef Name, bool isWeak=false) {
1232     std::string SymbolName = SymbolForClassRef(Name, isWeak);
1233     auto *ClassSymbol = TheModule.getNamedGlobal(SymbolName);
1234     if (ClassSymbol)
1235       return ClassSymbol;
1236     ClassSymbol = new llvm::GlobalVariable(TheModule,
1237         IdTy, false, llvm::GlobalValue::ExternalLinkage,
1238         nullptr, SymbolName);
1239     // If this is a weak symbol, then we are creating a valid definition for
1240     // the symbol, pointing to a weak definition of the real class pointer.  If
1241     // this is not a weak reference, then we are expecting another compilation
1242     // unit to provide the real indirection symbol.
1243     if (isWeak)
1244       ClassSymbol->setInitializer(new llvm::GlobalVariable(TheModule,
1245           Int8Ty, false, llvm::GlobalValue::ExternalWeakLinkage,
1246           nullptr, SymbolForClass(Name)));
1247     else {
1248       if (CGM.getTriple().isOSBinFormatCOFF()) {
1249         IdentifierInfo &II = CGM.getContext().Idents.get(Name);
1250         TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
1251         DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
1252 
1253         const ObjCInterfaceDecl *OID = nullptr;
1254         for (const auto *Result : DC->lookup(&II))
1255           if ((OID = dyn_cast<ObjCInterfaceDecl>(Result)))
1256             break;
1257 
1258         // The first Interface we find may be a @class,
1259         // which should only be treated as the source of
1260         // truth in the absence of a true declaration.
1261         assert(OID && "Failed to find ObjCInterfaceDecl");
1262         const ObjCInterfaceDecl *OIDDef = OID->getDefinition();
1263         if (OIDDef != nullptr)
1264           OID = OIDDef;
1265 
1266         auto Storage = llvm::GlobalValue::DefaultStorageClass;
1267         if (OID->hasAttr<DLLImportAttr>())
1268           Storage = llvm::GlobalValue::DLLImportStorageClass;
1269         else if (OID->hasAttr<DLLExportAttr>())
1270           Storage = llvm::GlobalValue::DLLExportStorageClass;
1271 
1272         cast<llvm::GlobalValue>(ClassSymbol)->setDLLStorageClass(Storage);
1273       }
1274     }
1275     assert(ClassSymbol->getName() == SymbolName);
1276     return ClassSymbol;
1277   }
GetClassNamed(CodeGenFunction & CGF,const std::string & Name,bool isWeak)1278   llvm::Value *GetClassNamed(CodeGenFunction &CGF,
1279                              const std::string &Name,
1280                              bool isWeak) override {
1281     return CGF.Builder.CreateLoad(
1282         Address(GetClassVar(Name, isWeak), IdTy, CGM.getPointerAlign()));
1283   }
FlagsForOwnership(Qualifiers::ObjCLifetime Ownership)1284   int32_t FlagsForOwnership(Qualifiers::ObjCLifetime Ownership) {
1285     // typedef enum {
1286     //   ownership_invalid = 0,
1287     //   ownership_strong  = 1,
1288     //   ownership_weak    = 2,
1289     //   ownership_unsafe  = 3
1290     // } ivar_ownership;
1291     int Flag;
1292     switch (Ownership) {
1293       case Qualifiers::OCL_Strong:
1294           Flag = 1;
1295           break;
1296       case Qualifiers::OCL_Weak:
1297           Flag = 2;
1298           break;
1299       case Qualifiers::OCL_ExplicitNone:
1300           Flag = 3;
1301           break;
1302       case Qualifiers::OCL_None:
1303       case Qualifiers::OCL_Autoreleasing:
1304         assert(Ownership != Qualifiers::OCL_Autoreleasing);
1305         Flag = 0;
1306     }
1307     return Flag;
1308   }
GenerateIvarList(ArrayRef<llvm::Constant * > IvarNames,ArrayRef<llvm::Constant * > IvarTypes,ArrayRef<llvm::Constant * > IvarOffsets,ArrayRef<llvm::Constant * > IvarAlign,ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership)1309   llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1310                    ArrayRef<llvm::Constant *> IvarTypes,
1311                    ArrayRef<llvm::Constant *> IvarOffsets,
1312                    ArrayRef<llvm::Constant *> IvarAlign,
1313                    ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) override {
1314     llvm_unreachable("Method should not be called!");
1315   }
1316 
GenerateEmptyProtocol(StringRef ProtocolName)1317   llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName) override {
1318     std::string Name = SymbolForProtocol(ProtocolName);
1319     auto *GV = TheModule.getGlobalVariable(Name);
1320     if (!GV) {
1321       // Emit a placeholder symbol.
1322       GV = new llvm::GlobalVariable(TheModule, ProtocolTy, false,
1323           llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1324       GV->setAlignment(CGM.getPointerAlign().getAsAlign());
1325     }
1326     return GV;
1327   }
1328 
1329   /// Existing protocol references.
1330   llvm::StringMap<llvm::Constant*> ExistingProtocolRefs;
1331 
GenerateProtocolRef(CodeGenFunction & CGF,const ObjCProtocolDecl * PD)1332   llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1333                                    const ObjCProtocolDecl *PD) override {
1334     auto Name = PD->getNameAsString();
1335     auto *&Ref = ExistingProtocolRefs[Name];
1336     if (!Ref) {
1337       auto *&Protocol = ExistingProtocols[Name];
1338       if (!Protocol)
1339         Protocol = GenerateProtocolRef(PD);
1340       std::string RefName = SymbolForProtocolRef(Name);
1341       assert(!TheModule.getGlobalVariable(RefName));
1342       // Emit a reference symbol.
1343       auto GV = new llvm::GlobalVariable(TheModule, ProtocolPtrTy, false,
1344                                          llvm::GlobalValue::LinkOnceODRLinkage,
1345                                          Protocol, RefName);
1346       GV->setComdat(TheModule.getOrInsertComdat(RefName));
1347       GV->setSection(sectionName<ProtocolReferenceSection>());
1348       GV->setAlignment(CGM.getPointerAlign().getAsAlign());
1349       Ref = GV;
1350     }
1351     EmittedProtocolRef = true;
1352     return CGF.Builder.CreateAlignedLoad(ProtocolPtrTy, Ref,
1353                                          CGM.getPointerAlign());
1354   }
1355 
GenerateProtocolList(ArrayRef<llvm::Constant * > Protocols)1356   llvm::Constant *GenerateProtocolList(ArrayRef<llvm::Constant*> Protocols) {
1357     llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(ProtocolPtrTy,
1358         Protocols.size());
1359     llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1360         Protocols);
1361     ConstantInitBuilder builder(CGM);
1362     auto ProtocolBuilder = builder.beginStruct();
1363     ProtocolBuilder.addNullPointer(PtrTy);
1364     ProtocolBuilder.addInt(SizeTy, Protocols.size());
1365     ProtocolBuilder.add(ProtocolArray);
1366     return ProtocolBuilder.finishAndCreateGlobal(".objc_protocol_list",
1367         CGM.getPointerAlign(), false, llvm::GlobalValue::InternalLinkage);
1368   }
1369 
GenerateProtocol(const ObjCProtocolDecl * PD)1370   void GenerateProtocol(const ObjCProtocolDecl *PD) override {
1371     // Do nothing - we only emit referenced protocols.
1372   }
GenerateProtocolRef(const ObjCProtocolDecl * PD)1373   llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD) override {
1374     std::string ProtocolName = PD->getNameAsString();
1375     auto *&Protocol = ExistingProtocols[ProtocolName];
1376     if (Protocol)
1377       return Protocol;
1378 
1379     EmittedProtocol = true;
1380 
1381     auto SymName = SymbolForProtocol(ProtocolName);
1382     auto *OldGV = TheModule.getGlobalVariable(SymName);
1383 
1384     // Use the protocol definition, if there is one.
1385     if (const ObjCProtocolDecl *Def = PD->getDefinition())
1386       PD = Def;
1387     else {
1388       // If there is no definition, then create an external linkage symbol and
1389       // hope that someone else fills it in for us (and fail to link if they
1390       // don't).
1391       assert(!OldGV);
1392       Protocol = new llvm::GlobalVariable(TheModule, ProtocolTy,
1393         /*isConstant*/false,
1394         llvm::GlobalValue::ExternalLinkage, nullptr, SymName);
1395       return Protocol;
1396     }
1397 
1398     SmallVector<llvm::Constant*, 16> Protocols;
1399     auto RuntimeProtocols =
1400         GetRuntimeProtocolList(PD->protocol_begin(), PD->protocol_end());
1401     for (const auto *PI : RuntimeProtocols)
1402       Protocols.push_back(GenerateProtocolRef(PI));
1403     llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1404 
1405     // Collect information about methods
1406     llvm::Constant *InstanceMethodList, *OptionalInstanceMethodList;
1407     llvm::Constant *ClassMethodList, *OptionalClassMethodList;
1408     EmitProtocolMethodList(PD->instance_methods(), InstanceMethodList,
1409         OptionalInstanceMethodList);
1410     EmitProtocolMethodList(PD->class_methods(), ClassMethodList,
1411         OptionalClassMethodList);
1412 
1413     // The isa pointer must be set to a magic number so the runtime knows it's
1414     // the correct layout.
1415     ConstantInitBuilder builder(CGM);
1416     auto ProtocolBuilder = builder.beginStruct();
1417     ProtocolBuilder.add(llvm::ConstantExpr::getIntToPtr(
1418           llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1419     ProtocolBuilder.add(MakeConstantString(ProtocolName));
1420     ProtocolBuilder.add(ProtocolList);
1421     ProtocolBuilder.add(InstanceMethodList);
1422     ProtocolBuilder.add(ClassMethodList);
1423     ProtocolBuilder.add(OptionalInstanceMethodList);
1424     ProtocolBuilder.add(OptionalClassMethodList);
1425     // Required instance properties
1426     ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, false));
1427     // Optional instance properties
1428     ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, true));
1429     // Required class properties
1430     ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, false));
1431     // Optional class properties
1432     ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, true));
1433 
1434     auto *GV = ProtocolBuilder.finishAndCreateGlobal(SymName,
1435         CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
1436     GV->setSection(sectionName<ProtocolSection>());
1437     GV->setComdat(TheModule.getOrInsertComdat(SymName));
1438     if (OldGV) {
1439       OldGV->replaceAllUsesWith(GV);
1440       OldGV->removeFromParent();
1441       GV->setName(SymName);
1442     }
1443     Protocol = GV;
1444     return GV;
1445   }
GetTypedSelector(CodeGenFunction & CGF,Selector Sel,const std::string & TypeEncoding)1446   llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
1447                                 const std::string &TypeEncoding) override {
1448     return GetConstantSelector(Sel, TypeEncoding);
1449   }
GetSymbolNameForTypeEncoding(const std::string & TypeEncoding)1450   std::string GetSymbolNameForTypeEncoding(const std::string &TypeEncoding) {
1451     std::string MangledTypes = std::string(TypeEncoding);
1452     // @ is used as a special character in ELF symbol names (used for symbol
1453     // versioning), so mangle the name to not include it.  Replace it with a
1454     // character that is not a valid type encoding character (and, being
1455     // non-printable, never will be!)
1456     if (CGM.getTriple().isOSBinFormatELF())
1457       std::replace(MangledTypes.begin(), MangledTypes.end(), '@', '\1');
1458     // = in dll exported names causes lld to fail when linking on Windows.
1459     if (CGM.getTriple().isOSWindows())
1460       std::replace(MangledTypes.begin(), MangledTypes.end(), '=', '\2');
1461     return MangledTypes;
1462   }
GetTypeString(llvm::StringRef TypeEncoding)1463   llvm::Constant  *GetTypeString(llvm::StringRef TypeEncoding) {
1464     if (TypeEncoding.empty())
1465       return NULLPtr;
1466     std::string MangledTypes =
1467         GetSymbolNameForTypeEncoding(std::string(TypeEncoding));
1468     std::string TypesVarName = ".objc_sel_types_" + MangledTypes;
1469     auto *TypesGlobal = TheModule.getGlobalVariable(TypesVarName);
1470     if (!TypesGlobal) {
1471       llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
1472           TypeEncoding);
1473       auto *GV = new llvm::GlobalVariable(TheModule, Init->getType(),
1474           true, llvm::GlobalValue::LinkOnceODRLinkage, Init, TypesVarName);
1475       GV->setComdat(TheModule.getOrInsertComdat(TypesVarName));
1476       GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1477       TypesGlobal = GV;
1478     }
1479     return llvm::ConstantExpr::getGetElementPtr(TypesGlobal->getValueType(),
1480         TypesGlobal, Zeros);
1481   }
GetConstantSelector(Selector Sel,const std::string & TypeEncoding)1482   llvm::Constant *GetConstantSelector(Selector Sel,
1483                                       const std::string &TypeEncoding) override {
1484     std::string MangledTypes = GetSymbolNameForTypeEncoding(TypeEncoding);
1485     auto SelVarName = (StringRef(".objc_selector_") + Sel.getAsString() + "_" +
1486       MangledTypes).str();
1487     if (auto *GV = TheModule.getNamedGlobal(SelVarName))
1488       return GV;
1489     ConstantInitBuilder builder(CGM);
1490     auto SelBuilder = builder.beginStruct();
1491     SelBuilder.add(ExportUniqueString(Sel.getAsString(), ".objc_sel_name_",
1492           true));
1493     SelBuilder.add(GetTypeString(TypeEncoding));
1494     auto *GV = SelBuilder.finishAndCreateGlobal(SelVarName,
1495         CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1496     GV->setComdat(TheModule.getOrInsertComdat(SelVarName));
1497     GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1498     GV->setSection(sectionName<SelectorSection>());
1499     return GV;
1500   }
1501   llvm::StructType *emptyStruct = nullptr;
1502 
1503   /// Return pointers to the start and end of a section.  On ELF platforms, we
1504   /// use the __start_ and __stop_ symbols that GNU-compatible linkers will set
1505   /// to the start and end of section names, as long as those section names are
1506   /// valid identifiers and the symbols are referenced but not defined.  On
1507   /// Windows, we use the fact that MSVC-compatible linkers will lexically sort
1508   /// by subsections and place everything that we want to reference in a middle
1509   /// subsection and then insert zero-sized symbols in subsections a and z.
1510   std::pair<llvm::Constant*,llvm::Constant*>
GetSectionBounds(StringRef Section)1511   GetSectionBounds(StringRef Section) {
1512     if (CGM.getTriple().isOSBinFormatCOFF()) {
1513       if (emptyStruct == nullptr) {
1514         emptyStruct = llvm::StructType::create(VMContext, ".objc_section_sentinel");
1515         emptyStruct->setBody({}, /*isPacked*/true);
1516       }
1517       auto ZeroInit = llvm::Constant::getNullValue(emptyStruct);
1518       auto Sym = [&](StringRef Prefix, StringRef SecSuffix) {
1519         auto *Sym = new llvm::GlobalVariable(TheModule, emptyStruct,
1520             /*isConstant*/false,
1521             llvm::GlobalValue::LinkOnceODRLinkage, ZeroInit, Prefix +
1522             Section);
1523         Sym->setVisibility(llvm::GlobalValue::HiddenVisibility);
1524         Sym->setSection((Section + SecSuffix).str());
1525         Sym->setComdat(TheModule.getOrInsertComdat((Prefix +
1526             Section).str()));
1527         Sym->setAlignment(CGM.getPointerAlign().getAsAlign());
1528         return Sym;
1529       };
1530       return { Sym("__start_", "$a"), Sym("__stop", "$z") };
1531     }
1532     auto *Start = new llvm::GlobalVariable(TheModule, PtrTy,
1533         /*isConstant*/false,
1534         llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__start_") +
1535         Section);
1536     Start->setVisibility(llvm::GlobalValue::HiddenVisibility);
1537     auto *Stop = new llvm::GlobalVariable(TheModule, PtrTy,
1538         /*isConstant*/false,
1539         llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__stop_") +
1540         Section);
1541     Stop->setVisibility(llvm::GlobalValue::HiddenVisibility);
1542     return { Start, Stop };
1543   }
getCatchAllTypeInfo()1544   CatchTypeInfo getCatchAllTypeInfo() override {
1545     return CGM.getCXXABI().getCatchAllTypeInfo();
1546   }
ModuleInitFunction()1547   llvm::Function *ModuleInitFunction() override {
1548     llvm::Function *LoadFunction = llvm::Function::Create(
1549       llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
1550       llvm::GlobalValue::LinkOnceODRLinkage, ".objcv2_load_function",
1551       &TheModule);
1552     LoadFunction->setVisibility(llvm::GlobalValue::HiddenVisibility);
1553     LoadFunction->setComdat(TheModule.getOrInsertComdat(".objcv2_load_function"));
1554 
1555     llvm::BasicBlock *EntryBB =
1556         llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
1557     CGBuilderTy B(CGM, VMContext);
1558     B.SetInsertPoint(EntryBB);
1559     ConstantInitBuilder builder(CGM);
1560     auto InitStructBuilder = builder.beginStruct();
1561     InitStructBuilder.addInt(Int64Ty, 0);
1562     auto &sectionVec = CGM.getTriple().isOSBinFormatCOFF() ? PECOFFSectionsBaseNames : SectionsBaseNames;
1563     for (auto *s : sectionVec) {
1564       auto bounds = GetSectionBounds(s);
1565       InitStructBuilder.add(bounds.first);
1566       InitStructBuilder.add(bounds.second);
1567     }
1568     auto *InitStruct = InitStructBuilder.finishAndCreateGlobal(".objc_init",
1569         CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1570     InitStruct->setVisibility(llvm::GlobalValue::HiddenVisibility);
1571     InitStruct->setComdat(TheModule.getOrInsertComdat(".objc_init"));
1572 
1573     CallRuntimeFunction(B, "__objc_load", {InitStruct});;
1574     B.CreateRetVoid();
1575     // Make sure that the optimisers don't delete this function.
1576     CGM.addCompilerUsedGlobal(LoadFunction);
1577     // FIXME: Currently ELF only!
1578     // We have to do this by hand, rather than with @llvm.ctors, so that the
1579     // linker can remove the duplicate invocations.
1580     auto *InitVar = new llvm::GlobalVariable(TheModule, LoadFunction->getType(),
1581         /*isConstant*/false, llvm::GlobalValue::LinkOnceAnyLinkage,
1582         LoadFunction, ".objc_ctor");
1583     // Check that this hasn't been renamed.  This shouldn't happen, because
1584     // this function should be called precisely once.
1585     assert(InitVar->getName() == ".objc_ctor");
1586     // In Windows, initialisers are sorted by the suffix.  XCL is for library
1587     // initialisers, which run before user initialisers.  We are running
1588     // Objective-C loads at the end of library load.  This means +load methods
1589     // will run before any other static constructors, but that static
1590     // constructors can see a fully initialised Objective-C state.
1591     if (CGM.getTriple().isOSBinFormatCOFF())
1592         InitVar->setSection(".CRT$XCLz");
1593     else
1594     {
1595       if (CGM.getCodeGenOpts().UseInitArray)
1596         InitVar->setSection(".init_array");
1597       else
1598         InitVar->setSection(".ctors");
1599     }
1600     InitVar->setVisibility(llvm::GlobalValue::HiddenVisibility);
1601     InitVar->setComdat(TheModule.getOrInsertComdat(".objc_ctor"));
1602     CGM.addUsedGlobal(InitVar);
1603     for (auto *C : Categories) {
1604       auto *Cat = cast<llvm::GlobalVariable>(C->stripPointerCasts());
1605       Cat->setSection(sectionName<CategorySection>());
1606       CGM.addUsedGlobal(Cat);
1607     }
1608     auto createNullGlobal = [&](StringRef Name, ArrayRef<llvm::Constant*> Init,
1609         StringRef Section) {
1610       auto nullBuilder = builder.beginStruct();
1611       for (auto *F : Init)
1612         nullBuilder.add(F);
1613       auto GV = nullBuilder.finishAndCreateGlobal(Name, CGM.getPointerAlign(),
1614           false, llvm::GlobalValue::LinkOnceODRLinkage);
1615       GV->setSection(Section);
1616       GV->setComdat(TheModule.getOrInsertComdat(Name));
1617       GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1618       CGM.addUsedGlobal(GV);
1619       return GV;
1620     };
1621     for (auto clsAlias : ClassAliases)
1622       createNullGlobal(std::string(".objc_class_alias") +
1623           clsAlias.second, { MakeConstantString(clsAlias.second),
1624           GetClassVar(clsAlias.first) }, sectionName<ClassAliasSection>());
1625     // On ELF platforms, add a null value for each special section so that we
1626     // can always guarantee that the _start and _stop symbols will exist and be
1627     // meaningful.  This is not required on COFF platforms, where our start and
1628     // stop symbols will create the section.
1629     if (!CGM.getTriple().isOSBinFormatCOFF()) {
1630       createNullGlobal(".objc_null_selector", {NULLPtr, NULLPtr},
1631           sectionName<SelectorSection>());
1632       if (Categories.empty())
1633         createNullGlobal(".objc_null_category", {NULLPtr, NULLPtr,
1634                       NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr},
1635             sectionName<CategorySection>());
1636       if (!EmittedClass) {
1637         createNullGlobal(".objc_null_cls_init_ref", NULLPtr,
1638             sectionName<ClassSection>());
1639         createNullGlobal(".objc_null_class_ref", { NULLPtr, NULLPtr },
1640             sectionName<ClassReferenceSection>());
1641       }
1642       if (!EmittedProtocol)
1643         createNullGlobal(".objc_null_protocol", {NULLPtr, NULLPtr, NULLPtr,
1644             NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr,
1645             NULLPtr}, sectionName<ProtocolSection>());
1646       if (!EmittedProtocolRef)
1647         createNullGlobal(".objc_null_protocol_ref", {NULLPtr},
1648             sectionName<ProtocolReferenceSection>());
1649       if (ClassAliases.empty())
1650         createNullGlobal(".objc_null_class_alias", { NULLPtr, NULLPtr },
1651             sectionName<ClassAliasSection>());
1652       if (ConstantStrings.empty()) {
1653         auto i32Zero = llvm::ConstantInt::get(Int32Ty, 0);
1654         createNullGlobal(".objc_null_constant_string", { NULLPtr, i32Zero,
1655             i32Zero, i32Zero, i32Zero, NULLPtr },
1656             sectionName<ConstantStringSection>());
1657       }
1658     }
1659     ConstantStrings.clear();
1660     Categories.clear();
1661     Classes.clear();
1662 
1663     if (EarlyInitList.size() > 0) {
1664       auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
1665             {}), llvm::GlobalValue::InternalLinkage, ".objc_early_init",
1666           &CGM.getModule());
1667       llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
1668             Init));
1669       for (const auto &lateInit : EarlyInitList) {
1670         auto *global = TheModule.getGlobalVariable(lateInit.first);
1671         if (global) {
1672           llvm::GlobalVariable *GV = lateInit.second.first;
1673           b.CreateAlignedStore(
1674               global,
1675               b.CreateStructGEP(GV->getValueType(), GV, lateInit.second.second),
1676               CGM.getPointerAlign().getAsAlign());
1677         }
1678       }
1679       b.CreateRetVoid();
1680       // We can't use the normal LLVM global initialisation array, because we
1681       // need to specify that this runs early in library initialisation.
1682       auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
1683           /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
1684           Init, ".objc_early_init_ptr");
1685       InitVar->setSection(".CRT$XCLb");
1686       CGM.addUsedGlobal(InitVar);
1687     }
1688     return nullptr;
1689   }
1690   /// In the v2 ABI, ivar offset variables use the type encoding in their name
1691   /// to trigger linker failures if the types don't match.
GetIVarOffsetVariableName(const ObjCInterfaceDecl * ID,const ObjCIvarDecl * Ivar)1692   std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
1693                                         const ObjCIvarDecl *Ivar) override {
1694     std::string TypeEncoding;
1695     CGM.getContext().getObjCEncodingForType(Ivar->getType(), TypeEncoding);
1696     TypeEncoding = GetSymbolNameForTypeEncoding(TypeEncoding);
1697     const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
1698       + '.' + Ivar->getNameAsString() + '.' + TypeEncoding;
1699     return Name;
1700   }
EmitIvarOffset(CodeGenFunction & CGF,const ObjCInterfaceDecl * Interface,const ObjCIvarDecl * Ivar)1701   llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
1702                               const ObjCInterfaceDecl *Interface,
1703                               const ObjCIvarDecl *Ivar) override {
1704     const std::string Name = GetIVarOffsetVariableName(Ivar->getContainingInterface(), Ivar);
1705     llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
1706     if (!IvarOffsetPointer)
1707       IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false,
1708               llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1709     CharUnits Align = CGM.getIntAlign();
1710     llvm::Value *Offset =
1711         CGF.Builder.CreateAlignedLoad(IntTy, IvarOffsetPointer, Align);
1712     if (Offset->getType() != PtrDiffTy)
1713       Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
1714     return Offset;
1715   }
GenerateClass(const ObjCImplementationDecl * OID)1716   void GenerateClass(const ObjCImplementationDecl *OID) override {
1717     ASTContext &Context = CGM.getContext();
1718     bool IsCOFF = CGM.getTriple().isOSBinFormatCOFF();
1719 
1720     // Get the class name
1721     ObjCInterfaceDecl *classDecl =
1722         const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
1723     std::string className = classDecl->getNameAsString();
1724     auto *classNameConstant = MakeConstantString(className);
1725 
1726     ConstantInitBuilder builder(CGM);
1727     auto metaclassFields = builder.beginStruct();
1728     // struct objc_class *isa;
1729     metaclassFields.addNullPointer(PtrTy);
1730     // struct objc_class *super_class;
1731     metaclassFields.addNullPointer(PtrTy);
1732     // const char *name;
1733     metaclassFields.add(classNameConstant);
1734     // long version;
1735     metaclassFields.addInt(LongTy, 0);
1736     // unsigned long info;
1737     // objc_class_flag_meta
1738     metaclassFields.addInt(LongTy, ClassFlags::ClassFlagMeta);
1739     // long instance_size;
1740     // Setting this to zero is consistent with the older ABI, but it might be
1741     // more sensible to set this to sizeof(struct objc_class)
1742     metaclassFields.addInt(LongTy, 0);
1743     // struct objc_ivar_list *ivars;
1744     metaclassFields.addNullPointer(PtrTy);
1745     // struct objc_method_list *methods
1746     // FIXME: Almost identical code is copied and pasted below for the
1747     // class, but refactoring it cleanly requires C++14 generic lambdas.
1748     if (OID->classmeth_begin() == OID->classmeth_end())
1749       metaclassFields.addNullPointer(PtrTy);
1750     else {
1751       SmallVector<ObjCMethodDecl*, 16> ClassMethods;
1752       ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
1753           OID->classmeth_end());
1754       metaclassFields.add(
1755           GenerateMethodList(className, "", ClassMethods, true));
1756     }
1757     // void *dtable;
1758     metaclassFields.addNullPointer(PtrTy);
1759     // IMP cxx_construct;
1760     metaclassFields.addNullPointer(PtrTy);
1761     // IMP cxx_destruct;
1762     metaclassFields.addNullPointer(PtrTy);
1763     // struct objc_class *subclass_list
1764     metaclassFields.addNullPointer(PtrTy);
1765     // struct objc_class *sibling_class
1766     metaclassFields.addNullPointer(PtrTy);
1767     // struct objc_protocol_list *protocols;
1768     metaclassFields.addNullPointer(PtrTy);
1769     // struct reference_list *extra_data;
1770     metaclassFields.addNullPointer(PtrTy);
1771     // long abi_version;
1772     metaclassFields.addInt(LongTy, 0);
1773     // struct objc_property_list *properties
1774     metaclassFields.add(GeneratePropertyList(OID, classDecl, /*isClassProperty*/true));
1775 
1776     auto *metaclass = metaclassFields.finishAndCreateGlobal(
1777         ManglePublicSymbol("OBJC_METACLASS_") + className,
1778         CGM.getPointerAlign());
1779 
1780     auto classFields = builder.beginStruct();
1781     // struct objc_class *isa;
1782     classFields.add(metaclass);
1783     // struct objc_class *super_class;
1784     // Get the superclass name.
1785     const ObjCInterfaceDecl * SuperClassDecl =
1786       OID->getClassInterface()->getSuperClass();
1787     llvm::Constant *SuperClass = nullptr;
1788     if (SuperClassDecl) {
1789       auto SuperClassName = SymbolForClass(SuperClassDecl->getNameAsString());
1790       SuperClass = TheModule.getNamedGlobal(SuperClassName);
1791       if (!SuperClass)
1792       {
1793         SuperClass = new llvm::GlobalVariable(TheModule, PtrTy, false,
1794             llvm::GlobalValue::ExternalLinkage, nullptr, SuperClassName);
1795         if (IsCOFF) {
1796           auto Storage = llvm::GlobalValue::DefaultStorageClass;
1797           if (SuperClassDecl->hasAttr<DLLImportAttr>())
1798             Storage = llvm::GlobalValue::DLLImportStorageClass;
1799           else if (SuperClassDecl->hasAttr<DLLExportAttr>())
1800             Storage = llvm::GlobalValue::DLLExportStorageClass;
1801 
1802           cast<llvm::GlobalValue>(SuperClass)->setDLLStorageClass(Storage);
1803         }
1804       }
1805       if (!IsCOFF)
1806         classFields.add(SuperClass);
1807       else
1808         classFields.addNullPointer(PtrTy);
1809     } else
1810       classFields.addNullPointer(PtrTy);
1811     // const char *name;
1812     classFields.add(classNameConstant);
1813     // long version;
1814     classFields.addInt(LongTy, 0);
1815     // unsigned long info;
1816     // !objc_class_flag_meta
1817     classFields.addInt(LongTy, 0);
1818     // long instance_size;
1819     int superInstanceSize = !SuperClassDecl ? 0 :
1820       Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
1821     // Instance size is negative for classes that have not yet had their ivar
1822     // layout calculated.
1823     classFields.addInt(LongTy,
1824       0 - (Context.getASTObjCImplementationLayout(OID).getSize().getQuantity() -
1825       superInstanceSize));
1826 
1827     if (classDecl->all_declared_ivar_begin() == nullptr)
1828       classFields.addNullPointer(PtrTy);
1829     else {
1830       int ivar_count = 0;
1831       for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1832            IVD = IVD->getNextIvar()) ivar_count++;
1833       llvm::DataLayout td(&TheModule);
1834       // struct objc_ivar_list *ivars;
1835       ConstantInitBuilder b(CGM);
1836       auto ivarListBuilder = b.beginStruct();
1837       // int count;
1838       ivarListBuilder.addInt(IntTy, ivar_count);
1839       // size_t size;
1840       llvm::StructType *ObjCIvarTy = llvm::StructType::get(
1841         PtrToInt8Ty,
1842         PtrToInt8Ty,
1843         PtrToInt8Ty,
1844         Int32Ty,
1845         Int32Ty);
1846       ivarListBuilder.addInt(SizeTy, td.getTypeSizeInBits(ObjCIvarTy) /
1847           CGM.getContext().getCharWidth());
1848       // struct objc_ivar ivars[]
1849       auto ivarArrayBuilder = ivarListBuilder.beginArray();
1850       for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1851            IVD = IVD->getNextIvar()) {
1852         auto ivarTy = IVD->getType();
1853         auto ivarBuilder = ivarArrayBuilder.beginStruct();
1854         // const char *name;
1855         ivarBuilder.add(MakeConstantString(IVD->getNameAsString()));
1856         // const char *type;
1857         std::string TypeStr;
1858         //Context.getObjCEncodingForType(ivarTy, TypeStr, IVD, true);
1859         Context.getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, ivarTy, TypeStr, true);
1860         ivarBuilder.add(MakeConstantString(TypeStr));
1861         // int *offset;
1862         uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
1863         uint64_t Offset = BaseOffset - superInstanceSize;
1864         llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
1865         std::string OffsetName = GetIVarOffsetVariableName(classDecl, IVD);
1866         llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
1867         if (OffsetVar)
1868           OffsetVar->setInitializer(OffsetValue);
1869         else
1870           OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
1871             false, llvm::GlobalValue::ExternalLinkage,
1872             OffsetValue, OffsetName);
1873         auto ivarVisibility =
1874             (IVD->getAccessControl() == ObjCIvarDecl::Private ||
1875              IVD->getAccessControl() == ObjCIvarDecl::Package ||
1876              classDecl->getVisibility() == HiddenVisibility) ?
1877                     llvm::GlobalValue::HiddenVisibility :
1878                     llvm::GlobalValue::DefaultVisibility;
1879         OffsetVar->setVisibility(ivarVisibility);
1880         if (ivarVisibility != llvm::GlobalValue::HiddenVisibility)
1881           CGM.setGVProperties(OffsetVar, OID->getClassInterface());
1882         ivarBuilder.add(OffsetVar);
1883         // Ivar size
1884         ivarBuilder.addInt(Int32Ty,
1885             CGM.getContext().getTypeSizeInChars(ivarTy).getQuantity());
1886         // Alignment will be stored as a base-2 log of the alignment.
1887         unsigned align =
1888             llvm::Log2_32(Context.getTypeAlignInChars(ivarTy).getQuantity());
1889         // Objects that require more than 2^64-byte alignment should be impossible!
1890         assert(align < 64);
1891         // uint32_t flags;
1892         // Bits 0-1 are ownership.
1893         // Bit 2 indicates an extended type encoding
1894         // Bits 3-8 contain log2(aligment)
1895         ivarBuilder.addInt(Int32Ty,
1896             (align << 3) | (1<<2) |
1897             FlagsForOwnership(ivarTy.getQualifiers().getObjCLifetime()));
1898         ivarBuilder.finishAndAddTo(ivarArrayBuilder);
1899       }
1900       ivarArrayBuilder.finishAndAddTo(ivarListBuilder);
1901       auto ivarList = ivarListBuilder.finishAndCreateGlobal(".objc_ivar_list",
1902           CGM.getPointerAlign(), /*constant*/ false,
1903           llvm::GlobalValue::PrivateLinkage);
1904       classFields.add(ivarList);
1905     }
1906     // struct objc_method_list *methods
1907     SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
1908     InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
1909         OID->instmeth_end());
1910     for (auto *propImpl : OID->property_impls())
1911       if (propImpl->getPropertyImplementation() ==
1912           ObjCPropertyImplDecl::Synthesize) {
1913         auto addIfExists = [&](const ObjCMethodDecl *OMD) {
1914           if (OMD && OMD->hasBody())
1915             InstanceMethods.push_back(OMD);
1916         };
1917         addIfExists(propImpl->getGetterMethodDecl());
1918         addIfExists(propImpl->getSetterMethodDecl());
1919       }
1920 
1921     if (InstanceMethods.size() == 0)
1922       classFields.addNullPointer(PtrTy);
1923     else
1924       classFields.add(
1925           GenerateMethodList(className, "", InstanceMethods, false));
1926 
1927     // void *dtable;
1928     classFields.addNullPointer(PtrTy);
1929     // IMP cxx_construct;
1930     classFields.addNullPointer(PtrTy);
1931     // IMP cxx_destruct;
1932     classFields.addNullPointer(PtrTy);
1933     // struct objc_class *subclass_list
1934     classFields.addNullPointer(PtrTy);
1935     // struct objc_class *sibling_class
1936     classFields.addNullPointer(PtrTy);
1937     // struct objc_protocol_list *protocols;
1938     auto RuntimeProtocols = GetRuntimeProtocolList(classDecl->protocol_begin(),
1939                                                    classDecl->protocol_end());
1940     SmallVector<llvm::Constant *, 16> Protocols;
1941     for (const auto *I : RuntimeProtocols)
1942       Protocols.push_back(GenerateProtocolRef(I));
1943 
1944     if (Protocols.empty())
1945       classFields.addNullPointer(PtrTy);
1946     else
1947       classFields.add(GenerateProtocolList(Protocols));
1948     // struct reference_list *extra_data;
1949     classFields.addNullPointer(PtrTy);
1950     // long abi_version;
1951     classFields.addInt(LongTy, 0);
1952     // struct objc_property_list *properties
1953     classFields.add(GeneratePropertyList(OID, classDecl));
1954 
1955     llvm::GlobalVariable *classStruct =
1956       classFields.finishAndCreateGlobal(SymbolForClass(className),
1957         CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
1958 
1959     auto *classRefSymbol = GetClassVar(className);
1960     classRefSymbol->setSection(sectionName<ClassReferenceSection>());
1961     classRefSymbol->setInitializer(classStruct);
1962 
1963     if (IsCOFF) {
1964       // we can't import a class struct.
1965       if (OID->getClassInterface()->hasAttr<DLLExportAttr>()) {
1966         classStruct->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1967         cast<llvm::GlobalValue>(classRefSymbol)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1968       }
1969 
1970       if (SuperClass) {
1971         std::pair<llvm::GlobalVariable*, int> v{classStruct, 1};
1972         EarlyInitList.emplace_back(std::string(SuperClass->getName()),
1973                                    std::move(v));
1974       }
1975 
1976     }
1977 
1978 
1979     // Resolve the class aliases, if they exist.
1980     // FIXME: Class pointer aliases shouldn't exist!
1981     if (ClassPtrAlias) {
1982       ClassPtrAlias->replaceAllUsesWith(classStruct);
1983       ClassPtrAlias->eraseFromParent();
1984       ClassPtrAlias = nullptr;
1985     }
1986     if (auto Placeholder =
1987         TheModule.getNamedGlobal(SymbolForClass(className)))
1988       if (Placeholder != classStruct) {
1989         Placeholder->replaceAllUsesWith(classStruct);
1990         Placeholder->eraseFromParent();
1991         classStruct->setName(SymbolForClass(className));
1992       }
1993     if (MetaClassPtrAlias) {
1994       MetaClassPtrAlias->replaceAllUsesWith(metaclass);
1995       MetaClassPtrAlias->eraseFromParent();
1996       MetaClassPtrAlias = nullptr;
1997     }
1998     assert(classStruct->getName() == SymbolForClass(className));
1999 
2000     auto classInitRef = new llvm::GlobalVariable(TheModule,
2001         classStruct->getType(), false, llvm::GlobalValue::ExternalLinkage,
2002         classStruct, ManglePublicSymbol("OBJC_INIT_CLASS_") + className);
2003     classInitRef->setSection(sectionName<ClassSection>());
2004     CGM.addUsedGlobal(classInitRef);
2005 
2006     EmittedClass = true;
2007   }
2008   public:
CGObjCGNUstep2(CodeGenModule & Mod)2009     CGObjCGNUstep2(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 10, 4, 2) {
2010       MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
2011                             PtrToObjCSuperTy, SelectorTy);
2012       SentInitializeFn.init(&CGM, "objc_send_initialize",
2013                             llvm::Type::getVoidTy(VMContext), IdTy);
2014       // struct objc_property
2015       // {
2016       //   const char *name;
2017       //   const char *attributes;
2018       //   const char *type;
2019       //   SEL getter;
2020       //   SEL setter;
2021       // }
2022       PropertyMetadataTy =
2023         llvm::StructType::get(CGM.getLLVMContext(),
2024             { PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
2025     }
2026 
GenerateDirectMethodPrologue(CodeGenFunction & CGF,llvm::Function * Fn,const ObjCMethodDecl * OMD,const ObjCContainerDecl * CD)2027     void GenerateDirectMethodPrologue(CodeGenFunction &CGF, llvm::Function *Fn,
2028                                       const ObjCMethodDecl *OMD,
2029                                       const ObjCContainerDecl *CD) override {
2030       auto &Builder = CGF.Builder;
2031       bool ReceiverCanBeNull = true;
2032       auto selfAddr = CGF.GetAddrOfLocalVar(OMD->getSelfDecl());
2033       auto selfValue = Builder.CreateLoad(selfAddr);
2034 
2035       // Generate:
2036       //
2037       // /* unless the receiver is never NULL */
2038       // if (self == nil) {
2039       //     return (ReturnType){ };
2040       // }
2041       //
2042       // /* for class methods only to force class lazy initialization */
2043       // if (!__objc_{class}_initialized)
2044       // {
2045       //   objc_send_initialize(class);
2046       //   __objc_{class}_initialized = 1;
2047       // }
2048       //
2049       // _cmd = @selector(...)
2050       // ...
2051 
2052       if (OMD->isClassMethod()) {
2053         const ObjCInterfaceDecl *OID = cast<ObjCInterfaceDecl>(CD);
2054 
2055         // Nullable `Class` expressions cannot be messaged with a direct method
2056         // so the only reason why the receive can be null would be because
2057         // of weak linking.
2058         ReceiverCanBeNull = isWeakLinkedClass(OID);
2059       }
2060 
2061       llvm::MDBuilder MDHelper(CGM.getLLVMContext());
2062       if (ReceiverCanBeNull) {
2063         llvm::BasicBlock *SelfIsNilBlock =
2064             CGF.createBasicBlock("objc_direct_method.self_is_nil");
2065         llvm::BasicBlock *ContBlock =
2066             CGF.createBasicBlock("objc_direct_method.cont");
2067 
2068         // if (self == nil) {
2069         auto selfTy = cast<llvm::PointerType>(selfValue->getType());
2070         auto Zero = llvm::ConstantPointerNull::get(selfTy);
2071 
2072         Builder.CreateCondBr(Builder.CreateICmpEQ(selfValue, Zero),
2073                              SelfIsNilBlock, ContBlock,
2074                              MDHelper.createBranchWeights(1, 1 << 20));
2075 
2076         CGF.EmitBlock(SelfIsNilBlock);
2077 
2078         //   return (ReturnType){ };
2079         auto retTy = OMD->getReturnType();
2080         Builder.SetInsertPoint(SelfIsNilBlock);
2081         if (!retTy->isVoidType()) {
2082           CGF.EmitNullInitialization(CGF.ReturnValue, retTy);
2083         }
2084         CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
2085         // }
2086 
2087         // rest of the body
2088         CGF.EmitBlock(ContBlock);
2089         Builder.SetInsertPoint(ContBlock);
2090       }
2091 
2092       if (OMD->isClassMethod()) {
2093         // Prefix of the class type.
2094         auto *classStart =
2095             llvm::StructType::get(PtrTy, PtrTy, PtrTy, LongTy, LongTy);
2096         auto &astContext = CGM.getContext();
2097         auto flags = Builder.CreateLoad(
2098             Address{Builder.CreateStructGEP(classStart, selfValue, 4), LongTy,
2099                     CharUnits::fromQuantity(
2100                         astContext.getTypeAlign(astContext.UnsignedLongTy))});
2101         auto isInitialized =
2102             Builder.CreateAnd(flags, ClassFlags::ClassFlagInitialized);
2103         llvm::BasicBlock *notInitializedBlock =
2104             CGF.createBasicBlock("objc_direct_method.class_uninitialized");
2105         llvm::BasicBlock *initializedBlock =
2106             CGF.createBasicBlock("objc_direct_method.class_initialized");
2107         Builder.CreateCondBr(Builder.CreateICmpEQ(isInitialized, Zeros[0]),
2108                              notInitializedBlock, initializedBlock,
2109                              MDHelper.createBranchWeights(1, 1 << 20));
2110         CGF.EmitBlock(notInitializedBlock);
2111         Builder.SetInsertPoint(notInitializedBlock);
2112         CGF.EmitRuntimeCall(SentInitializeFn, selfValue);
2113         Builder.CreateBr(initializedBlock);
2114         CGF.EmitBlock(initializedBlock);
2115         Builder.SetInsertPoint(initializedBlock);
2116       }
2117 
2118       // only synthesize _cmd if it's referenced
2119       if (OMD->getCmdDecl()->isUsed()) {
2120         // `_cmd` is not a parameter to direct methods, so storage must be
2121         // explicitly declared for it.
2122         CGF.EmitVarDecl(*OMD->getCmdDecl());
2123         Builder.CreateStore(GetSelector(CGF, OMD),
2124                             CGF.GetAddrOfLocalVar(OMD->getCmdDecl()));
2125       }
2126     }
2127 };
2128 
2129 const char *const CGObjCGNUstep2::SectionsBaseNames[8] =
2130 {
2131 "__objc_selectors",
2132 "__objc_classes",
2133 "__objc_class_refs",
2134 "__objc_cats",
2135 "__objc_protocols",
2136 "__objc_protocol_refs",
2137 "__objc_class_aliases",
2138 "__objc_constant_string"
2139 };
2140 
2141 const char *const CGObjCGNUstep2::PECOFFSectionsBaseNames[8] =
2142 {
2143 ".objcrt$SEL",
2144 ".objcrt$CLS",
2145 ".objcrt$CLR",
2146 ".objcrt$CAT",
2147 ".objcrt$PCL",
2148 ".objcrt$PCR",
2149 ".objcrt$CAL",
2150 ".objcrt$STR"
2151 };
2152 
2153 /// Support for the ObjFW runtime.
2154 class CGObjCObjFW: public CGObjCGNU {
2155 protected:
2156   /// The GCC ABI message lookup function.  Returns an IMP pointing to the
2157   /// method implementation for this message.
2158   LazyRuntimeFunction MsgLookupFn;
2159   /// stret lookup function.  While this does not seem to make sense at the
2160   /// first look, this is required to call the correct forwarding function.
2161   LazyRuntimeFunction MsgLookupFnSRet;
2162   /// The GCC ABI superclass message lookup function.  Takes a pointer to a
2163   /// structure describing the receiver and the class, and a selector as
2164   /// arguments.  Returns the IMP for the corresponding method.
2165   LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
2166 
LookupIMP(CodeGenFunction & CGF,llvm::Value * & Receiver,llvm::Value * cmd,llvm::MDNode * node,MessageSendInfo & MSI)2167   llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
2168                          llvm::Value *cmd, llvm::MDNode *node,
2169                          MessageSendInfo &MSI) override {
2170     CGBuilderTy &Builder = CGF.Builder;
2171     llvm::Value *args[] = {
2172             EnforceType(Builder, Receiver, IdTy),
2173             EnforceType(Builder, cmd, SelectorTy) };
2174 
2175     llvm::CallBase *imp;
2176     if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
2177       imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
2178     else
2179       imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
2180 
2181     imp->setMetadata(msgSendMDKind, node);
2182     return imp;
2183   }
2184 
LookupIMPSuper(CodeGenFunction & CGF,Address ObjCSuper,llvm::Value * cmd,MessageSendInfo & MSI)2185   llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
2186                               llvm::Value *cmd, MessageSendInfo &MSI) override {
2187     CGBuilderTy &Builder = CGF.Builder;
2188     llvm::Value *lookupArgs[] = {
2189         EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
2190     };
2191 
2192     if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
2193       return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
2194     else
2195       return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
2196   }
2197 
GetClassNamed(CodeGenFunction & CGF,const std::string & Name,bool isWeak)2198   llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
2199                              bool isWeak) override {
2200     if (isWeak)
2201       return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
2202 
2203     EmitClassRef(Name);
2204     std::string SymbolName = "_OBJC_CLASS_" + Name;
2205     llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
2206     if (!ClassSymbol)
2207       ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
2208                                              llvm::GlobalValue::ExternalLinkage,
2209                                              nullptr, SymbolName);
2210     return ClassSymbol;
2211   }
2212 
2213 public:
CGObjCObjFW(CodeGenModule & Mod)2214   CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
2215     // IMP objc_msg_lookup(id, SEL);
2216     MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
2217     MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
2218                          SelectorTy);
2219     // IMP objc_msg_lookup_super(struct objc_super*, SEL);
2220     MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
2221                           PtrToObjCSuperTy, SelectorTy);
2222     MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
2223                               PtrToObjCSuperTy, SelectorTy);
2224   }
2225 };
2226 } // end anonymous namespace
2227 
2228 /// Emits a reference to a dummy variable which is emitted with each class.
2229 /// This ensures that a linker error will be generated when trying to link
2230 /// together modules where a referenced class is not defined.
EmitClassRef(const std::string & className)2231 void CGObjCGNU::EmitClassRef(const std::string &className) {
2232   std::string symbolRef = "__objc_class_ref_" + className;
2233   // Don't emit two copies of the same symbol
2234   if (TheModule.getGlobalVariable(symbolRef))
2235     return;
2236   std::string symbolName = "__objc_class_name_" + className;
2237   llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
2238   if (!ClassSymbol) {
2239     ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
2240                                            llvm::GlobalValue::ExternalLinkage,
2241                                            nullptr, symbolName);
2242   }
2243   new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
2244     llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
2245 }
2246 
CGObjCGNU(CodeGenModule & cgm,unsigned runtimeABIVersion,unsigned protocolClassVersion,unsigned classABI)2247 CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
2248                      unsigned protocolClassVersion, unsigned classABI)
2249   : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
2250     VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
2251     MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
2252     ProtocolVersion(protocolClassVersion), ClassABIVersion(classABI) {
2253 
2254   msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
2255   usesSEHExceptions =
2256       cgm.getContext().getTargetInfo().getTriple().isWindowsMSVCEnvironment();
2257   usesCxxExceptions =
2258       cgm.getContext().getTargetInfo().getTriple().isOSCygMing() &&
2259       isRuntime(ObjCRuntime::GNUstep, 2);
2260 
2261   CodeGenTypes &Types = CGM.getTypes();
2262   IntTy = cast<llvm::IntegerType>(
2263       Types.ConvertType(CGM.getContext().IntTy));
2264   LongTy = cast<llvm::IntegerType>(
2265       Types.ConvertType(CGM.getContext().LongTy));
2266   SizeTy = cast<llvm::IntegerType>(
2267       Types.ConvertType(CGM.getContext().getSizeType()));
2268   PtrDiffTy = cast<llvm::IntegerType>(
2269       Types.ConvertType(CGM.getContext().getPointerDiffType()));
2270   BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
2271 
2272   Int8Ty = llvm::Type::getInt8Ty(VMContext);
2273   // C string type.  Used in lots of places.
2274   PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
2275   ProtocolPtrTy = llvm::PointerType::getUnqual(
2276       Types.ConvertType(CGM.getContext().getObjCProtoType()));
2277 
2278   Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
2279   Zeros[1] = Zeros[0];
2280   NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
2281   // Get the selector Type.
2282   QualType selTy = CGM.getContext().getObjCSelType();
2283   if (QualType() == selTy) {
2284     SelectorTy = PtrToInt8Ty;
2285     SelectorElemTy = Int8Ty;
2286   } else {
2287     SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
2288     SelectorElemTy = CGM.getTypes().ConvertTypeForMem(selTy->getPointeeType());
2289   }
2290 
2291   PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
2292   PtrTy = PtrToInt8Ty;
2293 
2294   Int32Ty = llvm::Type::getInt32Ty(VMContext);
2295   Int64Ty = llvm::Type::getInt64Ty(VMContext);
2296 
2297   IntPtrTy =
2298       CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
2299 
2300   // Object type
2301   QualType UnqualIdTy = CGM.getContext().getObjCIdType();
2302   ASTIdTy = CanQualType();
2303   if (UnqualIdTy != QualType()) {
2304     ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
2305     IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
2306     IdElemTy = CGM.getTypes().ConvertTypeForMem(
2307         ASTIdTy.getTypePtr()->getPointeeType());
2308   } else {
2309     IdTy = PtrToInt8Ty;
2310     IdElemTy = Int8Ty;
2311   }
2312   PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
2313   ProtocolTy = llvm::StructType::get(IdTy,
2314       PtrToInt8Ty, // name
2315       PtrToInt8Ty, // protocols
2316       PtrToInt8Ty, // instance methods
2317       PtrToInt8Ty, // class methods
2318       PtrToInt8Ty, // optional instance methods
2319       PtrToInt8Ty, // optional class methods
2320       PtrToInt8Ty, // properties
2321       PtrToInt8Ty);// optional properties
2322 
2323   // struct objc_property_gsv1
2324   // {
2325   //   const char *name;
2326   //   char attributes;
2327   //   char attributes2;
2328   //   char unused1;
2329   //   char unused2;
2330   //   const char *getter_name;
2331   //   const char *getter_types;
2332   //   const char *setter_name;
2333   //   const char *setter_types;
2334   // }
2335   PropertyMetadataTy = llvm::StructType::get(CGM.getLLVMContext(), {
2336       PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty,
2337       PtrToInt8Ty, PtrToInt8Ty });
2338 
2339   ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);
2340   PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
2341 
2342   llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
2343 
2344   // void objc_exception_throw(id);
2345   ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
2346   ExceptionReThrowFn.init(&CGM,
2347                           usesCxxExceptions ? "objc_exception_rethrow"
2348                                             : "objc_exception_throw",
2349                           VoidTy, IdTy);
2350   // int objc_sync_enter(id);
2351   SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
2352   // int objc_sync_exit(id);
2353   SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);
2354 
2355   // void objc_enumerationMutation (id)
2356   EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);
2357 
2358   // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
2359   GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
2360                      PtrDiffTy, BoolTy);
2361   // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
2362   SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
2363                      PtrDiffTy, IdTy, BoolTy, BoolTy);
2364   // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
2365   GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
2366                            PtrDiffTy, BoolTy, BoolTy);
2367   // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
2368   SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
2369                            PtrDiffTy, BoolTy, BoolTy);
2370 
2371   // IMP type
2372   llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
2373   IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
2374               true));
2375 
2376   const LangOptions &Opts = CGM.getLangOpts();
2377   if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
2378     RuntimeVersion = 10;
2379 
2380   // Don't bother initialising the GC stuff unless we're compiling in GC mode
2381   if (Opts.getGC() != LangOptions::NonGC) {
2382     // This is a bit of an hack.  We should sort this out by having a proper
2383     // CGObjCGNUstep subclass for GC, but we may want to really support the old
2384     // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
2385     // Get selectors needed in GC mode
2386     RetainSel = GetNullarySelector("retain", CGM.getContext());
2387     ReleaseSel = GetNullarySelector("release", CGM.getContext());
2388     AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
2389 
2390     // Get functions needed in GC mode
2391 
2392     // id objc_assign_ivar(id, id, ptrdiff_t);
2393     IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);
2394     // id objc_assign_strongCast (id, id*)
2395     StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
2396                             PtrToIdTy);
2397     // id objc_assign_global(id, id*);
2398     GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);
2399     // id objc_assign_weak(id, id*);
2400     WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);
2401     // id objc_read_weak(id*);
2402     WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);
2403     // void *objc_memmove_collectable(void*, void *, size_t);
2404     MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
2405                    SizeTy);
2406   }
2407 }
2408 
GetClassNamed(CodeGenFunction & CGF,const std::string & Name,bool isWeak)2409 llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
2410                                       const std::string &Name, bool isWeak) {
2411   llvm::Constant *ClassName = MakeConstantString(Name);
2412   // With the incompatible ABI, this will need to be replaced with a direct
2413   // reference to the class symbol.  For the compatible nonfragile ABI we are
2414   // still performing this lookup at run time but emitting the symbol for the
2415   // class externally so that we can make the switch later.
2416   //
2417   // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
2418   // with memoized versions or with static references if it's safe to do so.
2419   if (!isWeak)
2420     EmitClassRef(Name);
2421 
2422   llvm::FunctionCallee ClassLookupFn = CGM.CreateRuntimeFunction(
2423       llvm::FunctionType::get(IdTy, PtrToInt8Ty, true), "objc_lookup_class");
2424   return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
2425 }
2426 
2427 // This has to perform the lookup every time, since posing and related
2428 // techniques can modify the name -> class mapping.
GetClass(CodeGenFunction & CGF,const ObjCInterfaceDecl * OID)2429 llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
2430                                  const ObjCInterfaceDecl *OID) {
2431   auto *Value =
2432       GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
2433   if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value))
2434     CGM.setGVProperties(ClassSymbol, OID);
2435   return Value;
2436 }
2437 
EmitNSAutoreleasePoolClassRef(CodeGenFunction & CGF)2438 llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
2439   auto *Value  = GetClassNamed(CGF, "NSAutoreleasePool", false);
2440   if (CGM.getTriple().isOSBinFormatCOFF()) {
2441     if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
2442       IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
2443       TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2444       DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2445 
2446       const VarDecl *VD = nullptr;
2447       for (const auto *Result : DC->lookup(&II))
2448         if ((VD = dyn_cast<VarDecl>(Result)))
2449           break;
2450 
2451       CGM.setGVProperties(ClassSymbol, VD);
2452     }
2453   }
2454   return Value;
2455 }
2456 
GetTypedSelector(CodeGenFunction & CGF,Selector Sel,const std::string & TypeEncoding)2457 llvm::Value *CGObjCGNU::GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
2458                                          const std::string &TypeEncoding) {
2459   SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
2460   llvm::GlobalAlias *SelValue = nullptr;
2461 
2462   for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
2463       e = Types.end() ; i!=e ; i++) {
2464     if (i->first == TypeEncoding) {
2465       SelValue = i->second;
2466       break;
2467     }
2468   }
2469   if (!SelValue) {
2470     SelValue = llvm::GlobalAlias::create(SelectorElemTy, 0,
2471                                          llvm::GlobalValue::PrivateLinkage,
2472                                          ".objc_selector_" + Sel.getAsString(),
2473                                          &TheModule);
2474     Types.emplace_back(TypeEncoding, SelValue);
2475   }
2476 
2477   return SelValue;
2478 }
2479 
GetAddrOfSelector(CodeGenFunction & CGF,Selector Sel)2480 Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
2481   llvm::Value *SelValue = GetSelector(CGF, Sel);
2482 
2483   // Store it to a temporary.  Does this satisfy the semantics of
2484   // GetAddrOfSelector?  Hopefully.
2485   Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
2486                                      CGF.getPointerAlign());
2487   CGF.Builder.CreateStore(SelValue, tmp);
2488   return tmp;
2489 }
2490 
GetSelector(CodeGenFunction & CGF,Selector Sel)2491 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
2492   return GetTypedSelector(CGF, Sel, std::string());
2493 }
2494 
GetSelector(CodeGenFunction & CGF,const ObjCMethodDecl * Method)2495 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
2496                                     const ObjCMethodDecl *Method) {
2497   std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
2498   return GetTypedSelector(CGF, Method->getSelector(), SelTypes);
2499 }
2500 
GetEHType(QualType T)2501 llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
2502   if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
2503     // With the old ABI, there was only one kind of catchall, which broke
2504     // foreign exceptions.  With the new ABI, we use __objc_id_typeinfo as
2505     // a pointer indicating object catchalls, and NULL to indicate real
2506     // catchalls
2507     if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2508       return MakeConstantString("@id");
2509     } else {
2510       return nullptr;
2511     }
2512   }
2513 
2514   // All other types should be Objective-C interface pointer types.
2515   const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
2516   assert(OPT && "Invalid @catch type.");
2517   const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
2518   assert(IDecl && "Invalid @catch type.");
2519   return MakeConstantString(IDecl->getIdentifier()->getName());
2520 }
2521 
GetEHType(QualType T)2522 llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
2523   if (usesSEHExceptions)
2524     return CGM.getCXXABI().getAddrOfRTTIDescriptor(T);
2525 
2526   if (!CGM.getLangOpts().CPlusPlus && !usesCxxExceptions)
2527     return CGObjCGNU::GetEHType(T);
2528 
2529   // For Objective-C++, we want to provide the ability to catch both C++ and
2530   // Objective-C objects in the same function.
2531 
2532   // There's a particular fixed type info for 'id'.
2533   if (T->isObjCIdType() ||
2534       T->isObjCQualifiedIdType()) {
2535     llvm::Constant *IDEHType =
2536       CGM.getModule().getGlobalVariable("__objc_id_type_info");
2537     if (!IDEHType)
2538       IDEHType =
2539         new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
2540                                  false,
2541                                  llvm::GlobalValue::ExternalLinkage,
2542                                  nullptr, "__objc_id_type_info");
2543     return IDEHType;
2544   }
2545 
2546   const ObjCObjectPointerType *PT =
2547     T->getAs<ObjCObjectPointerType>();
2548   assert(PT && "Invalid @catch type.");
2549   const ObjCInterfaceType *IT = PT->getInterfaceType();
2550   assert(IT && "Invalid @catch type.");
2551   std::string className =
2552       std::string(IT->getDecl()->getIdentifier()->getName());
2553 
2554   std::string typeinfoName = "__objc_eh_typeinfo_" + className;
2555 
2556   // Return the existing typeinfo if it exists
2557   if (llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName))
2558     return typeinfo;
2559 
2560   // Otherwise create it.
2561 
2562   // vtable for gnustep::libobjc::__objc_class_type_info
2563   // It's quite ugly hard-coding this.  Ideally we'd generate it using the host
2564   // platform's name mangling.
2565   const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
2566   auto *Vtable = TheModule.getGlobalVariable(vtableName);
2567   if (!Vtable) {
2568     Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
2569                                       llvm::GlobalValue::ExternalLinkage,
2570                                       nullptr, vtableName);
2571   }
2572   llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
2573   auto *BVtable =
2574       llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two);
2575 
2576   llvm::Constant *typeName =
2577     ExportUniqueString(className, "__objc_eh_typename_");
2578 
2579   ConstantInitBuilder builder(CGM);
2580   auto fields = builder.beginStruct();
2581   fields.add(BVtable);
2582   fields.add(typeName);
2583   llvm::Constant *TI =
2584     fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
2585                                  CGM.getPointerAlign(),
2586                                  /*constant*/ false,
2587                                  llvm::GlobalValue::LinkOnceODRLinkage);
2588   return TI;
2589 }
2590 
2591 /// Generate an NSConstantString object.
GenerateConstantString(const StringLiteral * SL)2592 ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
2593 
2594   std::string Str = SL->getString().str();
2595   CharUnits Align = CGM.getPointerAlign();
2596 
2597   // Look for an existing one
2598   llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
2599   if (old != ObjCStrings.end())
2600     return ConstantAddress(old->getValue(), Int8Ty, Align);
2601 
2602   StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
2603 
2604   if (StringClass.empty()) StringClass = "NSConstantString";
2605 
2606   std::string Sym = "_OBJC_CLASS_";
2607   Sym += StringClass;
2608 
2609   llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
2610 
2611   if (!isa)
2612     isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */ false,
2613                                    llvm::GlobalValue::ExternalWeakLinkage,
2614                                    nullptr, Sym);
2615 
2616   ConstantInitBuilder Builder(CGM);
2617   auto Fields = Builder.beginStruct();
2618   Fields.add(isa);
2619   Fields.add(MakeConstantString(Str));
2620   Fields.addInt(IntTy, Str.size());
2621   llvm::Constant *ObjCStr = Fields.finishAndCreateGlobal(".objc_str", Align);
2622   ObjCStrings[Str] = ObjCStr;
2623   ConstantStrings.push_back(ObjCStr);
2624   return ConstantAddress(ObjCStr, Int8Ty, Align);
2625 }
2626 
2627 ///Generates a message send where the super is the receiver.  This is a message
2628 ///send to self with special delivery semantics indicating which class's method
2629 ///should be called.
2630 RValue
GenerateMessageSendSuper(CodeGenFunction & CGF,ReturnValueSlot Return,QualType ResultType,Selector Sel,const ObjCInterfaceDecl * Class,bool isCategoryImpl,llvm::Value * Receiver,bool IsClassMessage,const CallArgList & CallArgs,const ObjCMethodDecl * Method)2631 CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
2632                                     ReturnValueSlot Return,
2633                                     QualType ResultType,
2634                                     Selector Sel,
2635                                     const ObjCInterfaceDecl *Class,
2636                                     bool isCategoryImpl,
2637                                     llvm::Value *Receiver,
2638                                     bool IsClassMessage,
2639                                     const CallArgList &CallArgs,
2640                                     const ObjCMethodDecl *Method) {
2641   CGBuilderTy &Builder = CGF.Builder;
2642   if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
2643     if (Sel == RetainSel || Sel == AutoreleaseSel) {
2644       return RValue::get(EnforceType(Builder, Receiver,
2645                   CGM.getTypes().ConvertType(ResultType)));
2646     }
2647     if (Sel == ReleaseSel) {
2648       return RValue::get(nullptr);
2649     }
2650   }
2651 
2652   llvm::Value *cmd = GetSelector(CGF, Sel);
2653   CallArgList ActualArgs;
2654 
2655   ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
2656   ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
2657   ActualArgs.addFrom(CallArgs);
2658 
2659   MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
2660 
2661   llvm::Value *ReceiverClass = nullptr;
2662   bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2663   if (isV2ABI) {
2664     ReceiverClass = GetClassNamed(CGF,
2665         Class->getSuperClass()->getNameAsString(), /*isWeak*/false);
2666     if (IsClassMessage)  {
2667       // Load the isa pointer of the superclass is this is a class method.
2668       ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2669                                             llvm::PointerType::getUnqual(IdTy));
2670       ReceiverClass =
2671         Builder.CreateAlignedLoad(IdTy, ReceiverClass, CGF.getPointerAlign());
2672     }
2673     ReceiverClass = EnforceType(Builder, ReceiverClass, IdTy);
2674   } else {
2675     if (isCategoryImpl) {
2676       llvm::FunctionCallee classLookupFunction = nullptr;
2677       if (IsClassMessage)  {
2678         classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2679               IdTy, PtrTy, true), "objc_get_meta_class");
2680       } else {
2681         classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2682               IdTy, PtrTy, true), "objc_get_class");
2683       }
2684       ReceiverClass = Builder.CreateCall(classLookupFunction,
2685           MakeConstantString(Class->getNameAsString()));
2686     } else {
2687       // Set up global aliases for the metaclass or class pointer if they do not
2688       // already exist.  These will are forward-references which will be set to
2689       // pointers to the class and metaclass structure created for the runtime
2690       // load function.  To send a message to super, we look up the value of the
2691       // super_class pointer from either the class or metaclass structure.
2692       if (IsClassMessage)  {
2693         if (!MetaClassPtrAlias) {
2694           MetaClassPtrAlias = llvm::GlobalAlias::create(
2695               IdElemTy, 0, llvm::GlobalValue::InternalLinkage,
2696               ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
2697         }
2698         ReceiverClass = MetaClassPtrAlias;
2699       } else {
2700         if (!ClassPtrAlias) {
2701           ClassPtrAlias = llvm::GlobalAlias::create(
2702               IdElemTy, 0, llvm::GlobalValue::InternalLinkage,
2703               ".objc_class_ref" + Class->getNameAsString(), &TheModule);
2704         }
2705         ReceiverClass = ClassPtrAlias;
2706       }
2707     }
2708     // Cast the pointer to a simplified version of the class structure
2709     llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);
2710     ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2711                                           llvm::PointerType::getUnqual(CastTy));
2712     // Get the superclass pointer
2713     ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
2714     // Load the superclass pointer
2715     ReceiverClass =
2716       Builder.CreateAlignedLoad(IdTy, ReceiverClass, CGF.getPointerAlign());
2717   }
2718   // Construct the structure used to look up the IMP
2719   llvm::StructType *ObjCSuperTy =
2720       llvm::StructType::get(Receiver->getType(), IdTy);
2721 
2722   Address ObjCSuper = CGF.CreateTempAlloca(ObjCSuperTy,
2723                               CGF.getPointerAlign());
2724 
2725   Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
2726   Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
2727 
2728   // Get the IMP
2729   llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
2730   imp = EnforceType(Builder, imp, MSI.MessengerType);
2731 
2732   llvm::Metadata *impMD[] = {
2733       llvm::MDString::get(VMContext, Sel.getAsString()),
2734       llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
2735       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2736           llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
2737   llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
2738 
2739   CGCallee callee(CGCalleeInfo(), imp);
2740 
2741   llvm::CallBase *call;
2742   RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
2743   call->setMetadata(msgSendMDKind, node);
2744   return msgRet;
2745 }
2746 
2747 /// Generate code for a message send expression.
2748 RValue
GenerateMessageSend(CodeGenFunction & CGF,ReturnValueSlot Return,QualType ResultType,Selector Sel,llvm::Value * Receiver,const CallArgList & CallArgs,const ObjCInterfaceDecl * Class,const ObjCMethodDecl * Method)2749 CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
2750                                ReturnValueSlot Return,
2751                                QualType ResultType,
2752                                Selector Sel,
2753                                llvm::Value *Receiver,
2754                                const CallArgList &CallArgs,
2755                                const ObjCInterfaceDecl *Class,
2756                                const ObjCMethodDecl *Method) {
2757   CGBuilderTy &Builder = CGF.Builder;
2758 
2759   // Strip out message sends to retain / release in GC mode
2760   if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
2761     if (Sel == RetainSel || Sel == AutoreleaseSel) {
2762       return RValue::get(EnforceType(Builder, Receiver,
2763                   CGM.getTypes().ConvertType(ResultType)));
2764     }
2765     if (Sel == ReleaseSel) {
2766       return RValue::get(nullptr);
2767     }
2768   }
2769 
2770   bool isDirect = Method && Method->isDirectMethod();
2771 
2772   IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
2773   llvm::Value *cmd;
2774   if (!isDirect) {
2775     if (Method)
2776       cmd = GetSelector(CGF, Method);
2777     else
2778       cmd = GetSelector(CGF, Sel);
2779     cmd = EnforceType(Builder, cmd, SelectorTy);
2780   }
2781 
2782   Receiver = EnforceType(Builder, Receiver, IdTy);
2783 
2784   llvm::Metadata *impMD[] = {
2785       llvm::MDString::get(VMContext, Sel.getAsString()),
2786       llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
2787       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2788           llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
2789   llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
2790 
2791   CallArgList ActualArgs;
2792   ActualArgs.add(RValue::get(Receiver), ASTIdTy);
2793   if (!isDirect)
2794     ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
2795   ActualArgs.addFrom(CallArgs);
2796 
2797   MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
2798 
2799   // Message sends are expected to return a zero value when the
2800   // receiver is nil.  At one point, this was only guaranteed for
2801   // simple integer and pointer types, but expectations have grown
2802   // over time.
2803   //
2804   // Given a nil receiver, the GNU runtime's message lookup will
2805   // return a stub function that simply sets various return-value
2806   // registers to zero and then returns.  That's good enough for us
2807   // if and only if (1) the calling conventions of that stub are
2808   // compatible with the signature we're using and (2) the registers
2809   // it sets are sufficient to produce a zero value of the return type.
2810   // Rather than doing a whole target-specific analysis, we assume it
2811   // only works for void, integer, and pointer types, and in all
2812   // other cases we do an explicit nil check is emitted code.  In
2813   // addition to ensuring we produce a zero value for other types, this
2814   // sidesteps the few outright CC incompatibilities we know about that
2815   // could otherwise lead to crashes, like when a method is expected to
2816   // return on the x87 floating point stack or adjust the stack pointer
2817   // because of an indirect return.
2818   bool hasParamDestroyedInCallee = false;
2819   bool requiresExplicitZeroResult = false;
2820   bool requiresNilReceiverCheck = [&] {
2821     // We never need a check if we statically know the receiver isn't nil.
2822     if (!canMessageReceiverBeNull(CGF, Method, /*IsSuper*/ false,
2823                                   Class, Receiver))
2824       return false;
2825 
2826     // If there's a consumed argument, we need a nil check.
2827     if (Method && Method->hasParamDestroyedInCallee()) {
2828       hasParamDestroyedInCallee = true;
2829     }
2830 
2831     // If the return value isn't flagged as unused, and the result
2832     // type isn't in our narrow set where we assume compatibility,
2833     // we need a nil check to ensure a nil value.
2834     if (!Return.isUnused()) {
2835       if (ResultType->isVoidType()) {
2836         // void results are definitely okay.
2837       } else if (ResultType->hasPointerRepresentation() &&
2838                  CGM.getTypes().isZeroInitializable(ResultType)) {
2839         // Pointer types should be fine as long as they have
2840         // bitwise-zero null pointers.  But do we need to worry
2841         // about unusual address spaces?
2842       } else if (ResultType->isIntegralOrEnumerationType()) {
2843         // Bitwise zero should always be zero for integral types.
2844         // FIXME: we probably need a size limit here, but we've
2845         // never imposed one before
2846       } else {
2847         // Otherwise, use an explicit check just to be sure, unless we're
2848         // calling a direct method, where the implementation does this for us.
2849         requiresExplicitZeroResult = !isDirect;
2850       }
2851     }
2852 
2853     return hasParamDestroyedInCallee || requiresExplicitZeroResult;
2854   }();
2855 
2856   // We will need to explicitly zero-initialize an aggregate result slot
2857   // if we generally require explicit zeroing and we have an aggregate
2858   // result.
2859   bool requiresExplicitAggZeroing =
2860     requiresExplicitZeroResult && CGF.hasAggregateEvaluationKind(ResultType);
2861 
2862   // The block we're going to end up in after any message send or nil path.
2863   llvm::BasicBlock *continueBB = nullptr;
2864   // The block that eventually branched to continueBB along the nil path.
2865   llvm::BasicBlock *nilPathBB = nullptr;
2866   // The block to do explicit work in along the nil path, if necessary.
2867   llvm::BasicBlock *nilCleanupBB = nullptr;
2868 
2869   // Emit the nil-receiver check.
2870   if (requiresNilReceiverCheck) {
2871     llvm::BasicBlock *messageBB = CGF.createBasicBlock("msgSend");
2872     continueBB = CGF.createBasicBlock("continue");
2873 
2874     // If we need to zero-initialize an aggregate result or destroy
2875     // consumed arguments, we'll need a separate cleanup block.
2876     // Otherwise we can just branch directly to the continuation block.
2877     if (requiresExplicitAggZeroing || hasParamDestroyedInCallee) {
2878       nilCleanupBB = CGF.createBasicBlock("nilReceiverCleanup");
2879     } else {
2880       nilPathBB = Builder.GetInsertBlock();
2881     }
2882 
2883     llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
2884             llvm::Constant::getNullValue(Receiver->getType()));
2885     Builder.CreateCondBr(isNil, nilCleanupBB ? nilCleanupBB : continueBB,
2886                          messageBB);
2887     CGF.EmitBlock(messageBB);
2888   }
2889 
2890   // Get the IMP to call
2891   llvm::Value *imp;
2892 
2893   // If this is a direct method, just emit it here.
2894   if (isDirect)
2895     imp = GenerateMethod(Method, Method->getClassInterface());
2896   else
2897     // If we have non-legacy dispatch specified, we try using the
2898     // objc_msgSend() functions.  These are not supported on all platforms
2899     // (or all runtimes on a given platform), so we
2900     switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
2901     case CodeGenOptions::Legacy:
2902       imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
2903       break;
2904     case CodeGenOptions::Mixed:
2905     case CodeGenOptions::NonLegacy:
2906       StringRef name = "objc_msgSend";
2907       if (CGM.ReturnTypeUsesFPRet(ResultType)) {
2908         name = "objc_msgSend_fpret";
2909       } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
2910         name = "objc_msgSend_stret";
2911 
2912         // The address of the memory block is be passed in x8 for POD type,
2913         // or in x0 for non-POD type (marked as inreg).
2914         bool shouldCheckForInReg =
2915             CGM.getContext()
2916                 .getTargetInfo()
2917                 .getTriple()
2918                 .isWindowsMSVCEnvironment() &&
2919             CGM.getContext().getTargetInfo().getTriple().isAArch64();
2920         if (shouldCheckForInReg && CGM.ReturnTypeHasInReg(MSI.CallInfo)) {
2921           name = "objc_msgSend_stret2";
2922         }
2923       }
2924       // The actual types here don't matter - we're going to bitcast the
2925       // function anyway
2926       imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2927                                       name)
2928                 .getCallee();
2929     }
2930 
2931   // Reset the receiver in case the lookup modified it
2932   ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy);
2933 
2934   imp = EnforceType(Builder, imp, MSI.MessengerType);
2935 
2936   llvm::CallBase *call;
2937   CGCallee callee(CGCalleeInfo(), imp);
2938   RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
2939   if (!isDirect)
2940     call->setMetadata(msgSendMDKind, node);
2941 
2942   if (requiresNilReceiverCheck) {
2943     llvm::BasicBlock *nonNilPathBB = CGF.Builder.GetInsertBlock();
2944     CGF.Builder.CreateBr(continueBB);
2945 
2946     // Emit the nil path if we decided it was necessary above.
2947     if (nilCleanupBB) {
2948       CGF.EmitBlock(nilCleanupBB);
2949 
2950       if (hasParamDestroyedInCallee) {
2951         destroyCalleeDestroyedArguments(CGF, Method, CallArgs);
2952       }
2953 
2954       if (requiresExplicitAggZeroing) {
2955         assert(msgRet.isAggregate());
2956         Address addr = msgRet.getAggregateAddress();
2957         CGF.EmitNullInitialization(addr, ResultType);
2958       }
2959 
2960       nilPathBB = CGF.Builder.GetInsertBlock();
2961       CGF.Builder.CreateBr(continueBB);
2962     }
2963 
2964     // Enter the continuation block and emit a phi if required.
2965     CGF.EmitBlock(continueBB);
2966     if (msgRet.isScalar()) {
2967       // If the return type is void, do nothing
2968       if (llvm::Value *v = msgRet.getScalarVal()) {
2969         llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
2970         phi->addIncoming(v, nonNilPathBB);
2971         phi->addIncoming(CGM.EmitNullConstant(ResultType), nilPathBB);
2972         msgRet = RValue::get(phi);
2973       }
2974     } else if (msgRet.isAggregate()) {
2975       // Aggregate zeroing is handled in nilCleanupBB when it's required.
2976     } else /* isComplex() */ {
2977       std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
2978       llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
2979       phi->addIncoming(v.first, nonNilPathBB);
2980       phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
2981                        nilPathBB);
2982       llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
2983       phi2->addIncoming(v.second, nonNilPathBB);
2984       phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
2985                         nilPathBB);
2986       msgRet = RValue::getComplex(phi, phi2);
2987     }
2988   }
2989   return msgRet;
2990 }
2991 
2992 /// Generates a MethodList.  Used in construction of a objc_class and
2993 /// objc_category structures.
2994 llvm::Constant *CGObjCGNU::
GenerateMethodList(StringRef ClassName,StringRef CategoryName,ArrayRef<const ObjCMethodDecl * > Methods,bool isClassMethodList)2995 GenerateMethodList(StringRef ClassName,
2996                    StringRef CategoryName,
2997                    ArrayRef<const ObjCMethodDecl*> Methods,
2998                    bool isClassMethodList) {
2999   if (Methods.empty())
3000     return NULLPtr;
3001 
3002   ConstantInitBuilder Builder(CGM);
3003 
3004   auto MethodList = Builder.beginStruct();
3005   MethodList.addNullPointer(CGM.Int8PtrTy);
3006   MethodList.addInt(Int32Ty, Methods.size());
3007 
3008   // Get the method structure type.
3009   llvm::StructType *ObjCMethodTy =
3010     llvm::StructType::get(CGM.getLLVMContext(), {
3011       PtrToInt8Ty, // Really a selector, but the runtime creates it us.
3012       PtrToInt8Ty, // Method types
3013       IMPTy        // Method pointer
3014     });
3015   bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
3016   if (isV2ABI) {
3017     // size_t size;
3018     llvm::DataLayout td(&TheModule);
3019     MethodList.addInt(SizeTy, td.getTypeSizeInBits(ObjCMethodTy) /
3020         CGM.getContext().getCharWidth());
3021     ObjCMethodTy =
3022       llvm::StructType::get(CGM.getLLVMContext(), {
3023         IMPTy,       // Method pointer
3024         PtrToInt8Ty, // Selector
3025         PtrToInt8Ty  // Extended type encoding
3026       });
3027   } else {
3028     ObjCMethodTy =
3029       llvm::StructType::get(CGM.getLLVMContext(), {
3030         PtrToInt8Ty, // Really a selector, but the runtime creates it us.
3031         PtrToInt8Ty, // Method types
3032         IMPTy        // Method pointer
3033       });
3034   }
3035   auto MethodArray = MethodList.beginArray();
3036   ASTContext &Context = CGM.getContext();
3037   for (const auto *OMD : Methods) {
3038     llvm::Constant *FnPtr =
3039       TheModule.getFunction(getSymbolNameForMethod(OMD));
3040     assert(FnPtr && "Can't generate metadata for method that doesn't exist");
3041     auto Method = MethodArray.beginStruct(ObjCMethodTy);
3042     if (isV2ABI) {
3043       Method.add(FnPtr);
3044       Method.add(GetConstantSelector(OMD->getSelector(),
3045           Context.getObjCEncodingForMethodDecl(OMD)));
3046       Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD, true)));
3047     } else {
3048       Method.add(MakeConstantString(OMD->getSelector().getAsString()));
3049       Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD)));
3050       Method.add(FnPtr);
3051     }
3052     Method.finishAndAddTo(MethodArray);
3053   }
3054   MethodArray.finishAndAddTo(MethodList);
3055 
3056   // Create an instance of the structure
3057   return MethodList.finishAndCreateGlobal(".objc_method_list",
3058                                           CGM.getPointerAlign());
3059 }
3060 
3061 /// Generates an IvarList.  Used in construction of a objc_class.
3062 llvm::Constant *CGObjCGNU::
GenerateIvarList(ArrayRef<llvm::Constant * > IvarNames,ArrayRef<llvm::Constant * > IvarTypes,ArrayRef<llvm::Constant * > IvarOffsets,ArrayRef<llvm::Constant * > IvarAlign,ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership)3063 GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
3064                  ArrayRef<llvm::Constant *> IvarTypes,
3065                  ArrayRef<llvm::Constant *> IvarOffsets,
3066                  ArrayRef<llvm::Constant *> IvarAlign,
3067                  ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) {
3068   if (IvarNames.empty())
3069     return NULLPtr;
3070 
3071   ConstantInitBuilder Builder(CGM);
3072 
3073   // Structure containing array count followed by array.
3074   auto IvarList = Builder.beginStruct();
3075   IvarList.addInt(IntTy, (int)IvarNames.size());
3076 
3077   // Get the ivar structure type.
3078   llvm::StructType *ObjCIvarTy =
3079       llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);
3080 
3081   // Array of ivar structures.
3082   auto Ivars = IvarList.beginArray(ObjCIvarTy);
3083   for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
3084     auto Ivar = Ivars.beginStruct(ObjCIvarTy);
3085     Ivar.add(IvarNames[i]);
3086     Ivar.add(IvarTypes[i]);
3087     Ivar.add(IvarOffsets[i]);
3088     Ivar.finishAndAddTo(Ivars);
3089   }
3090   Ivars.finishAndAddTo(IvarList);
3091 
3092   // Create an instance of the structure
3093   return IvarList.finishAndCreateGlobal(".objc_ivar_list",
3094                                         CGM.getPointerAlign());
3095 }
3096 
3097 /// Generate a class structure
GenerateClassStructure(llvm::Constant * MetaClass,llvm::Constant * SuperClass,unsigned info,const char * Name,llvm::Constant * Version,llvm::Constant * InstanceSize,llvm::Constant * IVars,llvm::Constant * Methods,llvm::Constant * Protocols,llvm::Constant * IvarOffsets,llvm::Constant * Properties,llvm::Constant * StrongIvarBitmap,llvm::Constant * WeakIvarBitmap,bool isMeta)3098 llvm::Constant *CGObjCGNU::GenerateClassStructure(
3099     llvm::Constant *MetaClass,
3100     llvm::Constant *SuperClass,
3101     unsigned info,
3102     const char *Name,
3103     llvm::Constant *Version,
3104     llvm::Constant *InstanceSize,
3105     llvm::Constant *IVars,
3106     llvm::Constant *Methods,
3107     llvm::Constant *Protocols,
3108     llvm::Constant *IvarOffsets,
3109     llvm::Constant *Properties,
3110     llvm::Constant *StrongIvarBitmap,
3111     llvm::Constant *WeakIvarBitmap,
3112     bool isMeta) {
3113   // Set up the class structure
3114   // Note:  Several of these are char*s when they should be ids.  This is
3115   // because the runtime performs this translation on load.
3116   //
3117   // Fields marked New ABI are part of the GNUstep runtime.  We emit them
3118   // anyway; the classes will still work with the GNU runtime, they will just
3119   // be ignored.
3120   llvm::StructType *ClassTy = llvm::StructType::get(
3121       PtrToInt8Ty,        // isa
3122       PtrToInt8Ty,        // super_class
3123       PtrToInt8Ty,        // name
3124       LongTy,             // version
3125       LongTy,             // info
3126       LongTy,             // instance_size
3127       IVars->getType(),   // ivars
3128       Methods->getType(), // methods
3129       // These are all filled in by the runtime, so we pretend
3130       PtrTy, // dtable
3131       PtrTy, // subclass_list
3132       PtrTy, // sibling_class
3133       PtrTy, // protocols
3134       PtrTy, // gc_object_type
3135       // New ABI:
3136       LongTy,                 // abi_version
3137       IvarOffsets->getType(), // ivar_offsets
3138       Properties->getType(),  // properties
3139       IntPtrTy,               // strong_pointers
3140       IntPtrTy                // weak_pointers
3141       );
3142 
3143   ConstantInitBuilder Builder(CGM);
3144   auto Elements = Builder.beginStruct(ClassTy);
3145 
3146   // Fill in the structure
3147 
3148   // isa
3149   Elements.add(MetaClass);
3150   // super_class
3151   Elements.add(SuperClass);
3152   // name
3153   Elements.add(MakeConstantString(Name, ".class_name"));
3154   // version
3155   Elements.addInt(LongTy, 0);
3156   // info
3157   Elements.addInt(LongTy, info);
3158   // instance_size
3159   if (isMeta) {
3160     llvm::DataLayout td(&TheModule);
3161     Elements.addInt(LongTy,
3162                     td.getTypeSizeInBits(ClassTy) /
3163                       CGM.getContext().getCharWidth());
3164   } else
3165     Elements.add(InstanceSize);
3166   // ivars
3167   Elements.add(IVars);
3168   // methods
3169   Elements.add(Methods);
3170   // These are all filled in by the runtime, so we pretend
3171   // dtable
3172   Elements.add(NULLPtr);
3173   // subclass_list
3174   Elements.add(NULLPtr);
3175   // sibling_class
3176   Elements.add(NULLPtr);
3177   // protocols
3178   Elements.add(Protocols);
3179   // gc_object_type
3180   Elements.add(NULLPtr);
3181   // abi_version
3182   Elements.addInt(LongTy, ClassABIVersion);
3183   // ivar_offsets
3184   Elements.add(IvarOffsets);
3185   // properties
3186   Elements.add(Properties);
3187   // strong_pointers
3188   Elements.add(StrongIvarBitmap);
3189   // weak_pointers
3190   Elements.add(WeakIvarBitmap);
3191   // Create an instance of the structure
3192   // This is now an externally visible symbol, so that we can speed up class
3193   // messages in the next ABI.  We may already have some weak references to
3194   // this, so check and fix them properly.
3195   std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
3196           std::string(Name));
3197   llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
3198   llvm::Constant *Class =
3199     Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
3200                                    llvm::GlobalValue::ExternalLinkage);
3201   if (ClassRef) {
3202     ClassRef->replaceAllUsesWith(Class);
3203     ClassRef->removeFromParent();
3204     Class->setName(ClassSym);
3205   }
3206   return Class;
3207 }
3208 
3209 llvm::Constant *CGObjCGNU::
GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl * > Methods)3210 GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) {
3211   // Get the method structure type.
3212   llvm::StructType *ObjCMethodDescTy =
3213     llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
3214   ASTContext &Context = CGM.getContext();
3215   ConstantInitBuilder Builder(CGM);
3216   auto MethodList = Builder.beginStruct();
3217   MethodList.addInt(IntTy, Methods.size());
3218   auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
3219   for (auto *M : Methods) {
3220     auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
3221     Method.add(MakeConstantString(M->getSelector().getAsString()));
3222     Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(M)));
3223     Method.finishAndAddTo(MethodArray);
3224   }
3225   MethodArray.finishAndAddTo(MethodList);
3226   return MethodList.finishAndCreateGlobal(".objc_method_list",
3227                                           CGM.getPointerAlign());
3228 }
3229 
3230 // Create the protocol list structure used in classes, categories and so on
3231 llvm::Constant *
GenerateProtocolList(ArrayRef<std::string> Protocols)3232 CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
3233 
3234   ConstantInitBuilder Builder(CGM);
3235   auto ProtocolList = Builder.beginStruct();
3236   ProtocolList.add(NULLPtr);
3237   ProtocolList.addInt(LongTy, Protocols.size());
3238 
3239   auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
3240   for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
3241       iter != endIter ; iter++) {
3242     llvm::Constant *protocol = nullptr;
3243     llvm::StringMap<llvm::Constant*>::iterator value =
3244       ExistingProtocols.find(*iter);
3245     if (value == ExistingProtocols.end()) {
3246       protocol = GenerateEmptyProtocol(*iter);
3247     } else {
3248       protocol = value->getValue();
3249     }
3250     Elements.add(protocol);
3251   }
3252   Elements.finishAndAddTo(ProtocolList);
3253   return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3254                                             CGM.getPointerAlign());
3255 }
3256 
GenerateProtocolRef(CodeGenFunction & CGF,const ObjCProtocolDecl * PD)3257 llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
3258                                             const ObjCProtocolDecl *PD) {
3259   auto protocol = GenerateProtocolRef(PD);
3260   llvm::Type *T =
3261       CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
3262   return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
3263 }
3264 
GenerateProtocolRef(const ObjCProtocolDecl * PD)3265 llvm::Constant *CGObjCGNU::GenerateProtocolRef(const ObjCProtocolDecl *PD) {
3266   llvm::Constant *&protocol = ExistingProtocols[PD->getNameAsString()];
3267   if (!protocol)
3268     GenerateProtocol(PD);
3269   assert(protocol && "Unknown protocol");
3270   return protocol;
3271 }
3272 
3273 llvm::Constant *
GenerateEmptyProtocol(StringRef ProtocolName)3274 CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) {
3275   llvm::Constant *ProtocolList = GenerateProtocolList({});
3276   llvm::Constant *MethodList = GenerateProtocolMethodList({});
3277   // Protocols are objects containing lists of the methods implemented and
3278   // protocols adopted.
3279   ConstantInitBuilder Builder(CGM);
3280   auto Elements = Builder.beginStruct();
3281 
3282   // The isa pointer must be set to a magic number so the runtime knows it's
3283   // the correct layout.
3284   Elements.add(llvm::ConstantExpr::getIntToPtr(
3285           llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
3286 
3287   Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
3288   Elements.add(ProtocolList); /* .protocol_list */
3289   Elements.add(MethodList);   /* .instance_methods */
3290   Elements.add(MethodList);   /* .class_methods */
3291   Elements.add(MethodList);   /* .optional_instance_methods */
3292   Elements.add(MethodList);   /* .optional_class_methods */
3293   Elements.add(NULLPtr);      /* .properties */
3294   Elements.add(NULLPtr);      /* .optional_properties */
3295   return Elements.finishAndCreateGlobal(SymbolForProtocol(ProtocolName),
3296                                         CGM.getPointerAlign());
3297 }
3298 
GenerateProtocol(const ObjCProtocolDecl * PD)3299 void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
3300   if (PD->isNonRuntimeProtocol())
3301     return;
3302 
3303   std::string ProtocolName = PD->getNameAsString();
3304 
3305   // Use the protocol definition, if there is one.
3306   if (const ObjCProtocolDecl *Def = PD->getDefinition())
3307     PD = Def;
3308 
3309   SmallVector<std::string, 16> Protocols;
3310   for (const auto *PI : PD->protocols())
3311     Protocols.push_back(PI->getNameAsString());
3312   SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3313   SmallVector<const ObjCMethodDecl*, 16> OptionalInstanceMethods;
3314   for (const auto *I : PD->instance_methods())
3315     if (I->isOptional())
3316       OptionalInstanceMethods.push_back(I);
3317     else
3318       InstanceMethods.push_back(I);
3319   // Collect information about class methods:
3320   SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3321   SmallVector<const ObjCMethodDecl*, 16> OptionalClassMethods;
3322   for (const auto *I : PD->class_methods())
3323     if (I->isOptional())
3324       OptionalClassMethods.push_back(I);
3325     else
3326       ClassMethods.push_back(I);
3327 
3328   llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
3329   llvm::Constant *InstanceMethodList =
3330     GenerateProtocolMethodList(InstanceMethods);
3331   llvm::Constant *ClassMethodList =
3332     GenerateProtocolMethodList(ClassMethods);
3333   llvm::Constant *OptionalInstanceMethodList =
3334     GenerateProtocolMethodList(OptionalInstanceMethods);
3335   llvm::Constant *OptionalClassMethodList =
3336     GenerateProtocolMethodList(OptionalClassMethods);
3337 
3338   // Property metadata: name, attributes, isSynthesized, setter name, setter
3339   // types, getter name, getter types.
3340   // The isSynthesized value is always set to 0 in a protocol.  It exists to
3341   // simplify the runtime library by allowing it to use the same data
3342   // structures for protocol metadata everywhere.
3343 
3344   llvm::Constant *PropertyList =
3345     GeneratePropertyList(nullptr, PD, false, false);
3346   llvm::Constant *OptionalPropertyList =
3347     GeneratePropertyList(nullptr, PD, false, true);
3348 
3349   // Protocols are objects containing lists of the methods implemented and
3350   // protocols adopted.
3351   // The isa pointer must be set to a magic number so the runtime knows it's
3352   // the correct layout.
3353   ConstantInitBuilder Builder(CGM);
3354   auto Elements = Builder.beginStruct();
3355   Elements.add(
3356       llvm::ConstantExpr::getIntToPtr(
3357           llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
3358   Elements.add(MakeConstantString(ProtocolName));
3359   Elements.add(ProtocolList);
3360   Elements.add(InstanceMethodList);
3361   Elements.add(ClassMethodList);
3362   Elements.add(OptionalInstanceMethodList);
3363   Elements.add(OptionalClassMethodList);
3364   Elements.add(PropertyList);
3365   Elements.add(OptionalPropertyList);
3366   ExistingProtocols[ProtocolName] =
3367       Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign());
3368 }
GenerateProtocolHolderCategory()3369 void CGObjCGNU::GenerateProtocolHolderCategory() {
3370   // Collect information about instance methods
3371 
3372   ConstantInitBuilder Builder(CGM);
3373   auto Elements = Builder.beginStruct();
3374 
3375   const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
3376   const std::string CategoryName = "AnotherHack";
3377   Elements.add(MakeConstantString(CategoryName));
3378   Elements.add(MakeConstantString(ClassName));
3379   // Instance method list
3380   Elements.add(GenerateMethodList(ClassName, CategoryName, {}, false));
3381   // Class method list
3382   Elements.add(GenerateMethodList(ClassName, CategoryName, {}, true));
3383 
3384   // Protocol list
3385   ConstantInitBuilder ProtocolListBuilder(CGM);
3386   auto ProtocolList = ProtocolListBuilder.beginStruct();
3387   ProtocolList.add(NULLPtr);
3388   ProtocolList.addInt(LongTy, ExistingProtocols.size());
3389   auto ProtocolElements = ProtocolList.beginArray(PtrTy);
3390   for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
3391        iter != endIter ; iter++) {
3392     ProtocolElements.add(iter->getValue());
3393   }
3394   ProtocolElements.finishAndAddTo(ProtocolList);
3395   Elements.add(ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3396                                                   CGM.getPointerAlign()));
3397   Categories.push_back(
3398       Elements.finishAndCreateGlobal("", CGM.getPointerAlign()));
3399 }
3400 
3401 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
3402 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
3403 /// bits set to their values, LSB first, while larger ones are stored in a
3404 /// structure of this / form:
3405 ///
3406 /// struct { int32_t length; int32_t values[length]; };
3407 ///
3408 /// The values in the array are stored in host-endian format, with the least
3409 /// significant bit being assumed to come first in the bitfield.  Therefore, a
3410 /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
3411 /// bitfield / with the 63rd bit set will be 1<<64.
MakeBitField(ArrayRef<bool> bits)3412 llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
3413   int bitCount = bits.size();
3414   int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
3415   if (bitCount < ptrBits) {
3416     uint64_t val = 1;
3417     for (int i=0 ; i<bitCount ; ++i) {
3418       if (bits[i]) val |= 1ULL<<(i+1);
3419     }
3420     return llvm::ConstantInt::get(IntPtrTy, val);
3421   }
3422   SmallVector<llvm::Constant *, 8> values;
3423   int v=0;
3424   while (v < bitCount) {
3425     int32_t word = 0;
3426     for (int i=0 ; (i<32) && (v<bitCount)  ; ++i) {
3427       if (bits[v]) word |= 1<<i;
3428       v++;
3429     }
3430     values.push_back(llvm::ConstantInt::get(Int32Ty, word));
3431   }
3432 
3433   ConstantInitBuilder builder(CGM);
3434   auto fields = builder.beginStruct();
3435   fields.addInt(Int32Ty, values.size());
3436   auto array = fields.beginArray();
3437   for (auto *v : values) array.add(v);
3438   array.finishAndAddTo(fields);
3439 
3440   llvm::Constant *GS =
3441     fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
3442   llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
3443   return ptr;
3444 }
3445 
GenerateCategoryProtocolList(const ObjCCategoryDecl * OCD)3446 llvm::Constant *CGObjCGNU::GenerateCategoryProtocolList(const
3447     ObjCCategoryDecl *OCD) {
3448   const auto &RefPro = OCD->getReferencedProtocols();
3449   const auto RuntimeProtos =
3450       GetRuntimeProtocolList(RefPro.begin(), RefPro.end());
3451   SmallVector<std::string, 16> Protocols;
3452   for (const auto *PD : RuntimeProtos)
3453     Protocols.push_back(PD->getNameAsString());
3454   return GenerateProtocolList(Protocols);
3455 }
3456 
GenerateCategory(const ObjCCategoryImplDecl * OCD)3457 void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
3458   const ObjCInterfaceDecl *Class = OCD->getClassInterface();
3459   std::string ClassName = Class->getNameAsString();
3460   std::string CategoryName = OCD->getNameAsString();
3461 
3462   // Collect the names of referenced protocols
3463   const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
3464 
3465   ConstantInitBuilder Builder(CGM);
3466   auto Elements = Builder.beginStruct();
3467   Elements.add(MakeConstantString(CategoryName));
3468   Elements.add(MakeConstantString(ClassName));
3469   // Instance method list
3470   SmallVector<ObjCMethodDecl*, 16> InstanceMethods;
3471   InstanceMethods.insert(InstanceMethods.begin(), OCD->instmeth_begin(),
3472       OCD->instmeth_end());
3473   Elements.add(
3474       GenerateMethodList(ClassName, CategoryName, InstanceMethods, false));
3475 
3476   // Class method list
3477 
3478   SmallVector<ObjCMethodDecl*, 16> ClassMethods;
3479   ClassMethods.insert(ClassMethods.begin(), OCD->classmeth_begin(),
3480       OCD->classmeth_end());
3481   Elements.add(GenerateMethodList(ClassName, CategoryName, ClassMethods, true));
3482 
3483   // Protocol list
3484   Elements.add(GenerateCategoryProtocolList(CatDecl));
3485   if (isRuntime(ObjCRuntime::GNUstep, 2)) {
3486     const ObjCCategoryDecl *Category =
3487       Class->FindCategoryDeclaration(OCD->getIdentifier());
3488     if (Category) {
3489       // Instance properties
3490       Elements.add(GeneratePropertyList(OCD, Category, false));
3491       // Class properties
3492       Elements.add(GeneratePropertyList(OCD, Category, true));
3493     } else {
3494       Elements.addNullPointer(PtrTy);
3495       Elements.addNullPointer(PtrTy);
3496     }
3497   }
3498 
3499   Categories.push_back(Elements.finishAndCreateGlobal(
3500       std::string(".objc_category_") + ClassName + CategoryName,
3501       CGM.getPointerAlign()));
3502 }
3503 
GeneratePropertyList(const Decl * Container,const ObjCContainerDecl * OCD,bool isClassProperty,bool protocolOptionalProperties)3504 llvm::Constant *CGObjCGNU::GeneratePropertyList(const Decl *Container,
3505     const ObjCContainerDecl *OCD,
3506     bool isClassProperty,
3507     bool protocolOptionalProperties) {
3508 
3509   SmallVector<const ObjCPropertyDecl *, 16> Properties;
3510   llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
3511   bool isProtocol = isa<ObjCProtocolDecl>(OCD);
3512   ASTContext &Context = CGM.getContext();
3513 
3514   std::function<void(const ObjCProtocolDecl *Proto)> collectProtocolProperties
3515     = [&](const ObjCProtocolDecl *Proto) {
3516       for (const auto *P : Proto->protocols())
3517         collectProtocolProperties(P);
3518       for (const auto *PD : Proto->properties()) {
3519         if (isClassProperty != PD->isClassProperty())
3520           continue;
3521         // Skip any properties that are declared in protocols that this class
3522         // conforms to but are not actually implemented by this class.
3523         if (!isProtocol && !Context.getObjCPropertyImplDeclForPropertyDecl(PD, Container))
3524           continue;
3525         if (!PropertySet.insert(PD->getIdentifier()).second)
3526           continue;
3527         Properties.push_back(PD);
3528       }
3529     };
3530 
3531   if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3532     for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
3533       for (auto *PD : ClassExt->properties()) {
3534         if (isClassProperty != PD->isClassProperty())
3535           continue;
3536         PropertySet.insert(PD->getIdentifier());
3537         Properties.push_back(PD);
3538       }
3539 
3540   for (const auto *PD : OCD->properties()) {
3541     if (isClassProperty != PD->isClassProperty())
3542       continue;
3543     // If we're generating a list for a protocol, skip optional / required ones
3544     // when generating the other list.
3545     if (isProtocol && (protocolOptionalProperties != PD->isOptional()))
3546       continue;
3547     // Don't emit duplicate metadata for properties that were already in a
3548     // class extension.
3549     if (!PropertySet.insert(PD->getIdentifier()).second)
3550       continue;
3551 
3552     Properties.push_back(PD);
3553   }
3554 
3555   if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3556     for (const auto *P : OID->all_referenced_protocols())
3557       collectProtocolProperties(P);
3558   else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD))
3559     for (const auto *P : CD->protocols())
3560       collectProtocolProperties(P);
3561 
3562   auto numProperties = Properties.size();
3563 
3564   if (numProperties == 0)
3565     return NULLPtr;
3566 
3567   ConstantInitBuilder builder(CGM);
3568   auto propertyList = builder.beginStruct();
3569   auto properties = PushPropertyListHeader(propertyList, numProperties);
3570 
3571   // Add all of the property methods need adding to the method list and to the
3572   // property metadata list.
3573   for (auto *property : Properties) {
3574     bool isSynthesized = false;
3575     bool isDynamic = false;
3576     if (!isProtocol) {
3577       auto *propertyImpl = Context.getObjCPropertyImplDeclForPropertyDecl(property, Container);
3578       if (propertyImpl) {
3579         isSynthesized = (propertyImpl->getPropertyImplementation() ==
3580             ObjCPropertyImplDecl::Synthesize);
3581         isDynamic = (propertyImpl->getPropertyImplementation() ==
3582             ObjCPropertyImplDecl::Dynamic);
3583       }
3584     }
3585     PushProperty(properties, property, Container, isSynthesized, isDynamic);
3586   }
3587   properties.finishAndAddTo(propertyList);
3588 
3589   return propertyList.finishAndCreateGlobal(".objc_property_list",
3590                                             CGM.getPointerAlign());
3591 }
3592 
RegisterAlias(const ObjCCompatibleAliasDecl * OAD)3593 void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
3594   // Get the class declaration for which the alias is specified.
3595   ObjCInterfaceDecl *ClassDecl =
3596     const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
3597   ClassAliases.emplace_back(ClassDecl->getNameAsString(),
3598                             OAD->getNameAsString());
3599 }
3600 
GenerateClass(const ObjCImplementationDecl * OID)3601 void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
3602   ASTContext &Context = CGM.getContext();
3603 
3604   // Get the superclass name.
3605   const ObjCInterfaceDecl * SuperClassDecl =
3606     OID->getClassInterface()->getSuperClass();
3607   std::string SuperClassName;
3608   if (SuperClassDecl) {
3609     SuperClassName = SuperClassDecl->getNameAsString();
3610     EmitClassRef(SuperClassName);
3611   }
3612 
3613   // Get the class name
3614   ObjCInterfaceDecl *ClassDecl =
3615       const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
3616   std::string ClassName = ClassDecl->getNameAsString();
3617 
3618   // Emit the symbol that is used to generate linker errors if this class is
3619   // referenced in other modules but not declared.
3620   std::string classSymbolName = "__objc_class_name_" + ClassName;
3621   if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
3622     symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
3623   } else {
3624     new llvm::GlobalVariable(TheModule, LongTy, false,
3625                              llvm::GlobalValue::ExternalLinkage,
3626                              llvm::ConstantInt::get(LongTy, 0),
3627                              classSymbolName);
3628   }
3629 
3630   // Get the size of instances.
3631   int instanceSize =
3632     Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
3633 
3634   // Collect information about instance variables.
3635   SmallVector<llvm::Constant*, 16> IvarNames;
3636   SmallVector<llvm::Constant*, 16> IvarTypes;
3637   SmallVector<llvm::Constant*, 16> IvarOffsets;
3638   SmallVector<llvm::Constant*, 16> IvarAligns;
3639   SmallVector<Qualifiers::ObjCLifetime, 16> IvarOwnership;
3640 
3641   ConstantInitBuilder IvarOffsetBuilder(CGM);
3642   auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
3643   SmallVector<bool, 16> WeakIvars;
3644   SmallVector<bool, 16> StrongIvars;
3645 
3646   int superInstanceSize = !SuperClassDecl ? 0 :
3647     Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
3648   // For non-fragile ivars, set the instance size to 0 - {the size of just this
3649   // class}.  The runtime will then set this to the correct value on load.
3650   if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
3651     instanceSize = 0 - (instanceSize - superInstanceSize);
3652   }
3653 
3654   for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3655        IVD = IVD->getNextIvar()) {
3656       // Store the name
3657       IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
3658       // Get the type encoding for this ivar
3659       std::string TypeStr;
3660       Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);
3661       IvarTypes.push_back(MakeConstantString(TypeStr));
3662       IvarAligns.push_back(llvm::ConstantInt::get(IntTy,
3663             Context.getTypeSize(IVD->getType())));
3664       // Get the offset
3665       uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
3666       uint64_t Offset = BaseOffset;
3667       if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
3668         Offset = BaseOffset - superInstanceSize;
3669       }
3670       llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
3671       // Create the direct offset value
3672       std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
3673           IVD->getNameAsString();
3674 
3675       llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
3676       if (OffsetVar) {
3677         OffsetVar->setInitializer(OffsetValue);
3678         // If this is the real definition, change its linkage type so that
3679         // different modules will use this one, rather than their private
3680         // copy.
3681         OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
3682       } else
3683         OffsetVar = new llvm::GlobalVariable(TheModule, Int32Ty,
3684           false, llvm::GlobalValue::ExternalLinkage,
3685           OffsetValue, OffsetName);
3686       IvarOffsets.push_back(OffsetValue);
3687       IvarOffsetValues.add(OffsetVar);
3688       Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
3689       IvarOwnership.push_back(lt);
3690       switch (lt) {
3691         case Qualifiers::OCL_Strong:
3692           StrongIvars.push_back(true);
3693           WeakIvars.push_back(false);
3694           break;
3695         case Qualifiers::OCL_Weak:
3696           StrongIvars.push_back(false);
3697           WeakIvars.push_back(true);
3698           break;
3699         default:
3700           StrongIvars.push_back(false);
3701           WeakIvars.push_back(false);
3702       }
3703   }
3704   llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
3705   llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
3706   llvm::GlobalVariable *IvarOffsetArray =
3707     IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
3708                                            CGM.getPointerAlign());
3709 
3710   // Collect information about instance methods
3711   SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3712   InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
3713       OID->instmeth_end());
3714 
3715   SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3716   ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
3717       OID->classmeth_end());
3718 
3719   llvm::Constant *Properties = GeneratePropertyList(OID, ClassDecl);
3720 
3721   // Collect the names of referenced protocols
3722   auto RefProtocols = ClassDecl->protocols();
3723   auto RuntimeProtocols =
3724       GetRuntimeProtocolList(RefProtocols.begin(), RefProtocols.end());
3725   SmallVector<std::string, 16> Protocols;
3726   for (const auto *I : RuntimeProtocols)
3727     Protocols.push_back(I->getNameAsString());
3728 
3729   // Get the superclass pointer.
3730   llvm::Constant *SuperClass;
3731   if (!SuperClassName.empty()) {
3732     SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
3733   } else {
3734     SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
3735   }
3736   // Empty vector used to construct empty method lists
3737   SmallVector<llvm::Constant*, 1>  empty;
3738   // Generate the method and instance variable lists
3739   llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
3740       InstanceMethods, false);
3741   llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
3742       ClassMethods, true);
3743   llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
3744       IvarOffsets, IvarAligns, IvarOwnership);
3745   // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
3746   // we emit a symbol containing the offset for each ivar in the class.  This
3747   // allows code compiled for the non-Fragile ABI to inherit from code compiled
3748   // for the legacy ABI, without causing problems.  The converse is also
3749   // possible, but causes all ivar accesses to be fragile.
3750 
3751   // Offset pointer for getting at the correct field in the ivar list when
3752   // setting up the alias.  These are: The base address for the global, the
3753   // ivar array (second field), the ivar in this list (set for each ivar), and
3754   // the offset (third field in ivar structure)
3755   llvm::Type *IndexTy = Int32Ty;
3756   llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
3757       llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 2 : 1), nullptr,
3758       llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 3 : 2) };
3759 
3760   unsigned ivarIndex = 0;
3761   for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3762        IVD = IVD->getNextIvar()) {
3763       const std::string Name = GetIVarOffsetVariableName(ClassDecl, IVD);
3764       offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
3765       // Get the correct ivar field
3766       llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
3767           cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
3768           offsetPointerIndexes);
3769       // Get the existing variable, if one exists.
3770       llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
3771       if (offset) {
3772         offset->setInitializer(offsetValue);
3773         // If this is the real definition, change its linkage type so that
3774         // different modules will use this one, rather than their private
3775         // copy.
3776         offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
3777       } else
3778         // Add a new alias if there isn't one already.
3779         new llvm::GlobalVariable(TheModule, offsetValue->getType(),
3780                 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
3781       ++ivarIndex;
3782   }
3783   llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
3784 
3785   //Generate metaclass for class methods
3786   llvm::Constant *MetaClassStruct = GenerateClassStructure(
3787       NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
3788       NULLPtr, ClassMethodList, NULLPtr, NULLPtr,
3789       GeneratePropertyList(OID, ClassDecl, true), ZeroPtr, ZeroPtr, true);
3790   CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct),
3791                       OID->getClassInterface());
3792 
3793   // Generate the class structure
3794   llvm::Constant *ClassStruct = GenerateClassStructure(
3795       MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
3796       llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
3797       GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
3798       StrongIvarBitmap, WeakIvarBitmap);
3799   CGM.setGVProperties(cast<llvm::GlobalValue>(ClassStruct),
3800                       OID->getClassInterface());
3801 
3802   // Resolve the class aliases, if they exist.
3803   if (ClassPtrAlias) {
3804     ClassPtrAlias->replaceAllUsesWith(ClassStruct);
3805     ClassPtrAlias->eraseFromParent();
3806     ClassPtrAlias = nullptr;
3807   }
3808   if (MetaClassPtrAlias) {
3809     MetaClassPtrAlias->replaceAllUsesWith(MetaClassStruct);
3810     MetaClassPtrAlias->eraseFromParent();
3811     MetaClassPtrAlias = nullptr;
3812   }
3813 
3814   // Add class structure to list to be added to the symtab later
3815   Classes.push_back(ClassStruct);
3816 }
3817 
ModuleInitFunction()3818 llvm::Function *CGObjCGNU::ModuleInitFunction() {
3819   // Only emit an ObjC load function if no Objective-C stuff has been called
3820   if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
3821       ExistingProtocols.empty() && SelectorTable.empty())
3822     return nullptr;
3823 
3824   // Add all referenced protocols to a category.
3825   GenerateProtocolHolderCategory();
3826 
3827   llvm::StructType *selStructTy = dyn_cast<llvm::StructType>(SelectorElemTy);
3828   if (!selStructTy) {
3829     selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
3830                                         { PtrToInt8Ty, PtrToInt8Ty });
3831   }
3832 
3833   // Generate statics list:
3834   llvm::Constant *statics = NULLPtr;
3835   if (!ConstantStrings.empty()) {
3836     llvm::GlobalVariable *fileStatics = [&] {
3837       ConstantInitBuilder builder(CGM);
3838       auto staticsStruct = builder.beginStruct();
3839 
3840       StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
3841       if (stringClass.empty()) stringClass = "NXConstantString";
3842       staticsStruct.add(MakeConstantString(stringClass,
3843                                            ".objc_static_class_name"));
3844 
3845       auto array = staticsStruct.beginArray();
3846       array.addAll(ConstantStrings);
3847       array.add(NULLPtr);
3848       array.finishAndAddTo(staticsStruct);
3849 
3850       return staticsStruct.finishAndCreateGlobal(".objc_statics",
3851                                                  CGM.getPointerAlign());
3852     }();
3853 
3854     ConstantInitBuilder builder(CGM);
3855     auto allStaticsArray = builder.beginArray(fileStatics->getType());
3856     allStaticsArray.add(fileStatics);
3857     allStaticsArray.addNullPointer(fileStatics->getType());
3858 
3859     statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
3860                                                     CGM.getPointerAlign());
3861   }
3862 
3863   // Array of classes, categories, and constant objects.
3864 
3865   SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
3866   unsigned selectorCount;
3867 
3868   // Pointer to an array of selectors used in this module.
3869   llvm::GlobalVariable *selectorList = [&] {
3870     ConstantInitBuilder builder(CGM);
3871     auto selectors = builder.beginArray(selStructTy);
3872     auto &table = SelectorTable; // MSVC workaround
3873     std::vector<Selector> allSelectors;
3874     for (auto &entry : table)
3875       allSelectors.push_back(entry.first);
3876     llvm::sort(allSelectors);
3877 
3878     for (auto &untypedSel : allSelectors) {
3879       std::string selNameStr = untypedSel.getAsString();
3880       llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
3881 
3882       for (TypedSelector &sel : table[untypedSel]) {
3883         llvm::Constant *selectorTypeEncoding = NULLPtr;
3884         if (!sel.first.empty())
3885           selectorTypeEncoding =
3886             MakeConstantString(sel.first, ".objc_sel_types");
3887 
3888         auto selStruct = selectors.beginStruct(selStructTy);
3889         selStruct.add(selName);
3890         selStruct.add(selectorTypeEncoding);
3891         selStruct.finishAndAddTo(selectors);
3892 
3893         // Store the selector alias for later replacement
3894         selectorAliases.push_back(sel.second);
3895       }
3896     }
3897 
3898     // Remember the number of entries in the selector table.
3899     selectorCount = selectors.size();
3900 
3901     // NULL-terminate the selector list.  This should not actually be required,
3902     // because the selector list has a length field.  Unfortunately, the GCC
3903     // runtime decides to ignore the length field and expects a NULL terminator,
3904     // and GCC cooperates with this by always setting the length to 0.
3905     auto selStruct = selectors.beginStruct(selStructTy);
3906     selStruct.add(NULLPtr);
3907     selStruct.add(NULLPtr);
3908     selStruct.finishAndAddTo(selectors);
3909 
3910     return selectors.finishAndCreateGlobal(".objc_selector_list",
3911                                            CGM.getPointerAlign());
3912   }();
3913 
3914   // Now that all of the static selectors exist, create pointers to them.
3915   for (unsigned i = 0; i < selectorCount; ++i) {
3916     llvm::Constant *idxs[] = {
3917       Zeros[0],
3918       llvm::ConstantInt::get(Int32Ty, i)
3919     };
3920     // FIXME: We're generating redundant loads and stores here!
3921     llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
3922         selectorList->getValueType(), selectorList, idxs);
3923     selectorAliases[i]->replaceAllUsesWith(selPtr);
3924     selectorAliases[i]->eraseFromParent();
3925   }
3926 
3927   llvm::GlobalVariable *symtab = [&] {
3928     ConstantInitBuilder builder(CGM);
3929     auto symtab = builder.beginStruct();
3930 
3931     // Number of static selectors
3932     symtab.addInt(LongTy, selectorCount);
3933 
3934     symtab.add(selectorList);
3935 
3936     // Number of classes defined.
3937     symtab.addInt(CGM.Int16Ty, Classes.size());
3938     // Number of categories defined
3939     symtab.addInt(CGM.Int16Ty, Categories.size());
3940 
3941     // Create an array of classes, then categories, then static object instances
3942     auto classList = symtab.beginArray(PtrToInt8Ty);
3943     classList.addAll(Classes);
3944     classList.addAll(Categories);
3945     //  NULL-terminated list of static object instances (mainly constant strings)
3946     classList.add(statics);
3947     classList.add(NULLPtr);
3948     classList.finishAndAddTo(symtab);
3949 
3950     // Construct the symbol table.
3951     return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
3952   }();
3953 
3954   // The symbol table is contained in a module which has some version-checking
3955   // constants
3956   llvm::Constant *module = [&] {
3957     llvm::Type *moduleEltTys[] = {
3958       LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
3959     };
3960     llvm::StructType *moduleTy = llvm::StructType::get(
3961         CGM.getLLVMContext(),
3962         ArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
3963 
3964     ConstantInitBuilder builder(CGM);
3965     auto module = builder.beginStruct(moduleTy);
3966     // Runtime version, used for ABI compatibility checking.
3967     module.addInt(LongTy, RuntimeVersion);
3968     // sizeof(ModuleTy)
3969     module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
3970 
3971     // The path to the source file where this module was declared
3972     SourceManager &SM = CGM.getContext().getSourceManager();
3973     OptionalFileEntryRef mainFile = SM.getFileEntryRefForID(SM.getMainFileID());
3974     std::string path =
3975         (mainFile->getDir().getName() + "/" + mainFile->getName()).str();
3976     module.add(MakeConstantString(path, ".objc_source_file_name"));
3977     module.add(symtab);
3978 
3979     if (RuntimeVersion >= 10) {
3980       switch (CGM.getLangOpts().getGC()) {
3981       case LangOptions::GCOnly:
3982         module.addInt(IntTy, 2);
3983         break;
3984       case LangOptions::NonGC:
3985         if (CGM.getLangOpts().ObjCAutoRefCount)
3986           module.addInt(IntTy, 1);
3987         else
3988           module.addInt(IntTy, 0);
3989         break;
3990       case LangOptions::HybridGC:
3991         module.addInt(IntTy, 1);
3992         break;
3993       }
3994     }
3995 
3996     return module.finishAndCreateGlobal("", CGM.getPointerAlign());
3997   }();
3998 
3999   // Create the load function calling the runtime entry point with the module
4000   // structure
4001   llvm::Function * LoadFunction = llvm::Function::Create(
4002       llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
4003       llvm::GlobalValue::InternalLinkage, ".objc_load_function",
4004       &TheModule);
4005   llvm::BasicBlock *EntryBB =
4006       llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
4007   CGBuilderTy Builder(CGM, VMContext);
4008   Builder.SetInsertPoint(EntryBB);
4009 
4010   llvm::FunctionType *FT =
4011     llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
4012   llvm::FunctionCallee Register =
4013       CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
4014   Builder.CreateCall(Register, module);
4015 
4016   if (!ClassAliases.empty()) {
4017     llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
4018     llvm::FunctionType *RegisterAliasTy =
4019       llvm::FunctionType::get(Builder.getVoidTy(),
4020                               ArgTypes, false);
4021     llvm::Function *RegisterAlias = llvm::Function::Create(
4022       RegisterAliasTy,
4023       llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
4024       &TheModule);
4025     llvm::BasicBlock *AliasBB =
4026       llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
4027     llvm::BasicBlock *NoAliasBB =
4028       llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
4029 
4030     // Branch based on whether the runtime provided class_registerAlias_np()
4031     llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
4032             llvm::Constant::getNullValue(RegisterAlias->getType()));
4033     Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
4034 
4035     // The true branch (has alias registration function):
4036     Builder.SetInsertPoint(AliasBB);
4037     // Emit alias registration calls:
4038     for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
4039        iter != ClassAliases.end(); ++iter) {
4040        llvm::Constant *TheClass =
4041           TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
4042        if (TheClass) {
4043          Builder.CreateCall(RegisterAlias,
4044                             {TheClass, MakeConstantString(iter->second)});
4045        }
4046     }
4047     // Jump to end:
4048     Builder.CreateBr(NoAliasBB);
4049 
4050     // Missing alias registration function, just return from the function:
4051     Builder.SetInsertPoint(NoAliasBB);
4052   }
4053   Builder.CreateRetVoid();
4054 
4055   return LoadFunction;
4056 }
4057 
GenerateMethod(const ObjCMethodDecl * OMD,const ObjCContainerDecl * CD)4058 llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
4059                                           const ObjCContainerDecl *CD) {
4060   CodeGenTypes &Types = CGM.getTypes();
4061   llvm::FunctionType *MethodTy =
4062     Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
4063 
4064   bool isDirect = OMD->isDirectMethod();
4065   std::string FunctionName =
4066       getSymbolNameForMethod(OMD, /*include category*/ !isDirect);
4067 
4068   if (!isDirect)
4069     return llvm::Function::Create(MethodTy,
4070                                   llvm::GlobalVariable::InternalLinkage,
4071                                   FunctionName, &TheModule);
4072 
4073   auto *COMD = OMD->getCanonicalDecl();
4074   auto I = DirectMethodDefinitions.find(COMD);
4075   llvm::Function *OldFn = nullptr, *Fn = nullptr;
4076 
4077   if (I == DirectMethodDefinitions.end()) {
4078     auto *F =
4079         llvm::Function::Create(MethodTy, llvm::GlobalVariable::ExternalLinkage,
4080                                FunctionName, &TheModule);
4081     DirectMethodDefinitions.insert(std::make_pair(COMD, F));
4082     return F;
4083   }
4084 
4085   // Objective-C allows for the declaration and implementation types
4086   // to differ slightly.
4087   //
4088   // If we're being asked for the Function associated for a method
4089   // implementation, a previous value might have been cached
4090   // based on the type of the canonical declaration.
4091   //
4092   // If these do not match, then we'll replace this function with
4093   // a new one that has the proper type below.
4094   if (!OMD->getBody() || COMD->getReturnType() == OMD->getReturnType())
4095     return I->second;
4096 
4097   OldFn = I->second;
4098   Fn = llvm::Function::Create(MethodTy, llvm::GlobalValue::ExternalLinkage, "",
4099                               &CGM.getModule());
4100   Fn->takeName(OldFn);
4101   OldFn->replaceAllUsesWith(Fn);
4102   OldFn->eraseFromParent();
4103 
4104   // Replace the cached function in the map.
4105   I->second = Fn;
4106   return Fn;
4107 }
4108 
GenerateDirectMethodPrologue(CodeGenFunction & CGF,llvm::Function * Fn,const ObjCMethodDecl * OMD,const ObjCContainerDecl * CD)4109 void CGObjCGNU::GenerateDirectMethodPrologue(CodeGenFunction &CGF,
4110                                              llvm::Function *Fn,
4111                                              const ObjCMethodDecl *OMD,
4112                                              const ObjCContainerDecl *CD) {
4113   // GNU runtime doesn't support direct calls at this time
4114 }
4115 
GetPropertyGetFunction()4116 llvm::FunctionCallee CGObjCGNU::GetPropertyGetFunction() {
4117   return GetPropertyFn;
4118 }
4119 
GetPropertySetFunction()4120 llvm::FunctionCallee CGObjCGNU::GetPropertySetFunction() {
4121   return SetPropertyFn;
4122 }
4123 
GetOptimizedPropertySetFunction(bool atomic,bool copy)4124 llvm::FunctionCallee CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
4125                                                                 bool copy) {
4126   return nullptr;
4127 }
4128 
GetGetStructFunction()4129 llvm::FunctionCallee CGObjCGNU::GetGetStructFunction() {
4130   return GetStructPropertyFn;
4131 }
4132 
GetSetStructFunction()4133 llvm::FunctionCallee CGObjCGNU::GetSetStructFunction() {
4134   return SetStructPropertyFn;
4135 }
4136 
GetCppAtomicObjectGetFunction()4137 llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectGetFunction() {
4138   return nullptr;
4139 }
4140 
GetCppAtomicObjectSetFunction()4141 llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectSetFunction() {
4142   return nullptr;
4143 }
4144 
EnumerationMutationFunction()4145 llvm::FunctionCallee CGObjCGNU::EnumerationMutationFunction() {
4146   return EnumerationMutationFn;
4147 }
4148 
EmitSynchronizedStmt(CodeGenFunction & CGF,const ObjCAtSynchronizedStmt & S)4149 void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
4150                                      const ObjCAtSynchronizedStmt &S) {
4151   EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
4152 }
4153 
4154 
EmitTryStmt(CodeGenFunction & CGF,const ObjCAtTryStmt & S)4155 void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
4156                             const ObjCAtTryStmt &S) {
4157   // Unlike the Apple non-fragile runtimes, which also uses
4158   // unwind-based zero cost exceptions, the GNU Objective C runtime's
4159   // EH support isn't a veneer over C++ EH.  Instead, exception
4160   // objects are created by objc_exception_throw and destroyed by
4161   // the personality function; this avoids the need for bracketing
4162   // catch handlers with calls to __blah_begin_catch/__blah_end_catch
4163   // (or even _Unwind_DeleteException), but probably doesn't
4164   // interoperate very well with foreign exceptions.
4165   //
4166   // In Objective-C++ mode, we actually emit something equivalent to the C++
4167   // exception handler.
4168   EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
4169 }
4170 
EmitThrowStmt(CodeGenFunction & CGF,const ObjCAtThrowStmt & S,bool ClearInsertionPoint)4171 void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
4172                               const ObjCAtThrowStmt &S,
4173                               bool ClearInsertionPoint) {
4174   llvm::Value *ExceptionAsObject;
4175   bool isRethrow = false;
4176 
4177   if (const Expr *ThrowExpr = S.getThrowExpr()) {
4178     llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
4179     ExceptionAsObject = Exception;
4180   } else {
4181     assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
4182            "Unexpected rethrow outside @catch block.");
4183     ExceptionAsObject = CGF.ObjCEHValueStack.back();
4184     isRethrow = true;
4185   }
4186   if (isRethrow && (usesSEHExceptions || usesCxxExceptions)) {
4187     // For SEH, ExceptionAsObject may be undef, because the catch handler is
4188     // not passed it for catchalls and so it is not visible to the catch
4189     // funclet.  The real thrown object will still be live on the stack at this
4190     // point and will be rethrown.  If we are explicitly rethrowing the object
4191     // that was passed into the `@catch` block, then this code path is not
4192     // reached and we will instead call `objc_exception_throw` with an explicit
4193     // argument.
4194     llvm::CallBase *Throw = CGF.EmitRuntimeCallOrInvoke(ExceptionReThrowFn);
4195     Throw->setDoesNotReturn();
4196   } else {
4197     ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
4198     llvm::CallBase *Throw =
4199         CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
4200     Throw->setDoesNotReturn();
4201   }
4202   CGF.Builder.CreateUnreachable();
4203   if (ClearInsertionPoint)
4204     CGF.Builder.ClearInsertionPoint();
4205 }
4206 
EmitObjCWeakRead(CodeGenFunction & CGF,Address AddrWeakObj)4207 llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
4208                                           Address AddrWeakObj) {
4209   CGBuilderTy &B = CGF.Builder;
4210   return B.CreateCall(WeakReadFn,
4211                       EnforceType(B, AddrWeakObj.getPointer(), PtrToIdTy));
4212 }
4213 
EmitObjCWeakAssign(CodeGenFunction & CGF,llvm::Value * src,Address dst)4214 void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
4215                                    llvm::Value *src, Address dst) {
4216   CGBuilderTy &B = CGF.Builder;
4217   src = EnforceType(B, src, IdTy);
4218   llvm::Value *dstVal = EnforceType(B, dst.getPointer(), PtrToIdTy);
4219   B.CreateCall(WeakAssignFn, {src, dstVal});
4220 }
4221 
EmitObjCGlobalAssign(CodeGenFunction & CGF,llvm::Value * src,Address dst,bool threadlocal)4222 void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
4223                                      llvm::Value *src, Address dst,
4224                                      bool threadlocal) {
4225   CGBuilderTy &B = CGF.Builder;
4226   src = EnforceType(B, src, IdTy);
4227   llvm::Value *dstVal = EnforceType(B, dst.getPointer(), PtrToIdTy);
4228   // FIXME. Add threadloca assign API
4229   assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
4230   B.CreateCall(GlobalAssignFn, {src, dstVal});
4231 }
4232 
EmitObjCIvarAssign(CodeGenFunction & CGF,llvm::Value * src,Address dst,llvm::Value * ivarOffset)4233 void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
4234                                    llvm::Value *src, Address dst,
4235                                    llvm::Value *ivarOffset) {
4236   CGBuilderTy &B = CGF.Builder;
4237   src = EnforceType(B, src, IdTy);
4238   llvm::Value *dstVal = EnforceType(B, dst.getPointer(), IdTy);
4239   B.CreateCall(IvarAssignFn, {src, dstVal, ivarOffset});
4240 }
4241 
EmitObjCStrongCastAssign(CodeGenFunction & CGF,llvm::Value * src,Address dst)4242 void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
4243                                          llvm::Value *src, Address dst) {
4244   CGBuilderTy &B = CGF.Builder;
4245   src = EnforceType(B, src, IdTy);
4246   llvm::Value *dstVal = EnforceType(B, dst.getPointer(), PtrToIdTy);
4247   B.CreateCall(StrongCastAssignFn, {src, dstVal});
4248 }
4249 
EmitGCMemmoveCollectable(CodeGenFunction & CGF,Address DestPtr,Address SrcPtr,llvm::Value * Size)4250 void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
4251                                          Address DestPtr,
4252                                          Address SrcPtr,
4253                                          llvm::Value *Size) {
4254   CGBuilderTy &B = CGF.Builder;
4255   llvm::Value *DestPtrVal = EnforceType(B, DestPtr.getPointer(), PtrTy);
4256   llvm::Value *SrcPtrVal = EnforceType(B, SrcPtr.getPointer(), PtrTy);
4257 
4258   B.CreateCall(MemMoveFn, {DestPtrVal, SrcPtrVal, Size});
4259 }
4260 
ObjCIvarOffsetVariable(const ObjCInterfaceDecl * ID,const ObjCIvarDecl * Ivar)4261 llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
4262                               const ObjCInterfaceDecl *ID,
4263                               const ObjCIvarDecl *Ivar) {
4264   const std::string Name = GetIVarOffsetVariableName(ID, Ivar);
4265   // Emit the variable and initialize it with what we think the correct value
4266   // is.  This allows code compiled with non-fragile ivars to work correctly
4267   // when linked against code which isn't (most of the time).
4268   llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
4269   if (!IvarOffsetPointer)
4270     IvarOffsetPointer = new llvm::GlobalVariable(
4271         TheModule, llvm::PointerType::getUnqual(VMContext), false,
4272         llvm::GlobalValue::ExternalLinkage, nullptr, Name);
4273   return IvarOffsetPointer;
4274 }
4275 
EmitObjCValueForIvar(CodeGenFunction & CGF,QualType ObjectTy,llvm::Value * BaseValue,const ObjCIvarDecl * Ivar,unsigned CVRQualifiers)4276 LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
4277                                        QualType ObjectTy,
4278                                        llvm::Value *BaseValue,
4279                                        const ObjCIvarDecl *Ivar,
4280                                        unsigned CVRQualifiers) {
4281   const ObjCInterfaceDecl *ID =
4282     ObjectTy->castAs<ObjCObjectType>()->getInterface();
4283   return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4284                                   EmitIvarOffset(CGF, ID, Ivar));
4285 }
4286 
FindIvarInterface(ASTContext & Context,const ObjCInterfaceDecl * OID,const ObjCIvarDecl * OIVD)4287 static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
4288                                                   const ObjCInterfaceDecl *OID,
4289                                                   const ObjCIvarDecl *OIVD) {
4290   for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
4291        next = next->getNextIvar()) {
4292     if (OIVD == next)
4293       return OID;
4294   }
4295 
4296   // Otherwise check in the super class.
4297   if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
4298     return FindIvarInterface(Context, Super, OIVD);
4299 
4300   return nullptr;
4301 }
4302 
EmitIvarOffset(CodeGenFunction & CGF,const ObjCInterfaceDecl * Interface,const ObjCIvarDecl * Ivar)4303 llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
4304                          const ObjCInterfaceDecl *Interface,
4305                          const ObjCIvarDecl *Ivar) {
4306   if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
4307     Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
4308 
4309     // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
4310     // and ExternalLinkage, so create a reference to the ivar global and rely on
4311     // the definition being created as part of GenerateClass.
4312     if (RuntimeVersion < 10 ||
4313         CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
4314       return CGF.Builder.CreateZExtOrBitCast(
4315           CGF.Builder.CreateAlignedLoad(
4316               Int32Ty,
4317               CGF.Builder.CreateAlignedLoad(
4318                   llvm::PointerType::getUnqual(VMContext),
4319                   ObjCIvarOffsetVariable(Interface, Ivar),
4320                   CGF.getPointerAlign(), "ivar"),
4321               CharUnits::fromQuantity(4)),
4322           PtrDiffTy);
4323     std::string name = "__objc_ivar_offset_value_" +
4324       Interface->getNameAsString() +"." + Ivar->getNameAsString();
4325     CharUnits Align = CGM.getIntAlign();
4326     llvm::Value *Offset = TheModule.getGlobalVariable(name);
4327     if (!Offset) {
4328       auto GV = new llvm::GlobalVariable(TheModule, IntTy,
4329           false, llvm::GlobalValue::LinkOnceAnyLinkage,
4330           llvm::Constant::getNullValue(IntTy), name);
4331       GV->setAlignment(Align.getAsAlign());
4332       Offset = GV;
4333     }
4334     Offset = CGF.Builder.CreateAlignedLoad(IntTy, Offset, Align);
4335     if (Offset->getType() != PtrDiffTy)
4336       Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
4337     return Offset;
4338   }
4339   uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
4340   return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
4341 }
4342 
4343 CGObjCRuntime *
CreateGNUObjCRuntime(CodeGenModule & CGM)4344 clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
4345   auto Runtime = CGM.getLangOpts().ObjCRuntime;
4346   switch (Runtime.getKind()) {
4347   case ObjCRuntime::GNUstep:
4348     if (Runtime.getVersion() >= VersionTuple(2, 0))
4349       return new CGObjCGNUstep2(CGM);
4350     return new CGObjCGNUstep(CGM);
4351 
4352   case ObjCRuntime::GCC:
4353     return new CGObjCGCC(CGM);
4354 
4355   case ObjCRuntime::ObjFW:
4356     return new CGObjCObjFW(CGM);
4357 
4358   case ObjCRuntime::FragileMacOSX:
4359   case ObjCRuntime::MacOSX:
4360   case ObjCRuntime::iOS:
4361   case ObjCRuntime::WatchOS:
4362     llvm_unreachable("these runtimes are not GNU runtimes");
4363   }
4364   llvm_unreachable("bad runtime");
4365 }
4366