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