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