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