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